babylon.max.js 3.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. var KeyboardEventTypes = (function () {
  20. function KeyboardEventTypes() {
  21. }
  22. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  23. get: function () {
  24. return KeyboardEventTypes._KEYDOWN;
  25. },
  26. enumerable: true,
  27. configurable: true
  28. });
  29. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  30. get: function () {
  31. return KeyboardEventTypes._KEYUP;
  32. },
  33. enumerable: true,
  34. configurable: true
  35. });
  36. KeyboardEventTypes._KEYDOWN = 0x01;
  37. KeyboardEventTypes._KEYUP = 0x02;
  38. return KeyboardEventTypes;
  39. }());
  40. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  41. var KeyboardInfo = (function () {
  42. function KeyboardInfo(type, event) {
  43. this.type = type;
  44. this.event = event;
  45. }
  46. return KeyboardInfo;
  47. }());
  48. BABYLON.KeyboardInfo = KeyboardInfo;
  49. /**
  50. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  51. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  52. */
  53. var KeyboardInfoPre = (function (_super) {
  54. __extends(KeyboardInfoPre, _super);
  55. function KeyboardInfoPre(type, event) {
  56. var _this = _super.call(this, type, event) || this;
  57. _this.skipOnPointerObservable = false;
  58. return _this;
  59. }
  60. return KeyboardInfoPre;
  61. }(KeyboardInfo));
  62. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  63. })(BABYLON || (BABYLON = {}));
  64. //# sourceMappingURL=babylon.keyboardEvents.js.map
  65. var BABYLON;
  66. (function (BABYLON) {
  67. var PointerEventTypes = (function () {
  68. function PointerEventTypes() {
  69. }
  70. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  71. get: function () {
  72. return PointerEventTypes._POINTERDOWN;
  73. },
  74. enumerable: true,
  75. configurable: true
  76. });
  77. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  78. get: function () {
  79. return PointerEventTypes._POINTERUP;
  80. },
  81. enumerable: true,
  82. configurable: true
  83. });
  84. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  85. get: function () {
  86. return PointerEventTypes._POINTERMOVE;
  87. },
  88. enumerable: true,
  89. configurable: true
  90. });
  91. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  92. get: function () {
  93. return PointerEventTypes._POINTERWHEEL;
  94. },
  95. enumerable: true,
  96. configurable: true
  97. });
  98. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  99. get: function () {
  100. return PointerEventTypes._POINTERPICK;
  101. },
  102. enumerable: true,
  103. configurable: true
  104. });
  105. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  106. get: function () {
  107. return PointerEventTypes._POINTERTAP;
  108. },
  109. enumerable: true,
  110. configurable: true
  111. });
  112. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  113. get: function () {
  114. return PointerEventTypes._POINTERDOUBLETAP;
  115. },
  116. enumerable: true,
  117. configurable: true
  118. });
  119. PointerEventTypes._POINTERDOWN = 0x01;
  120. PointerEventTypes._POINTERUP = 0x02;
  121. PointerEventTypes._POINTERMOVE = 0x04;
  122. PointerEventTypes._POINTERWHEEL = 0x08;
  123. PointerEventTypes._POINTERPICK = 0x10;
  124. PointerEventTypes._POINTERTAP = 0x20;
  125. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  126. return PointerEventTypes;
  127. }());
  128. BABYLON.PointerEventTypes = PointerEventTypes;
  129. var PointerInfoBase = (function () {
  130. function PointerInfoBase(type, event) {
  131. this.type = type;
  132. this.event = event;
  133. }
  134. return PointerInfoBase;
  135. }());
  136. BABYLON.PointerInfoBase = PointerInfoBase;
  137. /**
  138. * This class is used to store pointer related info for the onPrePointerObservable event.
  139. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  140. */
  141. var PointerInfoPre = (function (_super) {
  142. __extends(PointerInfoPre, _super);
  143. function PointerInfoPre(type, event, localX, localY) {
  144. var _this = _super.call(this, type, event) || this;
  145. _this.skipOnPointerObservable = false;
  146. _this.localPosition = new BABYLON.Vector2(localX, localY);
  147. return _this;
  148. }
  149. return PointerInfoPre;
  150. }(PointerInfoBase));
  151. BABYLON.PointerInfoPre = PointerInfoPre;
  152. /**
  153. * This type contains all the data related to a pointer event in Babylon.js.
  154. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  155. */
  156. var PointerInfo = (function (_super) {
  157. __extends(PointerInfo, _super);
  158. function PointerInfo(type, event, pickInfo) {
  159. var _this = _super.call(this, type, event) || this;
  160. _this.pickInfo = pickInfo;
  161. return _this;
  162. }
  163. return PointerInfo;
  164. }(PointerInfoBase));
  165. BABYLON.PointerInfo = PointerInfo;
  166. })(BABYLON || (BABYLON = {}));
  167. //# sourceMappingURL=babylon.pointerEvents.js.map
  168. var BABYLON;
  169. (function (BABYLON) {
  170. BABYLON.ToGammaSpace = 1 / 2.2;
  171. BABYLON.ToLinearSpace = 2.2;
  172. BABYLON.Epsilon = 0.001;
  173. var Color3 = (function () {
  174. /**
  175. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  176. */
  177. function Color3(r, g, b) {
  178. if (r === void 0) { r = 0; }
  179. if (g === void 0) { g = 0; }
  180. if (b === void 0) { b = 0; }
  181. this.r = r;
  182. this.g = g;
  183. this.b = b;
  184. }
  185. /**
  186. * Returns a string with the Color3 current values.
  187. */
  188. Color3.prototype.toString = function () {
  189. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  190. };
  191. /**
  192. * Returns the string "Color3".
  193. */
  194. Color3.prototype.getClassName = function () {
  195. return "Color3";
  196. };
  197. /**
  198. * Returns the Color3 hash code.
  199. */
  200. Color3.prototype.getHashCode = function () {
  201. var hash = this.r || 0;
  202. hash = (hash * 397) ^ (this.g || 0);
  203. hash = (hash * 397) ^ (this.b || 0);
  204. return hash;
  205. };
  206. // Operators
  207. /**
  208. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  209. * Returns the Color3.
  210. */
  211. Color3.prototype.toArray = function (array, index) {
  212. if (index === undefined) {
  213. index = 0;
  214. }
  215. array[index] = this.r;
  216. array[index + 1] = this.g;
  217. array[index + 2] = this.b;
  218. return this;
  219. };
  220. /**
  221. * Returns a new Color4 object from the current Color3 and the passed alpha.
  222. */
  223. Color3.prototype.toColor4 = function (alpha) {
  224. if (alpha === void 0) { alpha = 1; }
  225. return new Color4(this.r, this.g, this.b, alpha);
  226. };
  227. /**
  228. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  229. */
  230. Color3.prototype.asArray = function () {
  231. var result = [];
  232. this.toArray(result, 0);
  233. return result;
  234. };
  235. /**
  236. * Returns the luminance value (float).
  237. */
  238. Color3.prototype.toLuminance = function () {
  239. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  240. };
  241. /**
  242. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  243. * Returns this new object.
  244. */
  245. Color3.prototype.multiply = function (otherColor) {
  246. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  247. };
  248. /**
  249. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  250. * Returns the current Color3.
  251. */
  252. Color3.prototype.multiplyToRef = function (otherColor, result) {
  253. result.r = this.r * otherColor.r;
  254. result.g = this.g * otherColor.g;
  255. result.b = this.b * otherColor.b;
  256. return this;
  257. };
  258. /**
  259. * Boolean : True if the rgb values are equal to the passed ones.
  260. */
  261. Color3.prototype.equals = function (otherColor) {
  262. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  263. };
  264. /**
  265. * Boolean : True if the rgb values are equal to the passed ones.
  266. */
  267. Color3.prototype.equalsFloats = function (r, g, b) {
  268. return this.r === r && this.g === g && this.b === b;
  269. };
  270. /**
  271. * Multiplies in place each rgb value by scale.
  272. * Returns the updated Color3.
  273. */
  274. Color3.prototype.scale = function (scale) {
  275. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  276. };
  277. /**
  278. * Multiplies the rgb values by scale and stores the result into "result".
  279. * Returns the unmodified current Color3.
  280. */
  281. Color3.prototype.scaleToRef = function (scale, result) {
  282. result.r = this.r * scale;
  283. result.g = this.g * scale;
  284. result.b = this.b * scale;
  285. return this;
  286. };
  287. /**
  288. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  289. */
  290. Color3.prototype.add = function (otherColor) {
  291. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  292. };
  293. /**
  294. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  295. * Returns the unmodified current Color3.
  296. */
  297. Color3.prototype.addToRef = function (otherColor, result) {
  298. result.r = this.r + otherColor.r;
  299. result.g = this.g + otherColor.g;
  300. result.b = this.b + otherColor.b;
  301. return this;
  302. };
  303. /**
  304. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  305. */
  306. Color3.prototype.subtract = function (otherColor) {
  307. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  308. };
  309. /**
  310. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  311. * Returns the unmodified current Color3.
  312. */
  313. Color3.prototype.subtractToRef = function (otherColor, result) {
  314. result.r = this.r - otherColor.r;
  315. result.g = this.g - otherColor.g;
  316. result.b = this.b - otherColor.b;
  317. return this;
  318. };
  319. /**
  320. * Returns a new Color3 copied the current one.
  321. */
  322. Color3.prototype.clone = function () {
  323. return new Color3(this.r, this.g, this.b);
  324. };
  325. /**
  326. * Copies the rgb values from the source in the current Color3.
  327. * Returns the updated Color3.
  328. */
  329. Color3.prototype.copyFrom = function (source) {
  330. this.r = source.r;
  331. this.g = source.g;
  332. this.b = source.b;
  333. return this;
  334. };
  335. /**
  336. * Updates the Color3 rgb values from the passed floats.
  337. * Returns the Color3.
  338. */
  339. Color3.prototype.copyFromFloats = function (r, g, b) {
  340. this.r = r;
  341. this.g = g;
  342. this.b = b;
  343. return this;
  344. };
  345. /**
  346. * Updates the Color3 rgb values from the passed floats.
  347. * Returns the Color3.
  348. */
  349. Color3.prototype.set = function (r, g, b) {
  350. return this.copyFromFloats(r, g, b);
  351. };
  352. /**
  353. * Returns the Color3 hexadecimal code as a string.
  354. */
  355. Color3.prototype.toHexString = function () {
  356. var intR = (this.r * 255) | 0;
  357. var intG = (this.g * 255) | 0;
  358. var intB = (this.b * 255) | 0;
  359. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  360. };
  361. /**
  362. * Returns a new Color3 converted to linear space.
  363. */
  364. Color3.prototype.toLinearSpace = function () {
  365. var convertedColor = new Color3();
  366. this.toLinearSpaceToRef(convertedColor);
  367. return convertedColor;
  368. };
  369. /**
  370. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  371. * Returns the unmodified Color3.
  372. */
  373. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  374. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  375. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  376. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  377. return this;
  378. };
  379. /**
  380. * Returns a new Color3 converted to gamma space.
  381. */
  382. Color3.prototype.toGammaSpace = function () {
  383. var convertedColor = new Color3();
  384. this.toGammaSpaceToRef(convertedColor);
  385. return convertedColor;
  386. };
  387. /**
  388. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  389. * Returns the unmodified Color3.
  390. */
  391. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  392. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  393. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  394. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  395. return this;
  396. };
  397. // Statics
  398. /**
  399. * Creates a new Color3 from the string containing valid hexadecimal values.
  400. */
  401. Color3.FromHexString = function (hex) {
  402. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  403. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  404. return new Color3(0, 0, 0);
  405. }
  406. var r = parseInt(hex.substring(1, 3), 16);
  407. var g = parseInt(hex.substring(3, 5), 16);
  408. var b = parseInt(hex.substring(5, 7), 16);
  409. return Color3.FromInts(r, g, b);
  410. };
  411. /**
  412. * Creates a new Vector3 from the startind index of the passed array.
  413. */
  414. Color3.FromArray = function (array, offset) {
  415. if (offset === void 0) { offset = 0; }
  416. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  417. };
  418. /**
  419. * Creates a new Color3 from integer values ( < 256).
  420. */
  421. Color3.FromInts = function (r, g, b) {
  422. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  423. };
  424. /**
  425. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  426. */
  427. Color3.Lerp = function (start, end, amount) {
  428. var r = start.r + ((end.r - start.r) * amount);
  429. var g = start.g + ((end.g - start.g) * amount);
  430. var b = start.b + ((end.b - start.b) * amount);
  431. return new Color3(r, g, b);
  432. };
  433. Color3.Red = function () { return new Color3(1, 0, 0); };
  434. Color3.Green = function () { return new Color3(0, 1, 0); };
  435. Color3.Blue = function () { return new Color3(0, 0, 1); };
  436. Color3.Black = function () { return new Color3(0, 0, 0); };
  437. Color3.White = function () { return new Color3(1, 1, 1); };
  438. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  439. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  440. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  441. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  442. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  443. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  444. return Color3;
  445. }());
  446. BABYLON.Color3 = Color3;
  447. var Color4 = (function () {
  448. /**
  449. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  450. */
  451. function Color4(r, g, b, a) {
  452. if (r === void 0) { r = 0; }
  453. if (g === void 0) { g = 0; }
  454. if (b === void 0) { b = 0; }
  455. if (a === void 0) { a = 1; }
  456. this.r = r;
  457. this.g = g;
  458. this.b = b;
  459. this.a = a;
  460. }
  461. // Operators
  462. /**
  463. * Adds in place the passed Color4 values to the current Color4.
  464. * Returns the updated Color4.
  465. */
  466. Color4.prototype.addInPlace = function (right) {
  467. this.r += right.r;
  468. this.g += right.g;
  469. this.b += right.b;
  470. this.a += right.a;
  471. return this;
  472. };
  473. /**
  474. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  475. */
  476. Color4.prototype.asArray = function () {
  477. var result = [];
  478. this.toArray(result, 0);
  479. return result;
  480. };
  481. /**
  482. * Stores from the starting index in the passed array the Color4 successive values.
  483. * Returns the Color4.
  484. */
  485. Color4.prototype.toArray = function (array, index) {
  486. if (index === undefined) {
  487. index = 0;
  488. }
  489. array[index] = this.r;
  490. array[index + 1] = this.g;
  491. array[index + 2] = this.b;
  492. array[index + 3] = this.a;
  493. return this;
  494. };
  495. /**
  496. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  497. */
  498. Color4.prototype.add = function (right) {
  499. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  500. };
  501. /**
  502. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  503. */
  504. Color4.prototype.subtract = function (right) {
  505. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  506. };
  507. /**
  508. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  509. * Returns the Color4.
  510. */
  511. Color4.prototype.subtractToRef = function (right, result) {
  512. result.r = this.r - right.r;
  513. result.g = this.g - right.g;
  514. result.b = this.b - right.b;
  515. result.a = this.a - right.a;
  516. return this;
  517. };
  518. /**
  519. * Creates a new Color4 with the current Color4 values multiplied by scale.
  520. */
  521. Color4.prototype.scale = function (scale) {
  522. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  523. };
  524. /**
  525. * Multiplies the current Color4 values by scale and stores the result in "result".
  526. * Returns the Color4.
  527. */
  528. Color4.prototype.scaleToRef = function (scale, result) {
  529. result.r = this.r * scale;
  530. result.g = this.g * scale;
  531. result.b = this.b * scale;
  532. result.a = this.a * scale;
  533. return this;
  534. };
  535. /**
  536. * Multipy an RGBA Color4 value by another and return a new Color4 object
  537. * @param color The Color4 (RGBA) value to multiply by
  538. * @returns A new Color4.
  539. */
  540. Color4.prototype.multiply = function (color) {
  541. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  542. };
  543. /**
  544. * Multipy an RGBA Color4 value by another and push the result in a reference value
  545. * @param color The Color4 (RGBA) value to multiply by
  546. * @param result The Color4 (RGBA) to fill the result in
  547. * @returns the result Color4.
  548. */
  549. Color4.prototype.multiplyToRef = function (color, result) {
  550. result.r = this.r * color.r;
  551. result.g = this.g * color.g;
  552. result.b = this.b * color.b;
  553. result.a = this.a * color.a;
  554. return result;
  555. };
  556. /**
  557. * Returns a string with the Color4 values.
  558. */
  559. Color4.prototype.toString = function () {
  560. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  561. };
  562. /**
  563. * Returns the string "Color4"
  564. */
  565. Color4.prototype.getClassName = function () {
  566. return "Color4";
  567. };
  568. /**
  569. * Return the Color4 hash code as a number.
  570. */
  571. Color4.prototype.getHashCode = function () {
  572. var hash = this.r || 0;
  573. hash = (hash * 397) ^ (this.g || 0);
  574. hash = (hash * 397) ^ (this.b || 0);
  575. hash = (hash * 397) ^ (this.a || 0);
  576. return hash;
  577. };
  578. /**
  579. * Creates a new Color4 copied from the current one.
  580. */
  581. Color4.prototype.clone = function () {
  582. return new Color4(this.r, this.g, this.b, this.a);
  583. };
  584. /**
  585. * Copies the passed Color4 values into the current one.
  586. * Returns the updated Color4.
  587. */
  588. Color4.prototype.copyFrom = function (source) {
  589. this.r = source.r;
  590. this.g = source.g;
  591. this.b = source.b;
  592. this.a = source.a;
  593. return this;
  594. };
  595. /**
  596. * Copies the passed float values into the current one.
  597. * Returns the updated Color4.
  598. */
  599. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  600. this.r = r;
  601. this.g = g;
  602. this.b = b;
  603. this.a = a;
  604. return this;
  605. };
  606. /**
  607. * Copies the passed float values into the current one.
  608. * Returns the updated Color4.
  609. */
  610. Color4.prototype.set = function (r, g, b, a) {
  611. return this.copyFromFloats(r, g, b, a);
  612. };
  613. /**
  614. * Returns a string containing the hexadecimal Color4 code.
  615. */
  616. Color4.prototype.toHexString = function () {
  617. var intR = (this.r * 255) | 0;
  618. var intG = (this.g * 255) | 0;
  619. var intB = (this.b * 255) | 0;
  620. var intA = (this.a * 255) | 0;
  621. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  622. };
  623. /**
  624. * Returns a new Color4 converted to linear space.
  625. */
  626. Color4.prototype.toLinearSpace = function () {
  627. var convertedColor = new Color4();
  628. this.toLinearSpaceToRef(convertedColor);
  629. return convertedColor;
  630. };
  631. /**
  632. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  633. * Returns the unmodified Color4.
  634. */
  635. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  636. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  637. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  638. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  639. convertedColor.a = this.a;
  640. return this;
  641. };
  642. /**
  643. * Returns a new Color4 converted to gamma space.
  644. */
  645. Color4.prototype.toGammaSpace = function () {
  646. var convertedColor = new Color4();
  647. this.toGammaSpaceToRef(convertedColor);
  648. return convertedColor;
  649. };
  650. /**
  651. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  652. * Returns the unmodified Color4.
  653. */
  654. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  655. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  656. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  657. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  658. convertedColor.a = this.a;
  659. return this;
  660. };
  661. // Statics
  662. /**
  663. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  664. */
  665. Color4.FromHexString = function (hex) {
  666. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  667. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  668. return new Color4(0.0, 0.0, 0.0, 0.0);
  669. }
  670. var r = parseInt(hex.substring(1, 3), 16);
  671. var g = parseInt(hex.substring(3, 5), 16);
  672. var b = parseInt(hex.substring(5, 7), 16);
  673. var a = parseInt(hex.substring(7, 9), 16);
  674. return Color4.FromInts(r, g, b, a);
  675. };
  676. /**
  677. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  678. */
  679. Color4.Lerp = function (left, right, amount) {
  680. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  681. Color4.LerpToRef(left, right, amount, result);
  682. return result;
  683. };
  684. /**
  685. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  686. */
  687. Color4.LerpToRef = function (left, right, amount, result) {
  688. result.r = left.r + (right.r - left.r) * amount;
  689. result.g = left.g + (right.g - left.g) * amount;
  690. result.b = left.b + (right.b - left.b) * amount;
  691. result.a = left.a + (right.a - left.a) * amount;
  692. };
  693. /**
  694. * Creates a new Color4 from the starting index element of the passed array.
  695. */
  696. Color4.FromArray = function (array, offset) {
  697. if (offset === void 0) { offset = 0; }
  698. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  699. };
  700. /**
  701. * Creates a new Color4 from the passed integers ( < 256 ).
  702. */
  703. Color4.FromInts = function (r, g, b, a) {
  704. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  705. };
  706. Color4.CheckColors4 = function (colors, count) {
  707. // Check if color3 was used
  708. if (colors.length === count * 3) {
  709. var colors4 = [];
  710. for (var index = 0; index < colors.length; index += 3) {
  711. var newIndex = (index / 3) * 4;
  712. colors4[newIndex] = colors[index];
  713. colors4[newIndex + 1] = colors[index + 1];
  714. colors4[newIndex + 2] = colors[index + 2];
  715. colors4[newIndex + 3] = 1.0;
  716. }
  717. return colors4;
  718. }
  719. return colors;
  720. };
  721. return Color4;
  722. }());
  723. BABYLON.Color4 = Color4;
  724. var Vector2 = (function () {
  725. /**
  726. * Creates a new Vector2 from the passed x and y coordinates.
  727. */
  728. function Vector2(x, y) {
  729. this.x = x;
  730. this.y = y;
  731. }
  732. /**
  733. * Returns a string with the Vector2 coordinates.
  734. */
  735. Vector2.prototype.toString = function () {
  736. return "{X: " + this.x + " Y:" + this.y + "}";
  737. };
  738. /**
  739. * Returns the string "Vector2"
  740. */
  741. Vector2.prototype.getClassName = function () {
  742. return "Vector2";
  743. };
  744. /**
  745. * Returns the Vector2 hash code as a number.
  746. */
  747. Vector2.prototype.getHashCode = function () {
  748. var hash = this.x || 0;
  749. hash = (hash * 397) ^ (this.y || 0);
  750. return hash;
  751. };
  752. // Operators
  753. /**
  754. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  755. * Returns the Vector2.
  756. */
  757. Vector2.prototype.toArray = function (array, index) {
  758. if (index === void 0) { index = 0; }
  759. array[index] = this.x;
  760. array[index + 1] = this.y;
  761. return this;
  762. };
  763. /**
  764. * Returns a new array with 2 elements : the Vector2 coordinates.
  765. */
  766. Vector2.prototype.asArray = function () {
  767. var result = [];
  768. this.toArray(result, 0);
  769. return result;
  770. };
  771. /**
  772. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  773. * Returns the updated Vector2.
  774. */
  775. Vector2.prototype.copyFrom = function (source) {
  776. this.x = source.x;
  777. this.y = source.y;
  778. return this;
  779. };
  780. /**
  781. * Sets the Vector2 coordinates with the passed floats.
  782. * Returns the updated Vector2.
  783. */
  784. Vector2.prototype.copyFromFloats = function (x, y) {
  785. this.x = x;
  786. this.y = y;
  787. return this;
  788. };
  789. /**
  790. * Sets the Vector2 coordinates with the passed floats.
  791. * Returns the updated Vector2.
  792. */
  793. Vector2.prototype.set = function (x, y) {
  794. return this.copyFromFloats(x, y);
  795. };
  796. /**
  797. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  798. */
  799. Vector2.prototype.add = function (otherVector) {
  800. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  801. };
  802. /**
  803. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  804. * Returns the Vector2.
  805. */
  806. Vector2.prototype.addToRef = function (otherVector, result) {
  807. result.x = this.x + otherVector.x;
  808. result.y = this.y + otherVector.y;
  809. return this;
  810. };
  811. /**
  812. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  813. * Returns the updated Vector2.
  814. */
  815. Vector2.prototype.addInPlace = function (otherVector) {
  816. this.x += otherVector.x;
  817. this.y += otherVector.y;
  818. return this;
  819. };
  820. /**
  821. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  822. */
  823. Vector2.prototype.addVector3 = function (otherVector) {
  824. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  825. };
  826. /**
  827. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  828. */
  829. Vector2.prototype.subtract = function (otherVector) {
  830. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  831. };
  832. /**
  833. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  834. * Returns the Vector2.
  835. */
  836. Vector2.prototype.subtractToRef = function (otherVector, result) {
  837. result.x = this.x - otherVector.x;
  838. result.y = this.y - otherVector.y;
  839. return this;
  840. };
  841. /**
  842. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  843. * Returns the updated Vector2.
  844. */
  845. Vector2.prototype.subtractInPlace = function (otherVector) {
  846. this.x -= otherVector.x;
  847. this.y -= otherVector.y;
  848. return this;
  849. };
  850. /**
  851. * Multiplies in place the current Vector2 coordinates by the passed ones.
  852. * Returns the updated Vector2.
  853. */
  854. Vector2.prototype.multiplyInPlace = function (otherVector) {
  855. this.x *= otherVector.x;
  856. this.y *= otherVector.y;
  857. return this;
  858. };
  859. /**
  860. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  861. */
  862. Vector2.prototype.multiply = function (otherVector) {
  863. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  864. };
  865. /**
  866. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  867. * Returns the Vector2.
  868. */
  869. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  870. result.x = this.x * otherVector.x;
  871. result.y = this.y * otherVector.y;
  872. return this;
  873. };
  874. /**
  875. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  876. */
  877. Vector2.prototype.multiplyByFloats = function (x, y) {
  878. return new Vector2(this.x * x, this.y * y);
  879. };
  880. /**
  881. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  882. */
  883. Vector2.prototype.divide = function (otherVector) {
  884. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  885. };
  886. /**
  887. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  888. * Returns the Vector2.
  889. */
  890. Vector2.prototype.divideToRef = function (otherVector, result) {
  891. result.x = this.x / otherVector.x;
  892. result.y = this.y / otherVector.y;
  893. return this;
  894. };
  895. /**
  896. * Returns a new Vector2 with current Vector2 negated coordinates.
  897. */
  898. Vector2.prototype.negate = function () {
  899. return new Vector2(-this.x, -this.y);
  900. };
  901. /**
  902. * Multiply the Vector2 coordinates by scale.
  903. * Returns the updated Vector2.
  904. */
  905. Vector2.prototype.scaleInPlace = function (scale) {
  906. this.x *= scale;
  907. this.y *= scale;
  908. return this;
  909. };
  910. /**
  911. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  912. */
  913. Vector2.prototype.scale = function (scale) {
  914. return new Vector2(this.x * scale, this.y * scale);
  915. };
  916. /**
  917. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  918. */
  919. Vector2.prototype.equals = function (otherVector) {
  920. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  921. };
  922. /**
  923. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  924. */
  925. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  926. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  927. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  928. };
  929. // Properties
  930. /**
  931. * Returns the vector length (float).
  932. */
  933. Vector2.prototype.length = function () {
  934. return Math.sqrt(this.x * this.x + this.y * this.y);
  935. };
  936. /**
  937. * Returns the vector squared length (float);
  938. */
  939. Vector2.prototype.lengthSquared = function () {
  940. return (this.x * this.x + this.y * this.y);
  941. };
  942. // Methods
  943. /**
  944. * Normalize the vector.
  945. * Returns the updated Vector2.
  946. */
  947. Vector2.prototype.normalize = function () {
  948. var len = this.length();
  949. if (len === 0)
  950. return this;
  951. var num = 1.0 / len;
  952. this.x *= num;
  953. this.y *= num;
  954. return this;
  955. };
  956. /**
  957. * Returns a new Vector2 copied from the Vector2.
  958. */
  959. Vector2.prototype.clone = function () {
  960. return new Vector2(this.x, this.y);
  961. };
  962. // Statics
  963. /**
  964. * Returns a new Vector2(0, 0)
  965. */
  966. Vector2.Zero = function () {
  967. return new Vector2(0, 0);
  968. };
  969. /**
  970. * Returns a new Vector2(1, 1)
  971. */
  972. Vector2.One = function () {
  973. return new Vector2(1, 1);
  974. };
  975. /**
  976. * Returns a new Vector2 set from the passed index element of the passed array.
  977. */
  978. Vector2.FromArray = function (array, offset) {
  979. if (offset === void 0) { offset = 0; }
  980. return new Vector2(array[offset], array[offset + 1]);
  981. };
  982. /**
  983. * Sets "result" from the passed index element of the passed array.
  984. */
  985. Vector2.FromArrayToRef = function (array, offset, result) {
  986. result.x = array[offset];
  987. result.y = array[offset + 1];
  988. };
  989. /**
  990. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  991. */
  992. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  993. var squared = amount * amount;
  994. var cubed = amount * squared;
  995. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  996. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  997. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  998. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  999. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1000. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1001. return new Vector2(x, y);
  1002. };
  1003. /**
  1004. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  1005. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1006. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1007. */
  1008. Vector2.Clamp = function (value, min, max) {
  1009. var x = value.x;
  1010. x = (x > max.x) ? max.x : x;
  1011. x = (x < min.x) ? min.x : x;
  1012. var y = value.y;
  1013. y = (y > max.y) ? max.y : y;
  1014. y = (y < min.y) ? min.y : y;
  1015. return new Vector2(x, y);
  1016. };
  1017. /**
  1018. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1019. */
  1020. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1021. var squared = amount * amount;
  1022. var cubed = amount * squared;
  1023. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1024. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1025. var part3 = (cubed - (2.0 * squared)) + amount;
  1026. var part4 = cubed - squared;
  1027. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1028. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1029. return new Vector2(x, y);
  1030. };
  1031. /**
  1032. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1033. */
  1034. Vector2.Lerp = function (start, end, amount) {
  1035. var x = start.x + ((end.x - start.x) * amount);
  1036. var y = start.y + ((end.y - start.y) * amount);
  1037. return new Vector2(x, y);
  1038. };
  1039. /**
  1040. * Returns the dot product (float) of the vector "left" and the vector "right".
  1041. */
  1042. Vector2.Dot = function (left, right) {
  1043. return left.x * right.x + left.y * right.y;
  1044. };
  1045. /**
  1046. * Returns a new Vector2 equal to the normalized passed vector.
  1047. */
  1048. Vector2.Normalize = function (vector) {
  1049. var newVector = vector.clone();
  1050. newVector.normalize();
  1051. return newVector;
  1052. };
  1053. /**
  1054. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1055. */
  1056. Vector2.Minimize = function (left, right) {
  1057. var x = (left.x < right.x) ? left.x : right.x;
  1058. var y = (left.y < right.y) ? left.y : right.y;
  1059. return new Vector2(x, y);
  1060. };
  1061. /**
  1062. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1063. */
  1064. Vector2.Maximize = function (left, right) {
  1065. var x = (left.x > right.x) ? left.x : right.x;
  1066. var y = (left.y > right.y) ? left.y : right.y;
  1067. return new Vector2(x, y);
  1068. };
  1069. /**
  1070. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1071. */
  1072. Vector2.Transform = function (vector, transformation) {
  1073. var r = Vector2.Zero();
  1074. Vector2.TransformToRef(vector, transformation, r);
  1075. return r;
  1076. };
  1077. /**
  1078. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1079. */
  1080. Vector2.TransformToRef = function (vector, transformation, result) {
  1081. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1082. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1083. result.x = x;
  1084. result.y = y;
  1085. };
  1086. /**
  1087. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1088. */
  1089. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1090. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1091. var sign = a < 0 ? -1 : 1;
  1092. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1093. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1094. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1095. };
  1096. /**
  1097. * Returns the distance (float) between the vectors "value1" and "value2".
  1098. */
  1099. Vector2.Distance = function (value1, value2) {
  1100. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1101. };
  1102. /**
  1103. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1104. */
  1105. Vector2.DistanceSquared = function (value1, value2) {
  1106. var x = value1.x - value2.x;
  1107. var y = value1.y - value2.y;
  1108. return (x * x) + (y * y);
  1109. };
  1110. /**
  1111. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1112. */
  1113. Vector2.Center = function (value1, value2) {
  1114. var center = value1.add(value2);
  1115. center.scaleInPlace(0.5);
  1116. return center;
  1117. };
  1118. /**
  1119. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1120. */
  1121. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1122. var l2 = Vector2.DistanceSquared(segA, segB);
  1123. if (l2 === 0.0) {
  1124. return Vector2.Distance(p, segA);
  1125. }
  1126. var v = segB.subtract(segA);
  1127. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1128. var proj = segA.add(v.multiplyByFloats(t, t));
  1129. return Vector2.Distance(p, proj);
  1130. };
  1131. return Vector2;
  1132. }());
  1133. BABYLON.Vector2 = Vector2;
  1134. var Vector3 = (function () {
  1135. /**
  1136. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1137. * A Vector3 is the main object used in 3D geometry.
  1138. * It can represent etiher the coordinates of a point the space, either a direction.
  1139. */
  1140. function Vector3(x, y, z) {
  1141. this.x = x;
  1142. this.y = y;
  1143. this.z = z;
  1144. }
  1145. /**
  1146. * Returns a string with the Vector3 coordinates.
  1147. */
  1148. Vector3.prototype.toString = function () {
  1149. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1150. };
  1151. /**
  1152. * Returns the string "Vector3"
  1153. */
  1154. Vector3.prototype.getClassName = function () {
  1155. return "Vector3";
  1156. };
  1157. /**
  1158. * Returns the Vector hash code.
  1159. */
  1160. Vector3.prototype.getHashCode = function () {
  1161. var hash = this.x || 0;
  1162. hash = (hash * 397) ^ (this.y || 0);
  1163. hash = (hash * 397) ^ (this.z || 0);
  1164. return hash;
  1165. };
  1166. // Operators
  1167. /**
  1168. * Returns a new array with three elements : the coordinates the Vector3.
  1169. */
  1170. Vector3.prototype.asArray = function () {
  1171. var result = [];
  1172. this.toArray(result, 0);
  1173. return result;
  1174. };
  1175. /**
  1176. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1177. * Returns the Vector3.
  1178. */
  1179. Vector3.prototype.toArray = function (array, index) {
  1180. if (index === void 0) { index = 0; }
  1181. array[index] = this.x;
  1182. array[index + 1] = this.y;
  1183. array[index + 2] = this.z;
  1184. return this;
  1185. };
  1186. /**
  1187. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1188. */
  1189. Vector3.prototype.toQuaternion = function () {
  1190. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1191. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1192. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1193. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1194. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1195. var cosy = Math.cos(this.y * 0.5);
  1196. var siny = Math.sin(this.y * 0.5);
  1197. result.x = coszMinusx * siny;
  1198. result.y = -sinzMinusx * siny;
  1199. result.z = sinxPlusz * cosy;
  1200. result.w = cosxPlusz * cosy;
  1201. return result;
  1202. };
  1203. /**
  1204. * Adds the passed vector to the current Vector3.
  1205. * Returns the updated Vector3.
  1206. */
  1207. Vector3.prototype.addInPlace = function (otherVector) {
  1208. this.x += otherVector.x;
  1209. this.y += otherVector.y;
  1210. this.z += otherVector.z;
  1211. return this;
  1212. };
  1213. /**
  1214. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1215. */
  1216. Vector3.prototype.add = function (otherVector) {
  1217. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1218. };
  1219. /**
  1220. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1221. * Returns the current Vector3.
  1222. */
  1223. Vector3.prototype.addToRef = function (otherVector, result) {
  1224. result.x = this.x + otherVector.x;
  1225. result.y = this.y + otherVector.y;
  1226. result.z = this.z + otherVector.z;
  1227. return this;
  1228. };
  1229. /**
  1230. * Subtract the passed vector from the current Vector3.
  1231. * Returns the updated Vector3.
  1232. */
  1233. Vector3.prototype.subtractInPlace = function (otherVector) {
  1234. this.x -= otherVector.x;
  1235. this.y -= otherVector.y;
  1236. this.z -= otherVector.z;
  1237. return this;
  1238. };
  1239. /**
  1240. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1241. */
  1242. Vector3.prototype.subtract = function (otherVector) {
  1243. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1244. };
  1245. /**
  1246. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1247. * Returns the current Vector3.
  1248. */
  1249. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1250. result.x = this.x - otherVector.x;
  1251. result.y = this.y - otherVector.y;
  1252. result.z = this.z - otherVector.z;
  1253. return this;
  1254. };
  1255. /**
  1256. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1257. */
  1258. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1259. return new Vector3(this.x - x, this.y - y, this.z - z);
  1260. };
  1261. /**
  1262. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1263. * Returns the current Vector3.
  1264. */
  1265. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1266. result.x = this.x - x;
  1267. result.y = this.y - y;
  1268. result.z = this.z - z;
  1269. return this;
  1270. };
  1271. /**
  1272. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1273. */
  1274. Vector3.prototype.negate = function () {
  1275. return new Vector3(-this.x, -this.y, -this.z);
  1276. };
  1277. /**
  1278. * Multiplies the Vector3 coordinates by the float "scale".
  1279. * Returns the updated Vector3.
  1280. */
  1281. Vector3.prototype.scaleInPlace = function (scale) {
  1282. this.x *= scale;
  1283. this.y *= scale;
  1284. this.z *= scale;
  1285. return this;
  1286. };
  1287. /**
  1288. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1289. */
  1290. Vector3.prototype.scale = function (scale) {
  1291. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1292. };
  1293. /**
  1294. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1295. * Returns the current Vector3.
  1296. */
  1297. Vector3.prototype.scaleToRef = function (scale, result) {
  1298. result.x = this.x * scale;
  1299. result.y = this.y * scale;
  1300. result.z = this.z * scale;
  1301. return this;
  1302. };
  1303. /**
  1304. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1305. */
  1306. Vector3.prototype.equals = function (otherVector) {
  1307. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1308. };
  1309. /**
  1310. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1311. */
  1312. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1313. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1314. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  1315. };
  1316. /**
  1317. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1318. */
  1319. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1320. return this.x === x && this.y === y && this.z === z;
  1321. };
  1322. /**
  1323. * Muliplies the current Vector3 coordinates by the passed ones.
  1324. * Returns the updated Vector3.
  1325. */
  1326. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1327. this.x *= otherVector.x;
  1328. this.y *= otherVector.y;
  1329. this.z *= otherVector.z;
  1330. return this;
  1331. };
  1332. /**
  1333. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1334. */
  1335. Vector3.prototype.multiply = function (otherVector) {
  1336. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1337. };
  1338. /**
  1339. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1340. * Returns the current Vector3.
  1341. */
  1342. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1343. result.x = this.x * otherVector.x;
  1344. result.y = this.y * otherVector.y;
  1345. result.z = this.z * otherVector.z;
  1346. return this;
  1347. };
  1348. /**
  1349. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1350. */
  1351. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1352. return new Vector3(this.x * x, this.y * y, this.z * z);
  1353. };
  1354. /**
  1355. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1356. */
  1357. Vector3.prototype.divide = function (otherVector) {
  1358. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1359. };
  1360. /**
  1361. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1362. * Returns the current Vector3.
  1363. */
  1364. Vector3.prototype.divideToRef = function (otherVector, result) {
  1365. result.x = this.x / otherVector.x;
  1366. result.y = this.y / otherVector.y;
  1367. result.z = this.z / otherVector.z;
  1368. return this;
  1369. };
  1370. /**
  1371. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1372. * Returns the updated Vector3.
  1373. */
  1374. Vector3.prototype.MinimizeInPlace = function (other) {
  1375. if (other.x < this.x)
  1376. this.x = other.x;
  1377. if (other.y < this.y)
  1378. this.y = other.y;
  1379. if (other.z < this.z)
  1380. this.z = other.z;
  1381. return this;
  1382. };
  1383. /**
  1384. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1385. * Returns the updated Vector3.
  1386. */
  1387. Vector3.prototype.MaximizeInPlace = function (other) {
  1388. if (other.x > this.x)
  1389. this.x = other.x;
  1390. if (other.y > this.y)
  1391. this.y = other.y;
  1392. if (other.z > this.z)
  1393. this.z = other.z;
  1394. return this;
  1395. };
  1396. // Properties
  1397. /**
  1398. * Returns the length of the Vector3 (float).
  1399. */
  1400. Vector3.prototype.length = function () {
  1401. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1402. };
  1403. /**
  1404. * Returns the squared length of the Vector3 (float).
  1405. */
  1406. Vector3.prototype.lengthSquared = function () {
  1407. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1408. };
  1409. // Methods
  1410. /**
  1411. * Normalize the current Vector3.
  1412. * Returns the updated Vector3.
  1413. */
  1414. Vector3.prototype.normalize = function () {
  1415. var len = this.length();
  1416. if (len === 0 || len === 1.0)
  1417. return this;
  1418. var num = 1.0 / len;
  1419. this.x *= num;
  1420. this.y *= num;
  1421. this.z *= num;
  1422. return this;
  1423. };
  1424. /**
  1425. * Returns a new Vector3 copied from the current Vector3.
  1426. */
  1427. Vector3.prototype.clone = function () {
  1428. return new Vector3(this.x, this.y, this.z);
  1429. };
  1430. /**
  1431. * Copies the passed vector coordinates to the current Vector3 ones.
  1432. * Returns the updated Vector3.
  1433. */
  1434. Vector3.prototype.copyFrom = function (source) {
  1435. this.x = source.x;
  1436. this.y = source.y;
  1437. this.z = source.z;
  1438. return this;
  1439. };
  1440. /**
  1441. * Copies the passed floats to the current Vector3 coordinates.
  1442. * Returns the updated Vector3.
  1443. */
  1444. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1445. this.x = x;
  1446. this.y = y;
  1447. this.z = z;
  1448. return this;
  1449. };
  1450. /**
  1451. * Copies the passed floats to the current Vector3 coordinates.
  1452. * Returns the updated Vector3.
  1453. */
  1454. Vector3.prototype.set = function (x, y, z) {
  1455. return this.copyFromFloats(x, y, z);
  1456. };
  1457. // Statics
  1458. /**
  1459. *
  1460. */
  1461. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1462. var d0 = Vector3.Dot(vector0, axis) - size;
  1463. var d1 = Vector3.Dot(vector1, axis) - size;
  1464. var s = d0 / (d0 - d1);
  1465. return s;
  1466. };
  1467. /**
  1468. * Returns a new Vector3 set from the index "offset" of the passed array.
  1469. */
  1470. Vector3.FromArray = function (array, offset) {
  1471. if (!offset) {
  1472. offset = 0;
  1473. }
  1474. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1475. };
  1476. /**
  1477. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1478. * This function is deprecated. Use FromArray instead.
  1479. */
  1480. Vector3.FromFloatArray = function (array, offset) {
  1481. return Vector3.FromArray(array, offset);
  1482. };
  1483. /**
  1484. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1485. */
  1486. Vector3.FromArrayToRef = function (array, offset, result) {
  1487. result.x = array[offset];
  1488. result.y = array[offset + 1];
  1489. result.z = array[offset + 2];
  1490. };
  1491. /**
  1492. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1493. * This function is deprecated. Use FromArrayToRef instead.
  1494. */
  1495. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1496. return Vector3.FromArrayToRef(array, offset, result);
  1497. };
  1498. /**
  1499. * Sets the passed vector "result" with the passed floats.
  1500. */
  1501. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1502. result.x = x;
  1503. result.y = y;
  1504. result.z = z;
  1505. };
  1506. /**
  1507. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1508. */
  1509. Vector3.Zero = function () {
  1510. return new Vector3(0.0, 0.0, 0.0);
  1511. };
  1512. /**
  1513. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1514. */
  1515. Vector3.One = function () {
  1516. return new Vector3(1.0, 1.0, 1.0);
  1517. };
  1518. /**
  1519. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1520. */
  1521. Vector3.Up = function () {
  1522. return new Vector3(0.0, 1.0, 0.0);
  1523. };
  1524. /**
  1525. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1526. */
  1527. Vector3.Forward = function () {
  1528. return new Vector3(0.0, 0.0, 1.0);
  1529. };
  1530. /**
  1531. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1532. */
  1533. Vector3.Right = function () {
  1534. return new Vector3(1.0, 0.0, 0.0);
  1535. };
  1536. /**
  1537. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1538. */
  1539. Vector3.Left = function () {
  1540. return new Vector3(-1.0, 0.0, 0.0);
  1541. };
  1542. /**
  1543. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1544. * This method computes tranformed coordinates only, not transformed direction vectors.
  1545. */
  1546. Vector3.TransformCoordinates = function (vector, transformation) {
  1547. var result = Vector3.Zero();
  1548. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1549. return result;
  1550. };
  1551. /**
  1552. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1553. * This method computes tranformed coordinates only, not transformed direction vectors.
  1554. */
  1555. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1556. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1557. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1558. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1559. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1560. result.x = x / w;
  1561. result.y = y / w;
  1562. result.z = z / w;
  1563. };
  1564. /**
  1565. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1566. * This method computes tranformed coordinates only, not transformed direction vectors.
  1567. */
  1568. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1569. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1570. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1571. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1572. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1573. result.x = rx / rw;
  1574. result.y = ry / rw;
  1575. result.z = rz / rw;
  1576. };
  1577. /**
  1578. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1579. * This methods computes transformed normalized direction vectors only.
  1580. */
  1581. Vector3.TransformNormal = function (vector, transformation) {
  1582. var result = Vector3.Zero();
  1583. Vector3.TransformNormalToRef(vector, transformation, result);
  1584. return result;
  1585. };
  1586. /**
  1587. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1588. * This methods computes transformed normalized direction vectors only.
  1589. */
  1590. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1591. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1592. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1593. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1594. result.x = x;
  1595. result.y = y;
  1596. result.z = z;
  1597. };
  1598. /**
  1599. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1600. * This methods computes transformed normalized direction vectors only.
  1601. */
  1602. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1603. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1604. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1605. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1606. };
  1607. /**
  1608. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1609. */
  1610. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1611. var squared = amount * amount;
  1612. var cubed = amount * squared;
  1613. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1614. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1615. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1616. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1617. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1618. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1619. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1620. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1621. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1622. return new Vector3(x, y, z);
  1623. };
  1624. /**
  1625. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
  1626. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1627. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1628. */
  1629. Vector3.Clamp = function (value, min, max) {
  1630. var x = value.x;
  1631. x = (x > max.x) ? max.x : x;
  1632. x = (x < min.x) ? min.x : x;
  1633. var y = value.y;
  1634. y = (y > max.y) ? max.y : y;
  1635. y = (y < min.y) ? min.y : y;
  1636. var z = value.z;
  1637. z = (z > max.z) ? max.z : z;
  1638. z = (z < min.z) ? min.z : z;
  1639. return new Vector3(x, y, z);
  1640. };
  1641. /**
  1642. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1643. */
  1644. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1645. var squared = amount * amount;
  1646. var cubed = amount * squared;
  1647. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1648. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1649. var part3 = (cubed - (2.0 * squared)) + amount;
  1650. var part4 = cubed - squared;
  1651. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1652. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1653. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1654. return new Vector3(x, y, z);
  1655. };
  1656. /**
  1657. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1658. */
  1659. Vector3.Lerp = function (start, end, amount) {
  1660. var result = new Vector3(0, 0, 0);
  1661. Vector3.LerpToRef(start, end, amount, result);
  1662. return result;
  1663. };
  1664. /**
  1665. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1666. */
  1667. Vector3.LerpToRef = function (start, end, amount, result) {
  1668. result.x = start.x + ((end.x - start.x) * amount);
  1669. result.y = start.y + ((end.y - start.y) * amount);
  1670. result.z = start.z + ((end.z - start.z) * amount);
  1671. };
  1672. /**
  1673. * Returns the dot product (float) between the vectors "left" and "right".
  1674. */
  1675. Vector3.Dot = function (left, right) {
  1676. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1677. };
  1678. /**
  1679. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1680. * The cross product is then orthogonal to both "left" and "right".
  1681. */
  1682. Vector3.Cross = function (left, right) {
  1683. var result = Vector3.Zero();
  1684. Vector3.CrossToRef(left, right, result);
  1685. return result;
  1686. };
  1687. /**
  1688. * Sets the passed vector "result" with the cross product of "left" and "right".
  1689. * The cross product is then orthogonal to both "left" and "right".
  1690. */
  1691. Vector3.CrossToRef = function (left, right, result) {
  1692. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1693. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1694. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1695. result.copyFrom(MathTmp.Vector3[0]);
  1696. };
  1697. /**
  1698. * Returns a new Vector3 as the normalization of the passed vector.
  1699. */
  1700. Vector3.Normalize = function (vector) {
  1701. var result = Vector3.Zero();
  1702. Vector3.NormalizeToRef(vector, result);
  1703. return result;
  1704. };
  1705. /**
  1706. * Sets the passed vector "result" with the normalization of the passed first vector.
  1707. */
  1708. Vector3.NormalizeToRef = function (vector, result) {
  1709. result.copyFrom(vector);
  1710. result.normalize();
  1711. };
  1712. Vector3.Project = function (vector, world, transform, viewport) {
  1713. var cw = viewport.width;
  1714. var ch = viewport.height;
  1715. var cx = viewport.x;
  1716. var cy = viewport.y;
  1717. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1718. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  1719. var matrix = MathTmp.Matrix[0];
  1720. world.multiplyToRef(transform, matrix);
  1721. matrix.multiplyToRef(viewportMatrix, matrix);
  1722. return Vector3.TransformCoordinates(vector, matrix);
  1723. };
  1724. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1725. var matrix = MathTmp.Matrix[0];
  1726. world.multiplyToRef(transform, matrix);
  1727. matrix.invert();
  1728. source.x = source.x / viewportWidth * 2 - 1;
  1729. source.y = -(source.y / viewportHeight * 2 - 1);
  1730. var vector = Vector3.TransformCoordinates(source, matrix);
  1731. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1732. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1733. vector = vector.scale(1.0 / num);
  1734. }
  1735. return vector;
  1736. };
  1737. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1738. var matrix = MathTmp.Matrix[0];
  1739. world.multiplyToRef(view, matrix);
  1740. matrix.multiplyToRef(projection, matrix);
  1741. matrix.invert();
  1742. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1743. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1744. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1745. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1746. vector = vector.scale(1.0 / num);
  1747. }
  1748. return vector;
  1749. };
  1750. Vector3.Minimize = function (left, right) {
  1751. var min = left.clone();
  1752. min.MinimizeInPlace(right);
  1753. return min;
  1754. };
  1755. Vector3.Maximize = function (left, right) {
  1756. var max = left.clone();
  1757. max.MaximizeInPlace(right);
  1758. return max;
  1759. };
  1760. /**
  1761. * Returns the distance (float) between the vectors "value1" and "value2".
  1762. */
  1763. Vector3.Distance = function (value1, value2) {
  1764. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1765. };
  1766. /**
  1767. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1768. */
  1769. Vector3.DistanceSquared = function (value1, value2) {
  1770. var x = value1.x - value2.x;
  1771. var y = value1.y - value2.y;
  1772. var z = value1.z - value2.z;
  1773. return (x * x) + (y * y) + (z * z);
  1774. };
  1775. /**
  1776. * Returns a new Vector3 located at the center between "value1" and "value2".
  1777. */
  1778. Vector3.Center = function (value1, value2) {
  1779. var center = value1.add(value2);
  1780. center.scaleInPlace(0.5);
  1781. return center;
  1782. };
  1783. /**
  1784. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1785. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1786. * to something in order to rotate it from its local system to the given target system.
  1787. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1788. * Returns a new Vector3.
  1789. */
  1790. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1791. var rotation = Vector3.Zero();
  1792. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1793. return rotation;
  1794. };
  1795. /**
  1796. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1797. */
  1798. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1799. var quat = MathTmp.Quaternion[0];
  1800. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1801. quat.toEulerAnglesToRef(ref);
  1802. };
  1803. return Vector3;
  1804. }());
  1805. BABYLON.Vector3 = Vector3;
  1806. //Vector4 class created for EulerAngle class conversion to Quaternion
  1807. var Vector4 = (function () {
  1808. /**
  1809. * Creates a Vector4 object from the passed floats.
  1810. */
  1811. function Vector4(x, y, z, w) {
  1812. this.x = x;
  1813. this.y = y;
  1814. this.z = z;
  1815. this.w = w;
  1816. }
  1817. /**
  1818. * Returns the string with the Vector4 coordinates.
  1819. */
  1820. Vector4.prototype.toString = function () {
  1821. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1822. };
  1823. /**
  1824. * Returns the string "Vector4".
  1825. */
  1826. Vector4.prototype.getClassName = function () {
  1827. return "Vector4";
  1828. };
  1829. /**
  1830. * Returns the Vector4 hash code.
  1831. */
  1832. Vector4.prototype.getHashCode = function () {
  1833. var hash = this.x || 0;
  1834. hash = (hash * 397) ^ (this.y || 0);
  1835. hash = (hash * 397) ^ (this.z || 0);
  1836. hash = (hash * 397) ^ (this.w || 0);
  1837. return hash;
  1838. };
  1839. // Operators
  1840. /**
  1841. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1842. */
  1843. Vector4.prototype.asArray = function () {
  1844. var result = [];
  1845. this.toArray(result, 0);
  1846. return result;
  1847. };
  1848. /**
  1849. * Populates the passed array from the passed index with the Vector4 coordinates.
  1850. * Returns the Vector4.
  1851. */
  1852. Vector4.prototype.toArray = function (array, index) {
  1853. if (index === undefined) {
  1854. index = 0;
  1855. }
  1856. array[index] = this.x;
  1857. array[index + 1] = this.y;
  1858. array[index + 2] = this.z;
  1859. array[index + 3] = this.w;
  1860. return this;
  1861. };
  1862. /**
  1863. * Adds the passed vector to the current Vector4.
  1864. * Returns the updated Vector4.
  1865. */
  1866. Vector4.prototype.addInPlace = function (otherVector) {
  1867. this.x += otherVector.x;
  1868. this.y += otherVector.y;
  1869. this.z += otherVector.z;
  1870. this.w += otherVector.w;
  1871. return this;
  1872. };
  1873. /**
  1874. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1875. */
  1876. Vector4.prototype.add = function (otherVector) {
  1877. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1878. };
  1879. /**
  1880. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1881. * Returns the current Vector4.
  1882. */
  1883. Vector4.prototype.addToRef = function (otherVector, result) {
  1884. result.x = this.x + otherVector.x;
  1885. result.y = this.y + otherVector.y;
  1886. result.z = this.z + otherVector.z;
  1887. result.w = this.w + otherVector.w;
  1888. return this;
  1889. };
  1890. /**
  1891. * Subtract in place the passed vector from the current Vector4.
  1892. * Returns the updated Vector4.
  1893. */
  1894. Vector4.prototype.subtractInPlace = function (otherVector) {
  1895. this.x -= otherVector.x;
  1896. this.y -= otherVector.y;
  1897. this.z -= otherVector.z;
  1898. this.w -= otherVector.w;
  1899. return this;
  1900. };
  1901. /**
  1902. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1903. */
  1904. Vector4.prototype.subtract = function (otherVector) {
  1905. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1906. };
  1907. /**
  1908. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1909. * Returns the current Vector4.
  1910. */
  1911. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1912. result.x = this.x - otherVector.x;
  1913. result.y = this.y - otherVector.y;
  1914. result.z = this.z - otherVector.z;
  1915. result.w = this.w - otherVector.w;
  1916. return this;
  1917. };
  1918. /**
  1919. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1920. */
  1921. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1922. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1923. };
  1924. /**
  1925. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1926. * Returns the current Vector4.
  1927. */
  1928. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1929. result.x = this.x - x;
  1930. result.y = this.y - y;
  1931. result.z = this.z - z;
  1932. result.w = this.w - w;
  1933. return this;
  1934. };
  1935. /**
  1936. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1937. */
  1938. Vector4.prototype.negate = function () {
  1939. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1940. };
  1941. /**
  1942. * Multiplies the current Vector4 coordinates by scale (float).
  1943. * Returns the updated Vector4.
  1944. */
  1945. Vector4.prototype.scaleInPlace = function (scale) {
  1946. this.x *= scale;
  1947. this.y *= scale;
  1948. this.z *= scale;
  1949. this.w *= scale;
  1950. return this;
  1951. };
  1952. /**
  1953. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1954. */
  1955. Vector4.prototype.scale = function (scale) {
  1956. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1957. };
  1958. /**
  1959. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1960. * Returns the current Vector4.
  1961. */
  1962. Vector4.prototype.scaleToRef = function (scale, result) {
  1963. result.x = this.x * scale;
  1964. result.y = this.y * scale;
  1965. result.z = this.z * scale;
  1966. result.w = this.w * scale;
  1967. return this;
  1968. };
  1969. /**
  1970. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1971. */
  1972. Vector4.prototype.equals = function (otherVector) {
  1973. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1974. };
  1975. /**
  1976. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1977. */
  1978. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1979. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1980. return otherVector
  1981. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  1982. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  1983. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  1984. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  1985. };
  1986. /**
  1987. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1988. */
  1989. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1990. return this.x === x && this.y === y && this.z === z && this.w === w;
  1991. };
  1992. /**
  1993. * Multiplies in place the current Vector4 by the passed one.
  1994. * Returns the updated Vector4.
  1995. */
  1996. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1997. this.x *= otherVector.x;
  1998. this.y *= otherVector.y;
  1999. this.z *= otherVector.z;
  2000. this.w *= otherVector.w;
  2001. return this;
  2002. };
  2003. /**
  2004. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2005. */
  2006. Vector4.prototype.multiply = function (otherVector) {
  2007. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2008. };
  2009. /**
  2010. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2011. * Returns the current Vector4.
  2012. */
  2013. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2014. result.x = this.x * otherVector.x;
  2015. result.y = this.y * otherVector.y;
  2016. result.z = this.z * otherVector.z;
  2017. result.w = this.w * otherVector.w;
  2018. return this;
  2019. };
  2020. /**
  2021. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2022. */
  2023. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2024. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2025. };
  2026. /**
  2027. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2028. */
  2029. Vector4.prototype.divide = function (otherVector) {
  2030. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2031. };
  2032. /**
  2033. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2034. * Returns the current Vector4.
  2035. */
  2036. Vector4.prototype.divideToRef = function (otherVector, result) {
  2037. result.x = this.x / otherVector.x;
  2038. result.y = this.y / otherVector.y;
  2039. result.z = this.z / otherVector.z;
  2040. result.w = this.w / otherVector.w;
  2041. return this;
  2042. };
  2043. /**
  2044. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2045. */
  2046. Vector4.prototype.MinimizeInPlace = function (other) {
  2047. if (other.x < this.x)
  2048. this.x = other.x;
  2049. if (other.y < this.y)
  2050. this.y = other.y;
  2051. if (other.z < this.z)
  2052. this.z = other.z;
  2053. if (other.w < this.w)
  2054. this.w = other.w;
  2055. return this;
  2056. };
  2057. /**
  2058. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2059. */
  2060. Vector4.prototype.MaximizeInPlace = function (other) {
  2061. if (other.x > this.x)
  2062. this.x = other.x;
  2063. if (other.y > this.y)
  2064. this.y = other.y;
  2065. if (other.z > this.z)
  2066. this.z = other.z;
  2067. if (other.w > this.w)
  2068. this.w = other.w;
  2069. return this;
  2070. };
  2071. // Properties
  2072. /**
  2073. * Returns the Vector4 length (float).
  2074. */
  2075. Vector4.prototype.length = function () {
  2076. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2077. };
  2078. /**
  2079. * Returns the Vector4 squared length (float).
  2080. */
  2081. Vector4.prototype.lengthSquared = function () {
  2082. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2083. };
  2084. // Methods
  2085. /**
  2086. * Normalizes in place the Vector4.
  2087. * Returns the updated Vector4.
  2088. */
  2089. Vector4.prototype.normalize = function () {
  2090. var len = this.length();
  2091. if (len === 0)
  2092. return this;
  2093. var num = 1.0 / len;
  2094. this.x *= num;
  2095. this.y *= num;
  2096. this.z *= num;
  2097. this.w *= num;
  2098. return this;
  2099. };
  2100. /**
  2101. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2102. */
  2103. Vector4.prototype.toVector3 = function () {
  2104. return new Vector3(this.x, this.y, this.z);
  2105. };
  2106. /**
  2107. * Returns a new Vector4 copied from the current one.
  2108. */
  2109. Vector4.prototype.clone = function () {
  2110. return new Vector4(this.x, this.y, this.z, this.w);
  2111. };
  2112. /**
  2113. * Updates the current Vector4 with the passed one coordinates.
  2114. * Returns the updated Vector4.
  2115. */
  2116. Vector4.prototype.copyFrom = function (source) {
  2117. this.x = source.x;
  2118. this.y = source.y;
  2119. this.z = source.z;
  2120. this.w = source.w;
  2121. return this;
  2122. };
  2123. /**
  2124. * Updates the current Vector4 coordinates with the passed floats.
  2125. * Returns the updated Vector4.
  2126. */
  2127. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2128. this.x = x;
  2129. this.y = y;
  2130. this.z = z;
  2131. this.w = w;
  2132. return this;
  2133. };
  2134. /**
  2135. * Updates the current Vector4 coordinates with the passed floats.
  2136. * Returns the updated Vector4.
  2137. */
  2138. Vector4.prototype.set = function (x, y, z, w) {
  2139. return this.copyFromFloats(x, y, z, w);
  2140. };
  2141. // Statics
  2142. /**
  2143. * Returns a new Vector4 set from the starting index of the passed array.
  2144. */
  2145. Vector4.FromArray = function (array, offset) {
  2146. if (!offset) {
  2147. offset = 0;
  2148. }
  2149. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2150. };
  2151. /**
  2152. * Updates the passed vector "result" from the starting index of the passed array.
  2153. */
  2154. Vector4.FromArrayToRef = function (array, offset, result) {
  2155. result.x = array[offset];
  2156. result.y = array[offset + 1];
  2157. result.z = array[offset + 2];
  2158. result.w = array[offset + 3];
  2159. };
  2160. /**
  2161. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2162. */
  2163. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2164. Vector4.FromArrayToRef(array, offset, result);
  2165. };
  2166. /**
  2167. * Updates the passed vector "result" coordinates from the passed floats.
  2168. */
  2169. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2170. result.x = x;
  2171. result.y = y;
  2172. result.z = z;
  2173. result.w = w;
  2174. };
  2175. /**
  2176. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2177. */
  2178. Vector4.Zero = function () {
  2179. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2180. };
  2181. /**
  2182. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2183. */
  2184. Vector4.One = function () {
  2185. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2186. };
  2187. /**
  2188. * Returns a new normalized Vector4 from the passed one.
  2189. */
  2190. Vector4.Normalize = function (vector) {
  2191. var result = Vector4.Zero();
  2192. Vector4.NormalizeToRef(vector, result);
  2193. return result;
  2194. };
  2195. /**
  2196. * Updates the passed vector "result" from the normalization of the passed one.
  2197. */
  2198. Vector4.NormalizeToRef = function (vector, result) {
  2199. result.copyFrom(vector);
  2200. result.normalize();
  2201. };
  2202. Vector4.Minimize = function (left, right) {
  2203. var min = left.clone();
  2204. min.MinimizeInPlace(right);
  2205. return min;
  2206. };
  2207. Vector4.Maximize = function (left, right) {
  2208. var max = left.clone();
  2209. max.MaximizeInPlace(right);
  2210. return max;
  2211. };
  2212. /**
  2213. * Returns the distance (float) between the vectors "value1" and "value2".
  2214. */
  2215. Vector4.Distance = function (value1, value2) {
  2216. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2217. };
  2218. /**
  2219. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2220. */
  2221. Vector4.DistanceSquared = function (value1, value2) {
  2222. var x = value1.x - value2.x;
  2223. var y = value1.y - value2.y;
  2224. var z = value1.z - value2.z;
  2225. var w = value1.w - value2.w;
  2226. return (x * x) + (y * y) + (z * z) + (w * w);
  2227. };
  2228. /**
  2229. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2230. */
  2231. Vector4.Center = function (value1, value2) {
  2232. var center = value1.add(value2);
  2233. center.scaleInPlace(0.5);
  2234. return center;
  2235. };
  2236. /**
  2237. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2238. * This methods computes transformed normalized direction vectors only.
  2239. */
  2240. Vector4.TransformNormal = function (vector, transformation) {
  2241. var result = Vector4.Zero();
  2242. Vector4.TransformNormalToRef(vector, transformation, result);
  2243. return result;
  2244. };
  2245. /**
  2246. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2247. * This methods computes transformed normalized direction vectors only.
  2248. */
  2249. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2250. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2251. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2252. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2253. result.x = x;
  2254. result.y = y;
  2255. result.z = z;
  2256. result.w = vector.w;
  2257. };
  2258. /**
  2259. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2260. * This methods computes transformed normalized direction vectors only.
  2261. */
  2262. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2263. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2264. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2265. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2266. result.w = w;
  2267. };
  2268. return Vector4;
  2269. }());
  2270. BABYLON.Vector4 = Vector4;
  2271. var Size = (function () {
  2272. /**
  2273. * Creates a Size object from the passed width and height (floats).
  2274. */
  2275. function Size(width, height) {
  2276. this.width = width;
  2277. this.height = height;
  2278. }
  2279. // Returns a string with the Size width and height.
  2280. Size.prototype.toString = function () {
  2281. return "{W: " + this.width + ", H: " + this.height + "}";
  2282. };
  2283. /**
  2284. * Returns the string "Size"
  2285. */
  2286. Size.prototype.getClassName = function () {
  2287. return "Size";
  2288. };
  2289. /**
  2290. * Returns the Size hash code.
  2291. */
  2292. Size.prototype.getHashCode = function () {
  2293. var hash = this.width || 0;
  2294. hash = (hash * 397) ^ (this.height || 0);
  2295. return hash;
  2296. };
  2297. /**
  2298. * Updates the current size from the passed one.
  2299. * Returns the updated Size.
  2300. */
  2301. Size.prototype.copyFrom = function (src) {
  2302. this.width = src.width;
  2303. this.height = src.height;
  2304. };
  2305. /**
  2306. * Updates in place the current Size from the passed floats.
  2307. * Returns the updated Size.
  2308. */
  2309. Size.prototype.copyFromFloats = function (width, height) {
  2310. this.width = width;
  2311. this.height = height;
  2312. return this;
  2313. };
  2314. /**
  2315. * Updates in place the current Size from the passed floats.
  2316. * Returns the updated Size.
  2317. */
  2318. Size.prototype.set = function (width, height) {
  2319. return this.copyFromFloats(width, height);
  2320. };
  2321. /**
  2322. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2323. */
  2324. Size.prototype.multiplyByFloats = function (w, h) {
  2325. return new Size(this.width * w, this.height * h);
  2326. };
  2327. /**
  2328. * Returns a new Size copied from the passed one.
  2329. */
  2330. Size.prototype.clone = function () {
  2331. return new Size(this.width, this.height);
  2332. };
  2333. /**
  2334. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2335. */
  2336. Size.prototype.equals = function (other) {
  2337. if (!other) {
  2338. return false;
  2339. }
  2340. return (this.width === other.width) && (this.height === other.height);
  2341. };
  2342. Object.defineProperty(Size.prototype, "surface", {
  2343. /**
  2344. * Returns the surface of the Size : width * height (float).
  2345. */
  2346. get: function () {
  2347. return this.width * this.height;
  2348. },
  2349. enumerable: true,
  2350. configurable: true
  2351. });
  2352. /**
  2353. * Returns a new Size set to (0.0, 0.0)
  2354. */
  2355. Size.Zero = function () {
  2356. return new Size(0.0, 0.0);
  2357. };
  2358. /**
  2359. * Returns a new Size set as the addition result of the current Size and the passed one.
  2360. */
  2361. Size.prototype.add = function (otherSize) {
  2362. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2363. return r;
  2364. };
  2365. /**
  2366. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2367. */
  2368. Size.prototype.subtract = function (otherSize) {
  2369. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2370. return r;
  2371. };
  2372. /**
  2373. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2374. */
  2375. Size.Lerp = function (start, end, amount) {
  2376. var w = start.width + ((end.width - start.width) * amount);
  2377. var h = start.height + ((end.height - start.height) * amount);
  2378. return new Size(w, h);
  2379. };
  2380. return Size;
  2381. }());
  2382. BABYLON.Size = Size;
  2383. var Quaternion = (function () {
  2384. /**
  2385. * Creates a new Quaternion from the passed floats.
  2386. */
  2387. function Quaternion(x, y, z, w) {
  2388. if (x === void 0) { x = 0.0; }
  2389. if (y === void 0) { y = 0.0; }
  2390. if (z === void 0) { z = 0.0; }
  2391. if (w === void 0) { w = 1.0; }
  2392. this.x = x;
  2393. this.y = y;
  2394. this.z = z;
  2395. this.w = w;
  2396. }
  2397. /**
  2398. * Returns a string with the Quaternion coordinates.
  2399. */
  2400. Quaternion.prototype.toString = function () {
  2401. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2402. };
  2403. /**
  2404. * Returns the string "Quaternion".
  2405. */
  2406. Quaternion.prototype.getClassName = function () {
  2407. return "Quaternion";
  2408. };
  2409. /**
  2410. * Returns the Quaternion hash code.
  2411. */
  2412. Quaternion.prototype.getHashCode = function () {
  2413. var hash = this.x || 0;
  2414. hash = (hash * 397) ^ (this.y || 0);
  2415. hash = (hash * 397) ^ (this.z || 0);
  2416. hash = (hash * 397) ^ (this.w || 0);
  2417. return hash;
  2418. };
  2419. /**
  2420. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2421. */
  2422. Quaternion.prototype.asArray = function () {
  2423. return [this.x, this.y, this.z, this.w];
  2424. };
  2425. /**
  2426. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2427. */
  2428. Quaternion.prototype.equals = function (otherQuaternion) {
  2429. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2430. };
  2431. /**
  2432. * Returns a new Quaternion copied from the current one.
  2433. */
  2434. Quaternion.prototype.clone = function () {
  2435. return new Quaternion(this.x, this.y, this.z, this.w);
  2436. };
  2437. /**
  2438. * Updates the current Quaternion from the passed one coordinates.
  2439. * Returns the updated Quaterion.
  2440. */
  2441. Quaternion.prototype.copyFrom = function (other) {
  2442. this.x = other.x;
  2443. this.y = other.y;
  2444. this.z = other.z;
  2445. this.w = other.w;
  2446. return this;
  2447. };
  2448. /**
  2449. * Updates the current Quaternion from the passed float coordinates.
  2450. * Returns the updated Quaterion.
  2451. */
  2452. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2453. this.x = x;
  2454. this.y = y;
  2455. this.z = z;
  2456. this.w = w;
  2457. return this;
  2458. };
  2459. /**
  2460. * Updates the current Quaternion from the passed float coordinates.
  2461. * Returns the updated Quaterion.
  2462. */
  2463. Quaternion.prototype.set = function (x, y, z, w) {
  2464. return this.copyFromFloats(x, y, z, w);
  2465. };
  2466. /**
  2467. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2468. */
  2469. Quaternion.prototype.add = function (other) {
  2470. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2471. };
  2472. /**
  2473. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2474. */
  2475. Quaternion.prototype.subtract = function (other) {
  2476. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2477. };
  2478. /**
  2479. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2480. */
  2481. Quaternion.prototype.scale = function (value) {
  2482. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2483. };
  2484. /**
  2485. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2486. */
  2487. Quaternion.prototype.multiply = function (q1) {
  2488. var result = new Quaternion(0, 0, 0, 1.0);
  2489. this.multiplyToRef(q1, result);
  2490. return result;
  2491. };
  2492. /**
  2493. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2494. * Returns the current Quaternion.
  2495. */
  2496. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2497. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2498. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2499. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2500. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2501. result.copyFromFloats(x, y, z, w);
  2502. return this;
  2503. };
  2504. /**
  2505. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2506. * Returns the updated Quaternion.
  2507. */
  2508. Quaternion.prototype.multiplyInPlace = function (q1) {
  2509. this.multiplyToRef(q1, this);
  2510. return this;
  2511. };
  2512. /**
  2513. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2514. * Returns the current Quaternion.
  2515. */
  2516. Quaternion.prototype.conjugateToRef = function (ref) {
  2517. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2518. return this;
  2519. };
  2520. /**
  2521. * Conjugates in place the current Quaternion.
  2522. * Returns the updated Quaternion.
  2523. */
  2524. Quaternion.prototype.conjugateInPlace = function () {
  2525. this.x *= -1;
  2526. this.y *= -1;
  2527. this.z *= -1;
  2528. return this;
  2529. };
  2530. /**
  2531. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2532. */
  2533. Quaternion.prototype.conjugate = function () {
  2534. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2535. return result;
  2536. };
  2537. /**
  2538. * Returns the Quaternion length (float).
  2539. */
  2540. Quaternion.prototype.length = function () {
  2541. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2542. };
  2543. /**
  2544. * Normalize in place the current Quaternion.
  2545. * Returns the updated Quaternion.
  2546. */
  2547. Quaternion.prototype.normalize = function () {
  2548. var length = 1.0 / this.length();
  2549. this.x *= length;
  2550. this.y *= length;
  2551. this.z *= length;
  2552. this.w *= length;
  2553. return this;
  2554. };
  2555. /**
  2556. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2557. */
  2558. Quaternion.prototype.toEulerAngles = function (order) {
  2559. if (order === void 0) { order = "YZX"; }
  2560. var result = Vector3.Zero();
  2561. this.toEulerAnglesToRef(result, order);
  2562. return result;
  2563. };
  2564. /**
  2565. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2566. * Returns the current Quaternion.
  2567. */
  2568. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2569. if (order === void 0) { order = "YZX"; }
  2570. var qz = this.z;
  2571. var qx = this.x;
  2572. var qy = this.y;
  2573. var qw = this.w;
  2574. var sqw = qw * qw;
  2575. var sqz = qz * qz;
  2576. var sqx = qx * qx;
  2577. var sqy = qy * qy;
  2578. var zAxisY = qy * qz - qx * qw;
  2579. var limit = .4999999;
  2580. if (zAxisY < -limit) {
  2581. result.y = 2 * Math.atan2(qy, qw);
  2582. result.x = Math.PI / 2;
  2583. result.z = 0;
  2584. }
  2585. else if (zAxisY > limit) {
  2586. result.y = 2 * Math.atan2(qy, qw);
  2587. result.x = -Math.PI / 2;
  2588. result.z = 0;
  2589. }
  2590. else {
  2591. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2592. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2593. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2594. }
  2595. return this;
  2596. };
  2597. /**
  2598. * Updates the passed rotation matrix with the current Quaternion values.
  2599. * Returns the current Quaternion.
  2600. */
  2601. Quaternion.prototype.toRotationMatrix = function (result) {
  2602. var xx = this.x * this.x;
  2603. var yy = this.y * this.y;
  2604. var zz = this.z * this.z;
  2605. var xy = this.x * this.y;
  2606. var zw = this.z * this.w;
  2607. var zx = this.z * this.x;
  2608. var yw = this.y * this.w;
  2609. var yz = this.y * this.z;
  2610. var xw = this.x * this.w;
  2611. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2612. result.m[1] = 2.0 * (xy + zw);
  2613. result.m[2] = 2.0 * (zx - yw);
  2614. result.m[3] = 0;
  2615. result.m[4] = 2.0 * (xy - zw);
  2616. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2617. result.m[6] = 2.0 * (yz + xw);
  2618. result.m[7] = 0;
  2619. result.m[8] = 2.0 * (zx + yw);
  2620. result.m[9] = 2.0 * (yz - xw);
  2621. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2622. result.m[11] = 0;
  2623. result.m[12] = 0;
  2624. result.m[13] = 0;
  2625. result.m[14] = 0;
  2626. result.m[15] = 1.0;
  2627. result._markAsUpdated();
  2628. return this;
  2629. };
  2630. /**
  2631. * Updates the current Quaternion from the passed rotation matrix values.
  2632. * Returns the updated Quaternion.
  2633. */
  2634. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2635. Quaternion.FromRotationMatrixToRef(matrix, this);
  2636. return this;
  2637. };
  2638. // Statics
  2639. /**
  2640. * Returns a new Quaternion set from the passed rotation matrix values.
  2641. */
  2642. Quaternion.FromRotationMatrix = function (matrix) {
  2643. var result = new Quaternion();
  2644. Quaternion.FromRotationMatrixToRef(matrix, result);
  2645. return result;
  2646. };
  2647. /**
  2648. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2649. */
  2650. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2651. var data = matrix.m;
  2652. var m11 = data[0], m12 = data[4], m13 = data[8];
  2653. var m21 = data[1], m22 = data[5], m23 = data[9];
  2654. var m31 = data[2], m32 = data[6], m33 = data[10];
  2655. var trace = m11 + m22 + m33;
  2656. var s;
  2657. if (trace > 0) {
  2658. s = 0.5 / Math.sqrt(trace + 1.0);
  2659. result.w = 0.25 / s;
  2660. result.x = (m32 - m23) * s;
  2661. result.y = (m13 - m31) * s;
  2662. result.z = (m21 - m12) * s;
  2663. }
  2664. else if (m11 > m22 && m11 > m33) {
  2665. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2666. result.w = (m32 - m23) / s;
  2667. result.x = 0.25 * s;
  2668. result.y = (m12 + m21) / s;
  2669. result.z = (m13 + m31) / s;
  2670. }
  2671. else if (m22 > m33) {
  2672. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2673. result.w = (m13 - m31) / s;
  2674. result.x = (m12 + m21) / s;
  2675. result.y = 0.25 * s;
  2676. result.z = (m23 + m32) / s;
  2677. }
  2678. else {
  2679. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2680. result.w = (m21 - m12) / s;
  2681. result.x = (m13 + m31) / s;
  2682. result.y = (m23 + m32) / s;
  2683. result.z = 0.25 * s;
  2684. }
  2685. };
  2686. /**
  2687. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2688. */
  2689. Quaternion.Zero = function () {
  2690. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2691. };
  2692. /**
  2693. * Returns a new Quaternion as the inverted current Quaternion.
  2694. */
  2695. Quaternion.Inverse = function (q) {
  2696. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2697. };
  2698. /**
  2699. * Returns the identity Quaternion.
  2700. */
  2701. Quaternion.Identity = function () {
  2702. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2703. };
  2704. Quaternion.IsIdentity = function (quaternion) {
  2705. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2706. };
  2707. /**
  2708. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2709. */
  2710. Quaternion.RotationAxis = function (axis, angle) {
  2711. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2712. };
  2713. /**
  2714. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2715. */
  2716. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2717. var sin = Math.sin(angle / 2);
  2718. axis.normalize();
  2719. result.w = Math.cos(angle / 2);
  2720. result.x = axis.x * sin;
  2721. result.y = axis.y * sin;
  2722. result.z = axis.z * sin;
  2723. return result;
  2724. };
  2725. /**
  2726. * Retuns a new Quaternion set from the starting index of the passed array.
  2727. */
  2728. Quaternion.FromArray = function (array, offset) {
  2729. if (!offset) {
  2730. offset = 0;
  2731. }
  2732. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2733. };
  2734. /**
  2735. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2736. */
  2737. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2738. var q = new Quaternion();
  2739. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2740. return q;
  2741. };
  2742. /**
  2743. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2744. */
  2745. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2746. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2747. var halfRoll = roll * 0.5;
  2748. var halfPitch = pitch * 0.5;
  2749. var halfYaw = yaw * 0.5;
  2750. var sinRoll = Math.sin(halfRoll);
  2751. var cosRoll = Math.cos(halfRoll);
  2752. var sinPitch = Math.sin(halfPitch);
  2753. var cosPitch = Math.cos(halfPitch);
  2754. var sinYaw = Math.sin(halfYaw);
  2755. var cosYaw = Math.cos(halfYaw);
  2756. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2757. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2758. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2759. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2760. };
  2761. /**
  2762. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2763. */
  2764. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2765. var result = new Quaternion();
  2766. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2767. return result;
  2768. };
  2769. /**
  2770. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2771. */
  2772. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2773. // Produces a quaternion from Euler angles in the z-x-z orientation
  2774. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2775. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2776. var halfBeta = beta * 0.5;
  2777. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2778. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2779. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2780. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2781. };
  2782. /**
  2783. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2784. * cf to Vector3.RotationFromAxis() documentation.
  2785. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2786. */
  2787. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2788. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2789. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2790. return quat;
  2791. };
  2792. /**
  2793. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2794. * cf to Vector3.RotationFromAxis() documentation.
  2795. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2796. */
  2797. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2798. var rotMat = MathTmp.Matrix[0];
  2799. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2800. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2801. };
  2802. Quaternion.Slerp = function (left, right, amount) {
  2803. var result = Quaternion.Identity();
  2804. Quaternion.SlerpToRef(left, right, amount, result);
  2805. return result;
  2806. };
  2807. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2808. var num2;
  2809. var num3;
  2810. var num = amount;
  2811. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2812. var flag = false;
  2813. if (num4 < 0) {
  2814. flag = true;
  2815. num4 = -num4;
  2816. }
  2817. if (num4 > 0.999999) {
  2818. num3 = 1 - num;
  2819. num2 = flag ? -num : num;
  2820. }
  2821. else {
  2822. var num5 = Math.acos(num4);
  2823. var num6 = (1.0 / Math.sin(num5));
  2824. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2825. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2826. }
  2827. result.x = (num3 * left.x) + (num2 * right.x);
  2828. result.y = (num3 * left.y) + (num2 * right.y);
  2829. result.z = (num3 * left.z) + (num2 * right.z);
  2830. result.w = (num3 * left.w) + (num2 * right.w);
  2831. };
  2832. /**
  2833. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2834. */
  2835. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2836. var squared = amount * amount;
  2837. var cubed = amount * squared;
  2838. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2839. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2840. var part3 = (cubed - (2.0 * squared)) + amount;
  2841. var part4 = cubed - squared;
  2842. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2843. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2844. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2845. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2846. return new Quaternion(x, y, z, w);
  2847. };
  2848. return Quaternion;
  2849. }());
  2850. BABYLON.Quaternion = Quaternion;
  2851. var Matrix = (function () {
  2852. function Matrix() {
  2853. this._isIdentity = false;
  2854. this._isIdentityDirty = true;
  2855. this.m = new Float32Array(16);
  2856. this._markAsUpdated();
  2857. }
  2858. Matrix.prototype._markAsUpdated = function () {
  2859. this.updateFlag = Matrix._updateFlagSeed++;
  2860. this._isIdentityDirty = true;
  2861. };
  2862. // Properties
  2863. /**
  2864. * Boolean : True is the matrix is the identity matrix
  2865. */
  2866. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2867. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2868. if (this._isIdentityDirty) {
  2869. this._isIdentityDirty = false;
  2870. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2871. this._isIdentity = false;
  2872. }
  2873. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2874. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2875. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2876. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2877. this._isIdentity = false;
  2878. }
  2879. else {
  2880. this._isIdentity = true;
  2881. }
  2882. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2883. this._isIdentity = false;
  2884. }
  2885. }
  2886. return this._isIdentity;
  2887. };
  2888. /**
  2889. * Returns the matrix determinant (float).
  2890. */
  2891. Matrix.prototype.determinant = function () {
  2892. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2893. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2894. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2895. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2896. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2897. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2898. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2899. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2900. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2901. };
  2902. // Methods
  2903. /**
  2904. * Returns the matrix underlying array.
  2905. */
  2906. Matrix.prototype.toArray = function () {
  2907. return this.m;
  2908. };
  2909. /**
  2910. * Returns the matrix underlying array.
  2911. */
  2912. Matrix.prototype.asArray = function () {
  2913. return this.toArray();
  2914. };
  2915. /**
  2916. * Inverts in place the Matrix.
  2917. * Returns the Matrix inverted.
  2918. */
  2919. Matrix.prototype.invert = function () {
  2920. this.invertToRef(this);
  2921. return this;
  2922. };
  2923. /**
  2924. * Sets all the matrix elements to zero.
  2925. * Returns the Matrix.
  2926. */
  2927. Matrix.prototype.reset = function () {
  2928. for (var index = 0; index < 16; index++) {
  2929. this.m[index] = 0.0;
  2930. }
  2931. this._markAsUpdated();
  2932. return this;
  2933. };
  2934. /**
  2935. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2936. */
  2937. Matrix.prototype.add = function (other) {
  2938. var result = new Matrix();
  2939. this.addToRef(other, result);
  2940. return result;
  2941. };
  2942. /**
  2943. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2944. * Returns the Matrix.
  2945. */
  2946. Matrix.prototype.addToRef = function (other, result) {
  2947. for (var index = 0; index < 16; index++) {
  2948. result.m[index] = this.m[index] + other.m[index];
  2949. }
  2950. result._markAsUpdated();
  2951. return this;
  2952. };
  2953. /**
  2954. * Adds in place the passed matrix to the current Matrix.
  2955. * Returns the updated Matrix.
  2956. */
  2957. Matrix.prototype.addToSelf = function (other) {
  2958. for (var index = 0; index < 16; index++) {
  2959. this.m[index] += other.m[index];
  2960. }
  2961. this._markAsUpdated();
  2962. return this;
  2963. };
  2964. /**
  2965. * Sets the passed matrix with the current inverted Matrix.
  2966. * Returns the unmodified current Matrix.
  2967. */
  2968. Matrix.prototype.invertToRef = function (other) {
  2969. var l1 = this.m[0];
  2970. var l2 = this.m[1];
  2971. var l3 = this.m[2];
  2972. var l4 = this.m[3];
  2973. var l5 = this.m[4];
  2974. var l6 = this.m[5];
  2975. var l7 = this.m[6];
  2976. var l8 = this.m[7];
  2977. var l9 = this.m[8];
  2978. var l10 = this.m[9];
  2979. var l11 = this.m[10];
  2980. var l12 = this.m[11];
  2981. var l13 = this.m[12];
  2982. var l14 = this.m[13];
  2983. var l15 = this.m[14];
  2984. var l16 = this.m[15];
  2985. var l17 = (l11 * l16) - (l12 * l15);
  2986. var l18 = (l10 * l16) - (l12 * l14);
  2987. var l19 = (l10 * l15) - (l11 * l14);
  2988. var l20 = (l9 * l16) - (l12 * l13);
  2989. var l21 = (l9 * l15) - (l11 * l13);
  2990. var l22 = (l9 * l14) - (l10 * l13);
  2991. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2992. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2993. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2994. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2995. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2996. var l28 = (l7 * l16) - (l8 * l15);
  2997. var l29 = (l6 * l16) - (l8 * l14);
  2998. var l30 = (l6 * l15) - (l7 * l14);
  2999. var l31 = (l5 * l16) - (l8 * l13);
  3000. var l32 = (l5 * l15) - (l7 * l13);
  3001. var l33 = (l5 * l14) - (l6 * l13);
  3002. var l34 = (l7 * l12) - (l8 * l11);
  3003. var l35 = (l6 * l12) - (l8 * l10);
  3004. var l36 = (l6 * l11) - (l7 * l10);
  3005. var l37 = (l5 * l12) - (l8 * l9);
  3006. var l38 = (l5 * l11) - (l7 * l9);
  3007. var l39 = (l5 * l10) - (l6 * l9);
  3008. other.m[0] = l23 * l27;
  3009. other.m[4] = l24 * l27;
  3010. other.m[8] = l25 * l27;
  3011. other.m[12] = l26 * l27;
  3012. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3013. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3014. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3015. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3016. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3017. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3018. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3019. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3020. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3021. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3022. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3023. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3024. other._markAsUpdated();
  3025. return this;
  3026. };
  3027. /**
  3028. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3029. * Returns the updated Matrix.
  3030. */
  3031. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3032. this.m[12] = x;
  3033. this.m[13] = y;
  3034. this.m[14] = z;
  3035. this._markAsUpdated();
  3036. return this;
  3037. };
  3038. /**
  3039. * Inserts the translation vector in the current Matrix.
  3040. * Returns the updated Matrix.
  3041. */
  3042. Matrix.prototype.setTranslation = function (vector3) {
  3043. this.m[12] = vector3.x;
  3044. this.m[13] = vector3.y;
  3045. this.m[14] = vector3.z;
  3046. this._markAsUpdated();
  3047. return this;
  3048. };
  3049. /**
  3050. * Returns a new Vector3 as the extracted translation from the Matrix.
  3051. */
  3052. Matrix.prototype.getTranslation = function () {
  3053. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3054. };
  3055. /**
  3056. * Fill a Vector3 with the extracted translation from the Matrix.
  3057. */
  3058. Matrix.prototype.getTranslationToRef = function (result) {
  3059. result.x = this.m[12];
  3060. result.y = this.m[13];
  3061. result.z = this.m[14];
  3062. return this;
  3063. };
  3064. /**
  3065. * Remove rotation and scaling part from the Matrix.
  3066. * Returns the updated Matrix.
  3067. */
  3068. Matrix.prototype.removeRotationAndScaling = function () {
  3069. this.setRowFromFloats(0, 1, 0, 0, 0);
  3070. this.setRowFromFloats(1, 0, 1, 0, 0);
  3071. this.setRowFromFloats(2, 0, 0, 1, 0);
  3072. return this;
  3073. };
  3074. /**
  3075. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3076. */
  3077. Matrix.prototype.multiply = function (other) {
  3078. var result = new Matrix();
  3079. this.multiplyToRef(other, result);
  3080. return result;
  3081. };
  3082. /**
  3083. * Updates the current Matrix from the passed one values.
  3084. * Returns the updated Matrix.
  3085. */
  3086. Matrix.prototype.copyFrom = function (other) {
  3087. for (var index = 0; index < 16; index++) {
  3088. this.m[index] = other.m[index];
  3089. }
  3090. this._markAsUpdated();
  3091. return this;
  3092. };
  3093. /**
  3094. * Populates the passed array from the starting index with the Matrix values.
  3095. * Returns the Matrix.
  3096. */
  3097. Matrix.prototype.copyToArray = function (array, offset) {
  3098. if (offset === void 0) { offset = 0; }
  3099. for (var index = 0; index < 16; index++) {
  3100. array[offset + index] = this.m[index];
  3101. }
  3102. return this;
  3103. };
  3104. /**
  3105. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3106. */
  3107. Matrix.prototype.multiplyToRef = function (other, result) {
  3108. this.multiplyToArray(other, result.m, 0);
  3109. result._markAsUpdated();
  3110. return this;
  3111. };
  3112. /**
  3113. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3114. */
  3115. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3116. var tm0 = this.m[0];
  3117. var tm1 = this.m[1];
  3118. var tm2 = this.m[2];
  3119. var tm3 = this.m[3];
  3120. var tm4 = this.m[4];
  3121. var tm5 = this.m[5];
  3122. var tm6 = this.m[6];
  3123. var tm7 = this.m[7];
  3124. var tm8 = this.m[8];
  3125. var tm9 = this.m[9];
  3126. var tm10 = this.m[10];
  3127. var tm11 = this.m[11];
  3128. var tm12 = this.m[12];
  3129. var tm13 = this.m[13];
  3130. var tm14 = this.m[14];
  3131. var tm15 = this.m[15];
  3132. var om0 = other.m[0];
  3133. var om1 = other.m[1];
  3134. var om2 = other.m[2];
  3135. var om3 = other.m[3];
  3136. var om4 = other.m[4];
  3137. var om5 = other.m[5];
  3138. var om6 = other.m[6];
  3139. var om7 = other.m[7];
  3140. var om8 = other.m[8];
  3141. var om9 = other.m[9];
  3142. var om10 = other.m[10];
  3143. var om11 = other.m[11];
  3144. var om12 = other.m[12];
  3145. var om13 = other.m[13];
  3146. var om14 = other.m[14];
  3147. var om15 = other.m[15];
  3148. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3149. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3150. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3151. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3152. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3153. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3154. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3155. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3156. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3157. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3158. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3159. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3160. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3161. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3162. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3163. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3164. return this;
  3165. };
  3166. /**
  3167. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3168. */
  3169. Matrix.prototype.equals = function (value) {
  3170. return value &&
  3171. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3172. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3173. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3174. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3175. };
  3176. /**
  3177. * Returns a new Matrix from the current Matrix.
  3178. */
  3179. Matrix.prototype.clone = function () {
  3180. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  3181. };
  3182. /**
  3183. * Returns the string "Matrix"
  3184. */
  3185. Matrix.prototype.getClassName = function () {
  3186. return "Matrix";
  3187. };
  3188. /**
  3189. * Returns the Matrix hash code.
  3190. */
  3191. Matrix.prototype.getHashCode = function () {
  3192. var hash = this.m[0] || 0;
  3193. for (var i = 1; i < 16; i++) {
  3194. hash = (hash * 397) ^ (this.m[i] || 0);
  3195. }
  3196. return hash;
  3197. };
  3198. /**
  3199. * Decomposes the current Matrix into :
  3200. * - a scale vector3 passed as a reference to update,
  3201. * - a rotation quaternion passed as a reference to update,
  3202. * - a translation vector3 passed as a reference to update.
  3203. * Returns the boolean `true`.
  3204. */
  3205. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3206. translation.x = this.m[12];
  3207. translation.y = this.m[13];
  3208. translation.z = this.m[14];
  3209. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3210. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3211. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3212. if (this.determinant() <= 0) {
  3213. scale.y *= -1;
  3214. }
  3215. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3216. rotation.x = 0;
  3217. rotation.y = 0;
  3218. rotation.z = 0;
  3219. rotation.w = 1;
  3220. return false;
  3221. }
  3222. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  3223. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3224. return true;
  3225. };
  3226. /**
  3227. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3228. */
  3229. Matrix.prototype.getRotationMatrix = function () {
  3230. var result = Matrix.Identity();
  3231. this.getRotationMatrixToRef(result);
  3232. return result;
  3233. };
  3234. /**
  3235. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3236. * Returns the current Matrix.
  3237. */
  3238. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3239. var m = this.m;
  3240. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3241. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3242. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3243. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3244. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3245. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3246. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  3247. return this;
  3248. };
  3249. // Statics
  3250. /**
  3251. * Returns a new Matrix set from the starting index of the passed array.
  3252. */
  3253. Matrix.FromArray = function (array, offset) {
  3254. var result = new Matrix();
  3255. if (!offset) {
  3256. offset = 0;
  3257. }
  3258. Matrix.FromArrayToRef(array, offset, result);
  3259. return result;
  3260. };
  3261. /**
  3262. * Sets the passed "result" matrix from the starting index of the passed array.
  3263. */
  3264. Matrix.FromArrayToRef = function (array, offset, result) {
  3265. for (var index = 0; index < 16; index++) {
  3266. result.m[index] = array[index + offset];
  3267. }
  3268. result._markAsUpdated();
  3269. };
  3270. /**
  3271. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3272. */
  3273. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3274. for (var index = 0; index < 16; index++) {
  3275. result.m[index] = array[index + offset] * scale;
  3276. }
  3277. result._markAsUpdated();
  3278. };
  3279. /**
  3280. * Sets the passed matrix "result" with the 16 passed floats.
  3281. */
  3282. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3283. result.m[0] = initialM11;
  3284. result.m[1] = initialM12;
  3285. result.m[2] = initialM13;
  3286. result.m[3] = initialM14;
  3287. result.m[4] = initialM21;
  3288. result.m[5] = initialM22;
  3289. result.m[6] = initialM23;
  3290. result.m[7] = initialM24;
  3291. result.m[8] = initialM31;
  3292. result.m[9] = initialM32;
  3293. result.m[10] = initialM33;
  3294. result.m[11] = initialM34;
  3295. result.m[12] = initialM41;
  3296. result.m[13] = initialM42;
  3297. result.m[14] = initialM43;
  3298. result.m[15] = initialM44;
  3299. result._markAsUpdated();
  3300. };
  3301. /**
  3302. * Returns the index-th row of the current matrix as a new Vector4.
  3303. */
  3304. Matrix.prototype.getRow = function (index) {
  3305. if (index < 0 || index > 3) {
  3306. return null;
  3307. }
  3308. var i = index * 4;
  3309. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3310. };
  3311. /**
  3312. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3313. * Returns the updated Matrix.
  3314. */
  3315. Matrix.prototype.setRow = function (index, row) {
  3316. if (index < 0 || index > 3) {
  3317. return this;
  3318. }
  3319. var i = index * 4;
  3320. this.m[i + 0] = row.x;
  3321. this.m[i + 1] = row.y;
  3322. this.m[i + 2] = row.z;
  3323. this.m[i + 3] = row.w;
  3324. this._markAsUpdated();
  3325. return this;
  3326. };
  3327. /**
  3328. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3329. * Returns the updated Matrix.
  3330. */
  3331. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3332. if (index < 0 || index > 3) {
  3333. return this;
  3334. }
  3335. var i = index * 4;
  3336. this.m[i + 0] = x;
  3337. this.m[i + 1] = y;
  3338. this.m[i + 2] = z;
  3339. this.m[i + 3] = w;
  3340. this._markAsUpdated();
  3341. return this;
  3342. };
  3343. /**
  3344. * Returns a new Matrix set from the 16 passed floats.
  3345. */
  3346. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3347. var result = new Matrix();
  3348. result.m[0] = initialM11;
  3349. result.m[1] = initialM12;
  3350. result.m[2] = initialM13;
  3351. result.m[3] = initialM14;
  3352. result.m[4] = initialM21;
  3353. result.m[5] = initialM22;
  3354. result.m[6] = initialM23;
  3355. result.m[7] = initialM24;
  3356. result.m[8] = initialM31;
  3357. result.m[9] = initialM32;
  3358. result.m[10] = initialM33;
  3359. result.m[11] = initialM34;
  3360. result.m[12] = initialM41;
  3361. result.m[13] = initialM42;
  3362. result.m[14] = initialM43;
  3363. result.m[15] = initialM44;
  3364. return result;
  3365. };
  3366. /**
  3367. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3368. */
  3369. Matrix.Compose = function (scale, rotation, translation) {
  3370. var result = Matrix.Identity();
  3371. Matrix.ComposeToRef(scale, rotation, translation, result);
  3372. return result;
  3373. };
  3374. /**
  3375. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3376. */
  3377. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3378. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3379. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3380. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3381. result.setTranslation(translation);
  3382. };
  3383. /**
  3384. * Returns a new indentity Matrix.
  3385. */
  3386. Matrix.Identity = function () {
  3387. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  3388. };
  3389. /**
  3390. * Sets the passed "result" as an identity matrix.
  3391. */
  3392. Matrix.IdentityToRef = function (result) {
  3393. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  3394. };
  3395. /**
  3396. * Returns a new zero Matrix.
  3397. */
  3398. Matrix.Zero = function () {
  3399. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  3400. };
  3401. /**
  3402. * Returns a new rotation matrix for "angle" radians around the X axis.
  3403. */
  3404. Matrix.RotationX = function (angle) {
  3405. var result = new Matrix();
  3406. Matrix.RotationXToRef(angle, result);
  3407. return result;
  3408. };
  3409. /**
  3410. * Returns a new Matrix as the passed inverted one.
  3411. */
  3412. Matrix.Invert = function (source) {
  3413. var result = new Matrix();
  3414. source.invertToRef(result);
  3415. return result;
  3416. };
  3417. /**
  3418. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3419. */
  3420. Matrix.RotationXToRef = function (angle, result) {
  3421. var s = Math.sin(angle);
  3422. var c = Math.cos(angle);
  3423. result.m[0] = 1.0;
  3424. result.m[15] = 1.0;
  3425. result.m[5] = c;
  3426. result.m[10] = c;
  3427. result.m[9] = -s;
  3428. result.m[6] = s;
  3429. result.m[1] = 0.0;
  3430. result.m[2] = 0.0;
  3431. result.m[3] = 0.0;
  3432. result.m[4] = 0.0;
  3433. result.m[7] = 0.0;
  3434. result.m[8] = 0.0;
  3435. result.m[11] = 0.0;
  3436. result.m[12] = 0.0;
  3437. result.m[13] = 0.0;
  3438. result.m[14] = 0.0;
  3439. result._markAsUpdated();
  3440. };
  3441. /**
  3442. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3443. */
  3444. Matrix.RotationY = function (angle) {
  3445. var result = new Matrix();
  3446. Matrix.RotationYToRef(angle, result);
  3447. return result;
  3448. };
  3449. /**
  3450. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3451. */
  3452. Matrix.RotationYToRef = function (angle, result) {
  3453. var s = Math.sin(angle);
  3454. var c = Math.cos(angle);
  3455. result.m[5] = 1.0;
  3456. result.m[15] = 1.0;
  3457. result.m[0] = c;
  3458. result.m[2] = -s;
  3459. result.m[8] = s;
  3460. result.m[10] = c;
  3461. result.m[1] = 0.0;
  3462. result.m[3] = 0.0;
  3463. result.m[4] = 0.0;
  3464. result.m[6] = 0.0;
  3465. result.m[7] = 0.0;
  3466. result.m[9] = 0.0;
  3467. result.m[11] = 0.0;
  3468. result.m[12] = 0.0;
  3469. result.m[13] = 0.0;
  3470. result.m[14] = 0.0;
  3471. result._markAsUpdated();
  3472. };
  3473. /**
  3474. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3475. */
  3476. Matrix.RotationZ = function (angle) {
  3477. var result = new Matrix();
  3478. Matrix.RotationZToRef(angle, result);
  3479. return result;
  3480. };
  3481. /**
  3482. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3483. */
  3484. Matrix.RotationZToRef = function (angle, result) {
  3485. var s = Math.sin(angle);
  3486. var c = Math.cos(angle);
  3487. result.m[10] = 1.0;
  3488. result.m[15] = 1.0;
  3489. result.m[0] = c;
  3490. result.m[1] = s;
  3491. result.m[4] = -s;
  3492. result.m[5] = c;
  3493. result.m[2] = 0.0;
  3494. result.m[3] = 0.0;
  3495. result.m[6] = 0.0;
  3496. result.m[7] = 0.0;
  3497. result.m[8] = 0.0;
  3498. result.m[9] = 0.0;
  3499. result.m[11] = 0.0;
  3500. result.m[12] = 0.0;
  3501. result.m[13] = 0.0;
  3502. result.m[14] = 0.0;
  3503. result._markAsUpdated();
  3504. };
  3505. /**
  3506. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3507. */
  3508. Matrix.RotationAxis = function (axis, angle) {
  3509. var result = Matrix.Zero();
  3510. Matrix.RotationAxisToRef(axis, angle, result);
  3511. return result;
  3512. };
  3513. /**
  3514. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3515. */
  3516. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3517. var s = Math.sin(-angle);
  3518. var c = Math.cos(-angle);
  3519. var c1 = 1 - c;
  3520. axis.normalize();
  3521. result.m[0] = (axis.x * axis.x) * c1 + c;
  3522. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3523. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3524. result.m[3] = 0.0;
  3525. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3526. result.m[5] = (axis.y * axis.y) * c1 + c;
  3527. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3528. result.m[7] = 0.0;
  3529. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3530. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3531. result.m[10] = (axis.z * axis.z) * c1 + c;
  3532. result.m[11] = 0.0;
  3533. result.m[15] = 1.0;
  3534. result._markAsUpdated();
  3535. };
  3536. /**
  3537. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3538. */
  3539. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3540. var result = new Matrix();
  3541. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3542. return result;
  3543. };
  3544. /**
  3545. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3546. */
  3547. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3548. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3549. this._tempQuaternion.toRotationMatrix(result);
  3550. };
  3551. /**
  3552. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3553. */
  3554. Matrix.Scaling = function (x, y, z) {
  3555. var result = Matrix.Zero();
  3556. Matrix.ScalingToRef(x, y, z, result);
  3557. return result;
  3558. };
  3559. /**
  3560. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3561. */
  3562. Matrix.ScalingToRef = function (x, y, z, result) {
  3563. result.m[0] = x;
  3564. result.m[1] = 0.0;
  3565. result.m[2] = 0.0;
  3566. result.m[3] = 0.0;
  3567. result.m[4] = 0.0;
  3568. result.m[5] = y;
  3569. result.m[6] = 0.0;
  3570. result.m[7] = 0.0;
  3571. result.m[8] = 0.0;
  3572. result.m[9] = 0.0;
  3573. result.m[10] = z;
  3574. result.m[11] = 0.0;
  3575. result.m[12] = 0.0;
  3576. result.m[13] = 0.0;
  3577. result.m[14] = 0.0;
  3578. result.m[15] = 1.0;
  3579. result._markAsUpdated();
  3580. };
  3581. /**
  3582. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3583. */
  3584. Matrix.Translation = function (x, y, z) {
  3585. var result = Matrix.Identity();
  3586. Matrix.TranslationToRef(x, y, z, result);
  3587. return result;
  3588. };
  3589. /**
  3590. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3591. */
  3592. Matrix.TranslationToRef = function (x, y, z, result) {
  3593. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  3594. };
  3595. /**
  3596. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3597. */
  3598. Matrix.Lerp = function (startValue, endValue, gradient) {
  3599. var result = Matrix.Zero();
  3600. for (var index = 0; index < 16; index++) {
  3601. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3602. }
  3603. result._markAsUpdated();
  3604. return result;
  3605. };
  3606. /**
  3607. * Returns a new Matrix whose values are computed by :
  3608. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3609. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3610. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3611. */
  3612. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3613. var startScale = new Vector3(0, 0, 0);
  3614. var startRotation = new Quaternion();
  3615. var startTranslation = new Vector3(0, 0, 0);
  3616. startValue.decompose(startScale, startRotation, startTranslation);
  3617. var endScale = new Vector3(0, 0, 0);
  3618. var endRotation = new Quaternion();
  3619. var endTranslation = new Vector3(0, 0, 0);
  3620. endValue.decompose(endScale, endRotation, endTranslation);
  3621. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3622. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3623. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3624. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3625. };
  3626. /**
  3627. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3628. * This methods works for a Left-Handed system.
  3629. */
  3630. Matrix.LookAtLH = function (eye, target, up) {
  3631. var result = Matrix.Zero();
  3632. Matrix.LookAtLHToRef(eye, target, up, result);
  3633. return result;
  3634. };
  3635. /**
  3636. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3637. * This methods works for a Left-Handed system.
  3638. */
  3639. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3640. // Z axis
  3641. target.subtractToRef(eye, this._zAxis);
  3642. this._zAxis.normalize();
  3643. // X axis
  3644. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3645. if (this._xAxis.lengthSquared() === 0) {
  3646. this._xAxis.x = 1.0;
  3647. }
  3648. else {
  3649. this._xAxis.normalize();
  3650. }
  3651. // Y axis
  3652. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3653. this._yAxis.normalize();
  3654. // Eye angles
  3655. var ex = -Vector3.Dot(this._xAxis, eye);
  3656. var ey = -Vector3.Dot(this._yAxis, eye);
  3657. var ez = -Vector3.Dot(this._zAxis, eye);
  3658. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3659. };
  3660. /**
  3661. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3662. * This methods works for a Right-Handed system.
  3663. */
  3664. Matrix.LookAtRH = function (eye, target, up) {
  3665. var result = Matrix.Zero();
  3666. Matrix.LookAtRHToRef(eye, target, up, result);
  3667. return result;
  3668. };
  3669. /**
  3670. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3671. * This methods works for a Left-Handed system.
  3672. */
  3673. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3674. // Z axis
  3675. eye.subtractToRef(target, this._zAxis);
  3676. this._zAxis.normalize();
  3677. // X axis
  3678. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3679. if (this._xAxis.lengthSquared() === 0) {
  3680. this._xAxis.x = 1.0;
  3681. }
  3682. else {
  3683. this._xAxis.normalize();
  3684. }
  3685. // Y axis
  3686. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3687. this._yAxis.normalize();
  3688. // Eye angles
  3689. var ex = -Vector3.Dot(this._xAxis, eye);
  3690. var ey = -Vector3.Dot(this._yAxis, eye);
  3691. var ez = -Vector3.Dot(this._zAxis, eye);
  3692. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3693. };
  3694. /**
  3695. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3696. */
  3697. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3698. var matrix = Matrix.Zero();
  3699. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3700. return matrix;
  3701. };
  3702. /**
  3703. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3704. */
  3705. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3706. var n = znear;
  3707. var f = zfar;
  3708. var a = 2.0 / width;
  3709. var b = 2.0 / height;
  3710. var c = 2.0 / (f - n);
  3711. var d = -(f + n) / (f - n);
  3712. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3713. };
  3714. /**
  3715. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3716. */
  3717. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3718. var matrix = Matrix.Zero();
  3719. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3720. return matrix;
  3721. };
  3722. /**
  3723. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3724. */
  3725. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3726. var n = znear;
  3727. var f = zfar;
  3728. var a = 2.0 / (right - left);
  3729. var b = 2.0 / (top - bottom);
  3730. var c = 2.0 / (f - n);
  3731. var d = -(f + n) / (f - n);
  3732. var i0 = (left + right) / (left - right);
  3733. var i1 = (top + bottom) / (bottom - top);
  3734. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3735. };
  3736. /**
  3737. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3738. */
  3739. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3740. var matrix = Matrix.Zero();
  3741. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3742. return matrix;
  3743. };
  3744. /**
  3745. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3746. */
  3747. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3748. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3749. result.m[10] *= -1.0;
  3750. };
  3751. /**
  3752. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3753. */
  3754. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3755. var matrix = Matrix.Zero();
  3756. var n = znear;
  3757. var f = zfar;
  3758. var a = 2.0 * n / width;
  3759. var b = 2.0 * n / height;
  3760. var c = (f + n) / (f - n);
  3761. var d = -2.0 * f * n / (f - n);
  3762. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3763. return matrix;
  3764. };
  3765. /**
  3766. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3767. */
  3768. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3769. var matrix = Matrix.Zero();
  3770. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3771. return matrix;
  3772. };
  3773. /**
  3774. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3775. */
  3776. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3777. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3778. var n = znear;
  3779. var f = zfar;
  3780. var t = 1.0 / (Math.tan(fov * 0.5));
  3781. var a = isVerticalFovFixed ? (t / aspect) : t;
  3782. var b = isVerticalFovFixed ? t : (t * aspect);
  3783. var c = (f + n) / (f - n);
  3784. var d = -2.0 * f * n / (f - n);
  3785. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3786. };
  3787. /**
  3788. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3789. */
  3790. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3791. var matrix = Matrix.Zero();
  3792. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3793. return matrix;
  3794. };
  3795. /**
  3796. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3797. */
  3798. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3799. //alternatively this could be expressed as:
  3800. // m = PerspectiveFovLHToRef
  3801. // m[10] *= -1.0;
  3802. // m[11] *= -1.0;
  3803. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3804. var n = znear;
  3805. var f = zfar;
  3806. var t = 1.0 / (Math.tan(fov * 0.5));
  3807. var a = isVerticalFovFixed ? (t / aspect) : t;
  3808. var b = isVerticalFovFixed ? t : (t * aspect);
  3809. var c = -(f + n) / (f - n);
  3810. var d = -2 * f * n / (f - n);
  3811. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3812. };
  3813. /**
  3814. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3815. */
  3816. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3817. if (rightHanded === void 0) { rightHanded = false; }
  3818. var rightHandedFactor = rightHanded ? -1 : 1;
  3819. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3820. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3821. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3822. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3823. var xScale = 2.0 / (leftTan + rightTan);
  3824. var yScale = 2.0 / (upTan + downTan);
  3825. result.m[0] = xScale;
  3826. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3827. result.m[5] = yScale;
  3828. result.m[6] = result.m[7] = 0.0;
  3829. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3830. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3831. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3832. result.m[10] = -zfar / (znear - zfar);
  3833. result.m[11] = 1.0 * rightHandedFactor;
  3834. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3835. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3836. // result.m[14] = (znear * zfar) / (znear - zfar);
  3837. result._markAsUpdated();
  3838. };
  3839. /**
  3840. * Returns the final transformation matrix : world * view * projection * viewport
  3841. */
  3842. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3843. var cw = viewport.width;
  3844. var ch = viewport.height;
  3845. var cx = viewport.x;
  3846. var cy = viewport.y;
  3847. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  3848. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3849. };
  3850. /**
  3851. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3852. */
  3853. Matrix.GetAsMatrix2x2 = function (matrix) {
  3854. return new Float32Array([
  3855. matrix.m[0], matrix.m[1],
  3856. matrix.m[4], matrix.m[5]
  3857. ]);
  3858. };
  3859. /**
  3860. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3861. */
  3862. Matrix.GetAsMatrix3x3 = function (matrix) {
  3863. return new Float32Array([
  3864. matrix.m[0], matrix.m[1], matrix.m[2],
  3865. matrix.m[4], matrix.m[5], matrix.m[6],
  3866. matrix.m[8], matrix.m[9], matrix.m[10]
  3867. ]);
  3868. };
  3869. /**
  3870. * Compute the transpose of the passed Matrix.
  3871. * Returns a new Matrix.
  3872. */
  3873. Matrix.Transpose = function (matrix) {
  3874. var result = new Matrix();
  3875. result.m[0] = matrix.m[0];
  3876. result.m[1] = matrix.m[4];
  3877. result.m[2] = matrix.m[8];
  3878. result.m[3] = matrix.m[12];
  3879. result.m[4] = matrix.m[1];
  3880. result.m[5] = matrix.m[5];
  3881. result.m[6] = matrix.m[9];
  3882. result.m[7] = matrix.m[13];
  3883. result.m[8] = matrix.m[2];
  3884. result.m[9] = matrix.m[6];
  3885. result.m[10] = matrix.m[10];
  3886. result.m[11] = matrix.m[14];
  3887. result.m[12] = matrix.m[3];
  3888. result.m[13] = matrix.m[7];
  3889. result.m[14] = matrix.m[11];
  3890. result.m[15] = matrix.m[15];
  3891. return result;
  3892. };
  3893. /**
  3894. * Returns a new Matrix as the reflection matrix across the passed plane.
  3895. */
  3896. Matrix.Reflection = function (plane) {
  3897. var matrix = new Matrix();
  3898. Matrix.ReflectionToRef(plane, matrix);
  3899. return matrix;
  3900. };
  3901. /**
  3902. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3903. */
  3904. Matrix.ReflectionToRef = function (plane, result) {
  3905. plane.normalize();
  3906. var x = plane.normal.x;
  3907. var y = plane.normal.y;
  3908. var z = plane.normal.z;
  3909. var temp = -2 * x;
  3910. var temp2 = -2 * y;
  3911. var temp3 = -2 * z;
  3912. result.m[0] = (temp * x) + 1;
  3913. result.m[1] = temp2 * x;
  3914. result.m[2] = temp3 * x;
  3915. result.m[3] = 0.0;
  3916. result.m[4] = temp * y;
  3917. result.m[5] = (temp2 * y) + 1;
  3918. result.m[6] = temp3 * y;
  3919. result.m[7] = 0.0;
  3920. result.m[8] = temp * z;
  3921. result.m[9] = temp2 * z;
  3922. result.m[10] = (temp3 * z) + 1;
  3923. result.m[11] = 0.0;
  3924. result.m[12] = temp * plane.d;
  3925. result.m[13] = temp2 * plane.d;
  3926. result.m[14] = temp3 * plane.d;
  3927. result.m[15] = 1.0;
  3928. result._markAsUpdated();
  3929. };
  3930. /**
  3931. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3932. */
  3933. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3934. result.m[0] = xaxis.x;
  3935. result.m[1] = xaxis.y;
  3936. result.m[2] = xaxis.z;
  3937. result.m[3] = 0.0;
  3938. result.m[4] = yaxis.x;
  3939. result.m[5] = yaxis.y;
  3940. result.m[6] = yaxis.z;
  3941. result.m[7] = 0.0;
  3942. result.m[8] = zaxis.x;
  3943. result.m[9] = zaxis.y;
  3944. result.m[10] = zaxis.z;
  3945. result.m[11] = 0.0;
  3946. result.m[12] = 0.0;
  3947. result.m[13] = 0.0;
  3948. result.m[14] = 0.0;
  3949. result.m[15] = 1.0;
  3950. result._markAsUpdated();
  3951. };
  3952. /**
  3953. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3954. */
  3955. Matrix.FromQuaternionToRef = function (quat, result) {
  3956. var xx = quat.x * quat.x;
  3957. var yy = quat.y * quat.y;
  3958. var zz = quat.z * quat.z;
  3959. var xy = quat.x * quat.y;
  3960. var zw = quat.z * quat.w;
  3961. var zx = quat.z * quat.x;
  3962. var yw = quat.y * quat.w;
  3963. var yz = quat.y * quat.z;
  3964. var xw = quat.x * quat.w;
  3965. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3966. result.m[1] = 2.0 * (xy + zw);
  3967. result.m[2] = 2.0 * (zx - yw);
  3968. result.m[3] = 0.0;
  3969. result.m[4] = 2.0 * (xy - zw);
  3970. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3971. result.m[6] = 2.0 * (yz + xw);
  3972. result.m[7] = 0.0;
  3973. result.m[8] = 2.0 * (zx + yw);
  3974. result.m[9] = 2.0 * (yz - xw);
  3975. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3976. result.m[11] = 0.0;
  3977. result.m[12] = 0.0;
  3978. result.m[13] = 0.0;
  3979. result.m[14] = 0.0;
  3980. result.m[15] = 1.0;
  3981. result._markAsUpdated();
  3982. };
  3983. Matrix._tempQuaternion = new Quaternion();
  3984. Matrix._xAxis = Vector3.Zero();
  3985. Matrix._yAxis = Vector3.Zero();
  3986. Matrix._zAxis = Vector3.Zero();
  3987. Matrix._updateFlagSeed = 0;
  3988. return Matrix;
  3989. }());
  3990. BABYLON.Matrix = Matrix;
  3991. var Plane = (function () {
  3992. /**
  3993. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3994. */
  3995. function Plane(a, b, c, d) {
  3996. this.normal = new Vector3(a, b, c);
  3997. this.d = d;
  3998. }
  3999. /**
  4000. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4001. */
  4002. Plane.prototype.asArray = function () {
  4003. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4004. };
  4005. // Methods
  4006. /**
  4007. * Returns a new plane copied from the current Plane.
  4008. */
  4009. Plane.prototype.clone = function () {
  4010. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4011. };
  4012. /**
  4013. * Returns the string "Plane".
  4014. */
  4015. Plane.prototype.getClassName = function () {
  4016. return "Plane";
  4017. };
  4018. /**
  4019. * Returns the Plane hash code.
  4020. */
  4021. Plane.prototype.getHashCode = function () {
  4022. var hash = this.normal.getHashCode();
  4023. hash = (hash * 397) ^ (this.d || 0);
  4024. return hash;
  4025. };
  4026. /**
  4027. * Normalize the current Plane in place.
  4028. * Returns the updated Plane.
  4029. */
  4030. Plane.prototype.normalize = function () {
  4031. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4032. var magnitude = 0.0;
  4033. if (norm !== 0) {
  4034. magnitude = 1.0 / norm;
  4035. }
  4036. this.normal.x *= magnitude;
  4037. this.normal.y *= magnitude;
  4038. this.normal.z *= magnitude;
  4039. this.d *= magnitude;
  4040. return this;
  4041. };
  4042. /**
  4043. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4044. */
  4045. Plane.prototype.transform = function (transformation) {
  4046. var transposedMatrix = Matrix.Transpose(transformation);
  4047. var x = this.normal.x;
  4048. var y = this.normal.y;
  4049. var z = this.normal.z;
  4050. var d = this.d;
  4051. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4052. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4053. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4054. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4055. return new Plane(normalX, normalY, normalZ, finalD);
  4056. };
  4057. /**
  4058. * Returns the dot product (float) of the point coordinates and the plane normal.
  4059. */
  4060. Plane.prototype.dotCoordinate = function (point) {
  4061. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4062. };
  4063. /**
  4064. * Updates the current Plane from the plane defined by the three passed points.
  4065. * Returns the updated Plane.
  4066. */
  4067. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4068. var x1 = point2.x - point1.x;
  4069. var y1 = point2.y - point1.y;
  4070. var z1 = point2.z - point1.z;
  4071. var x2 = point3.x - point1.x;
  4072. var y2 = point3.y - point1.y;
  4073. var z2 = point3.z - point1.z;
  4074. var yz = (y1 * z2) - (z1 * y2);
  4075. var xz = (z1 * x2) - (x1 * z2);
  4076. var xy = (x1 * y2) - (y1 * x2);
  4077. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4078. var invPyth;
  4079. if (pyth !== 0) {
  4080. invPyth = 1.0 / pyth;
  4081. }
  4082. else {
  4083. invPyth = 0.0;
  4084. }
  4085. this.normal.x = yz * invPyth;
  4086. this.normal.y = xz * invPyth;
  4087. this.normal.z = xy * invPyth;
  4088. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  4089. return this;
  4090. };
  4091. /**
  4092. * Boolean : True is the vector "direction" is the same side than the plane normal.
  4093. */
  4094. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  4095. var dot = Vector3.Dot(this.normal, direction);
  4096. return (dot <= epsilon);
  4097. };
  4098. /**
  4099. * Returns the signed distance (float) from the passed point to the Plane.
  4100. */
  4101. Plane.prototype.signedDistanceTo = function (point) {
  4102. return Vector3.Dot(point, this.normal) + this.d;
  4103. };
  4104. // Statics
  4105. /**
  4106. * Returns a new Plane from the passed array.
  4107. */
  4108. Plane.FromArray = function (array) {
  4109. return new Plane(array[0], array[1], array[2], array[3]);
  4110. };
  4111. /**
  4112. * Returns a new Plane defined by the three passed points.
  4113. */
  4114. Plane.FromPoints = function (point1, point2, point3) {
  4115. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4116. result.copyFromPoints(point1, point2, point3);
  4117. return result;
  4118. };
  4119. /**
  4120. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4121. * Note : the vector "normal" is updated because normalized.
  4122. */
  4123. Plane.FromPositionAndNormal = function (origin, normal) {
  4124. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4125. normal.normalize();
  4126. result.normal = normal;
  4127. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4128. return result;
  4129. };
  4130. /**
  4131. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4132. */
  4133. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4134. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4135. return Vector3.Dot(point, normal) + d;
  4136. };
  4137. return Plane;
  4138. }());
  4139. BABYLON.Plane = Plane;
  4140. var Viewport = (function () {
  4141. /**
  4142. * Creates a Viewport object located at (x, y) and sized (width, height).
  4143. */
  4144. function Viewport(x, y, width, height) {
  4145. this.x = x;
  4146. this.y = y;
  4147. this.width = width;
  4148. this.height = height;
  4149. }
  4150. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4151. if (renderWidthOrEngine.getRenderWidth) {
  4152. var engine = renderWidthOrEngine;
  4153. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4154. }
  4155. var renderWidth = renderWidthOrEngine;
  4156. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4157. };
  4158. /**
  4159. * Returns a new Viewport copied from the current one.
  4160. */
  4161. Viewport.prototype.clone = function () {
  4162. return new Viewport(this.x, this.y, this.width, this.height);
  4163. };
  4164. return Viewport;
  4165. }());
  4166. BABYLON.Viewport = Viewport;
  4167. var Frustum = (function () {
  4168. function Frustum() {
  4169. }
  4170. /**
  4171. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4172. */
  4173. Frustum.GetPlanes = function (transform) {
  4174. var frustumPlanes = [];
  4175. for (var index = 0; index < 6; index++) {
  4176. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4177. }
  4178. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4179. return frustumPlanes;
  4180. };
  4181. /**
  4182. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4183. */
  4184. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4185. // Near
  4186. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4187. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4188. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4189. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4190. frustumPlanes[0].normalize();
  4191. // Far
  4192. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4193. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4194. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4195. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4196. frustumPlanes[1].normalize();
  4197. // Left
  4198. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4199. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4200. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4201. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4202. frustumPlanes[2].normalize();
  4203. // Right
  4204. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4205. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4206. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4207. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4208. frustumPlanes[3].normalize();
  4209. // Top
  4210. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4211. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4212. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4213. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4214. frustumPlanes[4].normalize();
  4215. // Bottom
  4216. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4217. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4218. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4219. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4220. frustumPlanes[5].normalize();
  4221. };
  4222. return Frustum;
  4223. }());
  4224. BABYLON.Frustum = Frustum;
  4225. var Space;
  4226. (function (Space) {
  4227. Space[Space["LOCAL"] = 0] = "LOCAL";
  4228. Space[Space["WORLD"] = 1] = "WORLD";
  4229. Space[Space["BONE"] = 2] = "BONE";
  4230. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4231. var Axis = (function () {
  4232. function Axis() {
  4233. }
  4234. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4235. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4236. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4237. return Axis;
  4238. }());
  4239. BABYLON.Axis = Axis;
  4240. ;
  4241. var BezierCurve = (function () {
  4242. function BezierCurve() {
  4243. }
  4244. /**
  4245. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4246. */
  4247. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4248. // Extract X (which is equal to time here)
  4249. var f0 = 1 - 3 * x2 + 3 * x1;
  4250. var f1 = 3 * x2 - 6 * x1;
  4251. var f2 = 3 * x1;
  4252. var refinedT = t;
  4253. for (var i = 0; i < 5; i++) {
  4254. var refinedT2 = refinedT * refinedT;
  4255. var refinedT3 = refinedT2 * refinedT;
  4256. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4257. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4258. refinedT -= (x - t) * slope;
  4259. refinedT = Math.min(1, Math.max(0, refinedT));
  4260. }
  4261. // Resolve cubic bezier for the given x
  4262. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4263. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4264. Math.pow(refinedT, 3);
  4265. };
  4266. return BezierCurve;
  4267. }());
  4268. BABYLON.BezierCurve = BezierCurve;
  4269. var Orientation;
  4270. (function (Orientation) {
  4271. Orientation[Orientation["CW"] = 0] = "CW";
  4272. Orientation[Orientation["CCW"] = 1] = "CCW";
  4273. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4274. var Angle = (function () {
  4275. /**
  4276. * Creates an Angle object of "radians" radians (float).
  4277. */
  4278. function Angle(radians) {
  4279. var _this = this;
  4280. /**
  4281. * Returns the Angle value in degrees (float).
  4282. */
  4283. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4284. /**
  4285. * Returns the Angle value in radians (float).
  4286. */
  4287. this.radians = function () { return _this._radians; };
  4288. this._radians = radians;
  4289. if (this._radians < 0.0)
  4290. this._radians += (2.0 * Math.PI);
  4291. }
  4292. /**
  4293. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4294. */
  4295. Angle.BetweenTwoPoints = function (a, b) {
  4296. var delta = b.subtract(a);
  4297. var theta = Math.atan2(delta.y, delta.x);
  4298. return new Angle(theta);
  4299. };
  4300. /**
  4301. * Returns a new Angle object from the passed float in radians.
  4302. */
  4303. Angle.FromRadians = function (radians) {
  4304. return new Angle(radians);
  4305. };
  4306. /**
  4307. * Returns a new Angle object from the passed float in degrees.
  4308. */
  4309. Angle.FromDegrees = function (degrees) {
  4310. return new Angle(degrees * Math.PI / 180.0);
  4311. };
  4312. return Angle;
  4313. }());
  4314. BABYLON.Angle = Angle;
  4315. var Arc2 = (function () {
  4316. /**
  4317. * Creates an Arc object from the three passed points : start, middle and end.
  4318. */
  4319. function Arc2(startPoint, midPoint, endPoint) {
  4320. this.startPoint = startPoint;
  4321. this.midPoint = midPoint;
  4322. this.endPoint = endPoint;
  4323. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4324. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4325. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4326. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4327. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  4328. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4329. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4330. var a1 = this.startAngle.degrees();
  4331. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4332. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4333. // angles correction
  4334. if (a2 - a1 > +180.0)
  4335. a2 -= 360.0;
  4336. if (a2 - a1 < -180.0)
  4337. a2 += 360.0;
  4338. if (a3 - a2 > +180.0)
  4339. a3 -= 360.0;
  4340. if (a3 - a2 < -180.0)
  4341. a3 += 360.0;
  4342. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4343. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4344. }
  4345. return Arc2;
  4346. }());
  4347. BABYLON.Arc2 = Arc2;
  4348. var Path2 = (function () {
  4349. /**
  4350. * Creates a Path2 object from the starting 2D coordinates x and y.
  4351. */
  4352. function Path2(x, y) {
  4353. this._points = new Array();
  4354. this._length = 0.0;
  4355. this.closed = false;
  4356. this._points.push(new Vector2(x, y));
  4357. }
  4358. /**
  4359. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4360. * Returns the updated Path2.
  4361. */
  4362. Path2.prototype.addLineTo = function (x, y) {
  4363. if (closed) {
  4364. //Tools.Error("cannot add lines to closed paths");
  4365. return this;
  4366. }
  4367. var newPoint = new Vector2(x, y);
  4368. var previousPoint = this._points[this._points.length - 1];
  4369. this._points.push(newPoint);
  4370. this._length += newPoint.subtract(previousPoint).length();
  4371. return this;
  4372. };
  4373. /**
  4374. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  4375. * Returns the updated Path2.
  4376. */
  4377. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4378. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4379. if (closed) {
  4380. //Tools.Error("cannot add arcs to closed paths");
  4381. return this;
  4382. }
  4383. var startPoint = this._points[this._points.length - 1];
  4384. var midPoint = new Vector2(midX, midY);
  4385. var endPoint = new Vector2(endX, endY);
  4386. var arc = new Arc2(startPoint, midPoint, endPoint);
  4387. var increment = arc.angle.radians() / numberOfSegments;
  4388. if (arc.orientation === Orientation.CW)
  4389. increment *= -1;
  4390. var currentAngle = arc.startAngle.radians() + increment;
  4391. for (var i = 0; i < numberOfSegments; i++) {
  4392. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4393. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4394. this.addLineTo(x, y);
  4395. currentAngle += increment;
  4396. }
  4397. return this;
  4398. };
  4399. /**
  4400. * Closes the Path2.
  4401. * Returns the Path2.
  4402. */
  4403. Path2.prototype.close = function () {
  4404. this.closed = true;
  4405. return this;
  4406. };
  4407. /**
  4408. * Returns the Path2 total length (float).
  4409. */
  4410. Path2.prototype.length = function () {
  4411. var result = this._length;
  4412. if (!this.closed) {
  4413. var lastPoint = this._points[this._points.length - 1];
  4414. var firstPoint = this._points[0];
  4415. result += (firstPoint.subtract(lastPoint).length());
  4416. }
  4417. return result;
  4418. };
  4419. /**
  4420. * Returns the Path2 internal array of points.
  4421. */
  4422. Path2.prototype.getPoints = function () {
  4423. return this._points;
  4424. };
  4425. /**
  4426. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4427. */
  4428. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4429. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4430. //Tools.Error("normalized length position should be between 0 and 1.");
  4431. return Vector2.Zero();
  4432. }
  4433. var lengthPosition = normalizedLengthPosition * this.length();
  4434. var previousOffset = 0;
  4435. for (var i = 0; i < this._points.length; i++) {
  4436. var j = (i + 1) % this._points.length;
  4437. var a = this._points[i];
  4438. var b = this._points[j];
  4439. var bToA = b.subtract(a);
  4440. var nextOffset = (bToA.length() + previousOffset);
  4441. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4442. var dir = bToA.normalize();
  4443. var localOffset = lengthPosition - previousOffset;
  4444. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4445. }
  4446. previousOffset = nextOffset;
  4447. }
  4448. //Tools.Error("internal error");
  4449. return Vector2.Zero();
  4450. };
  4451. /**
  4452. * Returns a new Path2 starting at the coordinates (x, y).
  4453. */
  4454. Path2.StartingAt = function (x, y) {
  4455. return new Path2(x, y);
  4456. };
  4457. return Path2;
  4458. }());
  4459. BABYLON.Path2 = Path2;
  4460. var Path3D = (function () {
  4461. /**
  4462. * new Path3D(path, normal, raw)
  4463. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4464. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4465. * path : an array of Vector3, the curve axis of the Path3D
  4466. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4467. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4468. */
  4469. function Path3D(path, firstNormal, raw) {
  4470. this.path = path;
  4471. this._curve = new Array();
  4472. this._distances = new Array();
  4473. this._tangents = new Array();
  4474. this._normals = new Array();
  4475. this._binormals = new Array();
  4476. for (var p = 0; p < path.length; p++) {
  4477. this._curve[p] = path[p].clone(); // hard copy
  4478. }
  4479. this._raw = raw || false;
  4480. this._compute(firstNormal);
  4481. }
  4482. /**
  4483. * Returns the Path3D array of successive Vector3 designing its curve.
  4484. */
  4485. Path3D.prototype.getCurve = function () {
  4486. return this._curve;
  4487. };
  4488. /**
  4489. * Returns an array populated with tangent vectors on each Path3D curve point.
  4490. */
  4491. Path3D.prototype.getTangents = function () {
  4492. return this._tangents;
  4493. };
  4494. /**
  4495. * Returns an array populated with normal vectors on each Path3D curve point.
  4496. */
  4497. Path3D.prototype.getNormals = function () {
  4498. return this._normals;
  4499. };
  4500. /**
  4501. * Returns an array populated with binormal vectors on each Path3D curve point.
  4502. */
  4503. Path3D.prototype.getBinormals = function () {
  4504. return this._binormals;
  4505. };
  4506. /**
  4507. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4508. */
  4509. Path3D.prototype.getDistances = function () {
  4510. return this._distances;
  4511. };
  4512. /**
  4513. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4514. * Returns the same object updated.
  4515. */
  4516. Path3D.prototype.update = function (path, firstNormal) {
  4517. for (var p = 0; p < path.length; p++) {
  4518. this._curve[p].x = path[p].x;
  4519. this._curve[p].y = path[p].y;
  4520. this._curve[p].z = path[p].z;
  4521. }
  4522. this._compute(firstNormal);
  4523. return this;
  4524. };
  4525. // private function compute() : computes tangents, normals and binormals
  4526. Path3D.prototype._compute = function (firstNormal) {
  4527. var l = this._curve.length;
  4528. // first and last tangents
  4529. this._tangents[0] = this._getFirstNonNullVector(0);
  4530. if (!this._raw) {
  4531. this._tangents[0].normalize();
  4532. }
  4533. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4534. if (!this._raw) {
  4535. this._tangents[l - 1].normalize();
  4536. }
  4537. // normals and binormals at first point : arbitrary vector with _normalVector()
  4538. var tg0 = this._tangents[0];
  4539. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4540. this._normals[0] = pp0;
  4541. if (!this._raw) {
  4542. this._normals[0].normalize();
  4543. }
  4544. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4545. if (!this._raw) {
  4546. this._binormals[0].normalize();
  4547. }
  4548. this._distances[0] = 0.0;
  4549. // normals and binormals : next points
  4550. var prev; // previous vector (segment)
  4551. var cur; // current vector (segment)
  4552. var curTang; // current tangent
  4553. // previous normal
  4554. var prevBinor; // previous binormal
  4555. for (var i = 1; i < l; i++) {
  4556. // tangents
  4557. prev = this._getLastNonNullVector(i);
  4558. if (i < l - 1) {
  4559. cur = this._getFirstNonNullVector(i);
  4560. this._tangents[i] = prev.add(cur);
  4561. this._tangents[i].normalize();
  4562. }
  4563. this._distances[i] = this._distances[i - 1] + prev.length();
  4564. // normals and binormals
  4565. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4566. curTang = this._tangents[i];
  4567. prevBinor = this._binormals[i - 1];
  4568. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4569. if (!this._raw) {
  4570. this._normals[i].normalize();
  4571. }
  4572. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4573. if (!this._raw) {
  4574. this._binormals[i].normalize();
  4575. }
  4576. }
  4577. };
  4578. // private function getFirstNonNullVector(index)
  4579. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4580. Path3D.prototype._getFirstNonNullVector = function (index) {
  4581. var i = 1;
  4582. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4583. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4584. i++;
  4585. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4586. }
  4587. return nNVector;
  4588. };
  4589. // private function getLastNonNullVector(index)
  4590. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4591. Path3D.prototype._getLastNonNullVector = function (index) {
  4592. var i = 1;
  4593. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4594. while (nLVector.length() === 0 && index > i + 1) {
  4595. i++;
  4596. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4597. }
  4598. return nLVector;
  4599. };
  4600. // private function normalVector(v0, vt, va) :
  4601. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4602. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4603. Path3D.prototype._normalVector = function (v0, vt, va) {
  4604. var normal0;
  4605. var tgl = vt.length();
  4606. if (tgl === 0.0) {
  4607. tgl = 1.0;
  4608. }
  4609. if (va === undefined || va === null) {
  4610. var point;
  4611. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4612. point = new Vector3(0.0, -1.0, 0.0);
  4613. }
  4614. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4615. point = new Vector3(1.0, 0.0, 0.0);
  4616. }
  4617. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4618. point = new Vector3(0.0, 0.0, 1.0);
  4619. }
  4620. normal0 = Vector3.Cross(vt, point);
  4621. }
  4622. else {
  4623. normal0 = Vector3.Cross(vt, va);
  4624. Vector3.CrossToRef(normal0, vt, normal0);
  4625. }
  4626. normal0.normalize();
  4627. return normal0;
  4628. };
  4629. return Path3D;
  4630. }());
  4631. BABYLON.Path3D = Path3D;
  4632. var Curve3 = (function () {
  4633. /**
  4634. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4635. * A Curve3 is designed from a series of successive Vector3.
  4636. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4637. */
  4638. function Curve3(points) {
  4639. this._length = 0.0;
  4640. this._points = points;
  4641. this._length = this._computeLength(points);
  4642. }
  4643. /**
  4644. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4645. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4646. * @param v1 (Vector3) the control point
  4647. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4648. * @param nbPoints (integer) the wanted number of points in the curve
  4649. */
  4650. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4651. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4652. var bez = new Array();
  4653. var equation = function (t, val0, val1, val2) {
  4654. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4655. return res;
  4656. };
  4657. for (var i = 0; i <= nbPoints; i++) {
  4658. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  4659. }
  4660. return new Curve3(bez);
  4661. };
  4662. /**
  4663. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4664. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4665. * @param v1 (Vector3) the first control point
  4666. * @param v2 (Vector3) the second control point
  4667. * @param v3 (Vector3) the end point of the Cubic Bezier
  4668. * @param nbPoints (integer) the wanted number of points in the curve
  4669. */
  4670. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4671. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4672. var bez = new Array();
  4673. var equation = function (t, val0, val1, val2, val3) {
  4674. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  4675. return res;
  4676. };
  4677. for (var i = 0; i <= nbPoints; i++) {
  4678. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  4679. }
  4680. return new Curve3(bez);
  4681. };
  4682. /**
  4683. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4684. * @param p1 (Vector3) the origin point of the Hermite Spline
  4685. * @param t1 (Vector3) the tangent vector at the origin point
  4686. * @param p2 (Vector3) the end point of the Hermite Spline
  4687. * @param t2 (Vector3) the tangent vector at the end point
  4688. * @param nbPoints (integer) the wanted number of points in the curve
  4689. */
  4690. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4691. var hermite = new Array();
  4692. var step = 1.0 / nbPoints;
  4693. for (var i = 0; i <= nbPoints; i++) {
  4694. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4695. }
  4696. return new Curve3(hermite);
  4697. };
  4698. /**
  4699. * Returns a Curve3 object along a CatmullRom Spline curve :
  4700. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4701. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4702. */
  4703. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4704. var totalPoints = new Array();
  4705. totalPoints.push(points[0].clone());
  4706. Array.prototype.push.apply(totalPoints, points);
  4707. totalPoints.push(points[points.length - 1].clone());
  4708. var catmullRom = new Array();
  4709. var step = 1.0 / nbPoints;
  4710. for (var i = 0; i < totalPoints.length - 3; i++) {
  4711. var amount = 0.0;
  4712. for (var c = 0; c < nbPoints; c++) {
  4713. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4714. amount += step;
  4715. }
  4716. }
  4717. i--;
  4718. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4719. return new Curve3(catmullRom);
  4720. };
  4721. /**
  4722. * Returns the Curve3 stored array of successive Vector3
  4723. */
  4724. Curve3.prototype.getPoints = function () {
  4725. return this._points;
  4726. };
  4727. /**
  4728. * Returns the computed length (float) of the curve.
  4729. */
  4730. Curve3.prototype.length = function () {
  4731. return this._length;
  4732. };
  4733. /**
  4734. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4735. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4736. * curveA and curveB keep unchanged.
  4737. */
  4738. Curve3.prototype.continue = function (curve) {
  4739. var lastPoint = this._points[this._points.length - 1];
  4740. var continuedPoints = this._points.slice();
  4741. var curvePoints = curve.getPoints();
  4742. for (var i = 1; i < curvePoints.length; i++) {
  4743. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4744. }
  4745. var continuedCurve = new Curve3(continuedPoints);
  4746. return continuedCurve;
  4747. };
  4748. Curve3.prototype._computeLength = function (path) {
  4749. var l = 0;
  4750. for (var i = 1; i < path.length; i++) {
  4751. l += (path[i].subtract(path[i - 1])).length();
  4752. }
  4753. return l;
  4754. };
  4755. return Curve3;
  4756. }());
  4757. BABYLON.Curve3 = Curve3;
  4758. // Vertex formats
  4759. var PositionNormalVertex = (function () {
  4760. function PositionNormalVertex(position, normal) {
  4761. if (position === void 0) { position = Vector3.Zero(); }
  4762. if (normal === void 0) { normal = Vector3.Up(); }
  4763. this.position = position;
  4764. this.normal = normal;
  4765. }
  4766. PositionNormalVertex.prototype.clone = function () {
  4767. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4768. };
  4769. return PositionNormalVertex;
  4770. }());
  4771. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4772. var PositionNormalTextureVertex = (function () {
  4773. function PositionNormalTextureVertex(position, normal, uv) {
  4774. if (position === void 0) { position = Vector3.Zero(); }
  4775. if (normal === void 0) { normal = Vector3.Up(); }
  4776. if (uv === void 0) { uv = Vector2.Zero(); }
  4777. this.position = position;
  4778. this.normal = normal;
  4779. this.uv = uv;
  4780. }
  4781. PositionNormalTextureVertex.prototype.clone = function () {
  4782. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4783. };
  4784. return PositionNormalTextureVertex;
  4785. }());
  4786. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4787. // Temporary pre-allocated objects for engine internal use
  4788. // usage in any internal function :
  4789. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4790. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4791. var Tmp = (function () {
  4792. function Tmp() {
  4793. }
  4794. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4795. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4796. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4797. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4798. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4799. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4800. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4801. Matrix.Zero(), Matrix.Zero(),
  4802. Matrix.Zero(), Matrix.Zero(),
  4803. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4804. return Tmp;
  4805. }());
  4806. BABYLON.Tmp = Tmp;
  4807. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4808. var MathTmp = (function () {
  4809. function MathTmp() {
  4810. }
  4811. MathTmp.Vector3 = [Vector3.Zero()];
  4812. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4813. MathTmp.Quaternion = [Quaternion.Zero()];
  4814. return MathTmp;
  4815. }());
  4816. })(BABYLON || (BABYLON = {}));
  4817. //# sourceMappingURL=babylon.math.js.map
  4818. var BABYLON;
  4819. (function (BABYLON) {
  4820. var Scalar = (function () {
  4821. function Scalar() {
  4822. }
  4823. /**
  4824. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4825. */
  4826. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4827. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4828. var num = a - b;
  4829. return -epsilon <= num && num <= epsilon;
  4830. };
  4831. /**
  4832. * Returns a string : the upper case translation of the number i to hexadecimal.
  4833. */
  4834. Scalar.ToHex = function (i) {
  4835. var str = i.toString(16);
  4836. if (i <= 15) {
  4837. return ("0" + str).toUpperCase();
  4838. }
  4839. return str.toUpperCase();
  4840. };
  4841. /**
  4842. * Returns -1 if value is negative and +1 is value is positive.
  4843. * Returns the value itself if it's equal to zero.
  4844. */
  4845. Scalar.Sign = function (value) {
  4846. value = +value; // convert to a number
  4847. if (value === 0 || isNaN(value))
  4848. return value;
  4849. return value > 0 ? 1 : -1;
  4850. };
  4851. /**
  4852. * Returns the value itself if it's between min and max.
  4853. * Returns min if the value is lower than min.
  4854. * Returns max if the value is greater than max.
  4855. */
  4856. Scalar.Clamp = function (value, min, max) {
  4857. if (min === void 0) { min = 0; }
  4858. if (max === void 0) { max = 1; }
  4859. return Math.min(max, Math.max(min, value));
  4860. };
  4861. /**
  4862. * Returns the log2 of value.
  4863. */
  4864. Scalar.Log2 = function (value) {
  4865. return Math.log(value) * Math.LOG2E;
  4866. };
  4867. /**
  4868. * Loops the value, so that it is never larger than length and never smaller than 0.
  4869. *
  4870. * This is similar to the modulo operator but it works with floating point numbers.
  4871. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4872. * With t = 5 and length = 2.5, the result would be 0.0.
  4873. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4874. */
  4875. Scalar.Repeat = function (value, length) {
  4876. return value - Math.floor(value / length) * length;
  4877. };
  4878. /**
  4879. * Normalize the value between 0.0 and 1.0 using min and max values
  4880. */
  4881. Scalar.Normalize = function (value, min, max) {
  4882. return (value - min) / (max - min);
  4883. };
  4884. /**
  4885. * Denormalize the value from 0.0 and 1.0 using min and max values
  4886. */
  4887. Scalar.Denormalize = function (normalized, min, max) {
  4888. return (normalized * (max - min) + min);
  4889. };
  4890. /**
  4891. * Calculates the shortest difference between two given angles given in degrees.
  4892. */
  4893. Scalar.DeltaAngle = function (current, target) {
  4894. var num = Scalar.Repeat(target - current, 360.0);
  4895. if (num > 180.0) {
  4896. num -= 360.0;
  4897. }
  4898. return num;
  4899. };
  4900. /**
  4901. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4902. *
  4903. * The returned value will move back and forth between 0 and length
  4904. */
  4905. Scalar.PingPong = function (tx, length) {
  4906. var t = Scalar.Repeat(tx, length * 2.0);
  4907. return length - Math.abs(t - length);
  4908. };
  4909. /**
  4910. * Interpolates between min and max with smoothing at the limits.
  4911. *
  4912. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  4913. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  4914. */
  4915. Scalar.SmoothStep = function (from, to, tx) {
  4916. var t = Scalar.Clamp(tx);
  4917. t = -2.0 * t * t * t + 3.0 * t * t;
  4918. return to * t + from * (1.0 - t);
  4919. };
  4920. /**
  4921. * Moves a value current towards target.
  4922. *
  4923. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  4924. * Negative values of maxDelta pushes the value away from target.
  4925. */
  4926. Scalar.MoveTowards = function (current, target, maxDelta) {
  4927. var result = 0;
  4928. if (Math.abs(target - current) <= maxDelta) {
  4929. result = target;
  4930. }
  4931. else {
  4932. result = current + Scalar.Sign(target - current) * maxDelta;
  4933. }
  4934. return result;
  4935. };
  4936. /**
  4937. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4938. *
  4939. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  4940. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  4941. */
  4942. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  4943. var num = Scalar.DeltaAngle(current, target);
  4944. var result = 0;
  4945. if (-maxDelta < num && num < maxDelta) {
  4946. result = target;
  4947. }
  4948. else {
  4949. target = current + num;
  4950. result = Scalar.MoveTowards(current, target, maxDelta);
  4951. }
  4952. return result;
  4953. };
  4954. /**
  4955. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  4956. */
  4957. Scalar.Lerp = function (start, end, amount) {
  4958. return start + ((end - start) * amount);
  4959. };
  4960. /**
  4961. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4962. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  4963. */
  4964. Scalar.LerpAngle = function (start, end, amount) {
  4965. var num = Scalar.Repeat(end - start, 360.0);
  4966. if (num > 180.0) {
  4967. num -= 360.0;
  4968. }
  4969. return start + num * Scalar.Clamp(amount);
  4970. };
  4971. /**
  4972. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  4973. */
  4974. Scalar.InverseLerp = function (a, b, value) {
  4975. var result = 0;
  4976. if (a != b) {
  4977. result = Scalar.Clamp((value - a) / (b - a));
  4978. }
  4979. else {
  4980. result = 0.0;
  4981. }
  4982. return result;
  4983. };
  4984. /**
  4985. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  4986. */
  4987. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4988. var squared = amount * amount;
  4989. var cubed = amount * squared;
  4990. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4991. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4992. var part3 = (cubed - (2.0 * squared)) + amount;
  4993. var part4 = cubed - squared;
  4994. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  4995. };
  4996. /**
  4997. * Returns a random float number between and min and max values
  4998. */
  4999. Scalar.RandomRange = function (min, max) {
  5000. if (min === max)
  5001. return min;
  5002. return ((Math.random() * (max - min)) + min);
  5003. };
  5004. /**
  5005. * This function returns percentage of a number in a given range.
  5006. *
  5007. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5008. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5009. */
  5010. Scalar.RangeToPercent = function (number, min, max) {
  5011. return ((number - min) / (max - min));
  5012. };
  5013. /**
  5014. * This function returns number that corresponds to the percentage in a given range.
  5015. *
  5016. * PercentToRange(0.34,0,100) will return 34.
  5017. */
  5018. Scalar.PercentToRange = function (percent, min, max) {
  5019. return ((max - min) * percent + min);
  5020. };
  5021. return Scalar;
  5022. }());
  5023. BABYLON.Scalar = Scalar;
  5024. })(BABYLON || (BABYLON = {}));
  5025. //# sourceMappingURL=babylon.math.scalar.js.map
  5026. //# sourceMappingURL=babylon.mixins.js.map
  5027. var BABYLON;
  5028. (function (BABYLON) {
  5029. var __decoratorInitialStore = {};
  5030. var __mergedStore = {};
  5031. var _copySource = function (creationFunction, source, instanciate) {
  5032. var destination = creationFunction();
  5033. // Tags
  5034. if (BABYLON.Tags) {
  5035. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5036. }
  5037. var classStore = getMergedStore(destination);
  5038. // Properties
  5039. for (var property in classStore) {
  5040. var propertyDescriptor = classStore[property];
  5041. var sourceProperty = source[property];
  5042. var propertyType = propertyDescriptor.type;
  5043. if (sourceProperty !== undefined && sourceProperty !== null) {
  5044. switch (propertyType) {
  5045. case 0: // Value
  5046. case 6:// Mesh reference
  5047. destination[property] = sourceProperty;
  5048. break;
  5049. case 1: // Texture
  5050. case 2: // Color3
  5051. case 3: // FresnelParameters
  5052. case 4: // Vector2
  5053. case 5: // Vector3
  5054. case 7:// Color Curves
  5055. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5056. break;
  5057. }
  5058. }
  5059. }
  5060. return destination;
  5061. };
  5062. function getDirectStore(target) {
  5063. var classKey = target.getClassName();
  5064. if (!__decoratorInitialStore[classKey]) {
  5065. __decoratorInitialStore[classKey] = {};
  5066. }
  5067. return __decoratorInitialStore[classKey];
  5068. }
  5069. /**
  5070. * Return the list of properties flagged as serializable
  5071. * @param target: host object
  5072. */
  5073. function getMergedStore(target) {
  5074. var classKey = target.getClassName();
  5075. if (__mergedStore[classKey]) {
  5076. return __mergedStore[classKey];
  5077. }
  5078. __mergedStore[classKey] = {};
  5079. var store = __mergedStore[classKey];
  5080. var currentTarget = target;
  5081. var currentKey = classKey;
  5082. while (currentKey) {
  5083. var initialStore = __decoratorInitialStore[currentKey];
  5084. for (var property in initialStore) {
  5085. store[property] = initialStore[property];
  5086. }
  5087. var parent_1 = void 0;
  5088. var done = false;
  5089. do {
  5090. parent_1 = Object.getPrototypeOf(currentTarget);
  5091. if (!parent_1.getClassName) {
  5092. done = true;
  5093. break;
  5094. }
  5095. if (parent_1.getClassName() !== currentKey) {
  5096. break;
  5097. }
  5098. currentTarget = parent_1;
  5099. } while (parent_1);
  5100. if (done) {
  5101. break;
  5102. }
  5103. currentKey = parent_1.getClassName();
  5104. currentTarget = parent_1;
  5105. }
  5106. return store;
  5107. }
  5108. function generateSerializableMember(type, sourceName) {
  5109. return function (target, propertyKey) {
  5110. var classStore = getDirectStore(target);
  5111. if (!classStore[propertyKey]) {
  5112. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5113. }
  5114. };
  5115. }
  5116. function generateExpandMember(setCallback, targetKey) {
  5117. return function (target, propertyKey) {
  5118. var key = targetKey || ("_" + propertyKey);
  5119. Object.defineProperty(target, propertyKey, {
  5120. get: function () {
  5121. return this[key];
  5122. },
  5123. set: function (value) {
  5124. if (this[key] === value) {
  5125. return;
  5126. }
  5127. this[key] = value;
  5128. target[setCallback].apply(this);
  5129. },
  5130. enumerable: true,
  5131. configurable: true
  5132. });
  5133. };
  5134. }
  5135. function expandToProperty(callback, targetKey) {
  5136. return generateExpandMember(callback, targetKey);
  5137. }
  5138. BABYLON.expandToProperty = expandToProperty;
  5139. function serialize(sourceName) {
  5140. return generateSerializableMember(0, sourceName); // value member
  5141. }
  5142. BABYLON.serialize = serialize;
  5143. function serializeAsTexture(sourceName) {
  5144. return generateSerializableMember(1, sourceName); // texture member
  5145. }
  5146. BABYLON.serializeAsTexture = serializeAsTexture;
  5147. function serializeAsColor3(sourceName) {
  5148. return generateSerializableMember(2, sourceName); // color3 member
  5149. }
  5150. BABYLON.serializeAsColor3 = serializeAsColor3;
  5151. function serializeAsFresnelParameters(sourceName) {
  5152. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5153. }
  5154. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5155. function serializeAsVector2(sourceName) {
  5156. return generateSerializableMember(4, sourceName); // vector2 member
  5157. }
  5158. BABYLON.serializeAsVector2 = serializeAsVector2;
  5159. function serializeAsVector3(sourceName) {
  5160. return generateSerializableMember(5, sourceName); // vector3 member
  5161. }
  5162. BABYLON.serializeAsVector3 = serializeAsVector3;
  5163. function serializeAsMeshReference(sourceName) {
  5164. return generateSerializableMember(6, sourceName); // mesh reference member
  5165. }
  5166. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5167. function serializeAsColorCurves(sourceName) {
  5168. return generateSerializableMember(7, sourceName); // color curves
  5169. }
  5170. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5171. function serializeAsColor4(sourceName) {
  5172. return generateSerializableMember(8, sourceName); // color 4
  5173. }
  5174. BABYLON.serializeAsColor4 = serializeAsColor4;
  5175. function serializeAsImageProcessingConfiguration(sourceName) {
  5176. return generateSerializableMember(9, sourceName); // image processing
  5177. }
  5178. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5179. var SerializationHelper = (function () {
  5180. function SerializationHelper() {
  5181. }
  5182. SerializationHelper.Serialize = function (entity, serializationObject) {
  5183. if (!serializationObject) {
  5184. serializationObject = {};
  5185. }
  5186. // Tags
  5187. if (BABYLON.Tags) {
  5188. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5189. }
  5190. var serializedProperties = getMergedStore(entity);
  5191. // Properties
  5192. for (var property in serializedProperties) {
  5193. var propertyDescriptor = serializedProperties[property];
  5194. var targetPropertyName = propertyDescriptor.sourceName || property;
  5195. var propertyType = propertyDescriptor.type;
  5196. var sourceProperty = entity[property];
  5197. if (sourceProperty !== undefined && sourceProperty !== null) {
  5198. switch (propertyType) {
  5199. case 0:// Value
  5200. serializationObject[targetPropertyName] = sourceProperty;
  5201. break;
  5202. case 1:// Texture
  5203. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5204. break;
  5205. case 2:// Color3
  5206. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5207. break;
  5208. case 3:// FresnelParameters
  5209. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5210. break;
  5211. case 4:// Vector2
  5212. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5213. break;
  5214. case 5:// Vector3
  5215. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5216. break;
  5217. case 6:// Mesh reference
  5218. serializationObject[targetPropertyName] = sourceProperty.id;
  5219. break;
  5220. case 7:// Color Curves
  5221. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5222. break;
  5223. case 8:// Color 4
  5224. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5225. break;
  5226. case 9:// Image Processing
  5227. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5228. break;
  5229. }
  5230. }
  5231. }
  5232. return serializationObject;
  5233. };
  5234. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5235. var destination = creationFunction();
  5236. // Tags
  5237. if (BABYLON.Tags) {
  5238. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5239. }
  5240. var classStore = getMergedStore(destination);
  5241. // Properties
  5242. for (var property in classStore) {
  5243. var propertyDescriptor = classStore[property];
  5244. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5245. var propertyType = propertyDescriptor.type;
  5246. if (sourceProperty !== undefined && sourceProperty !== null) {
  5247. switch (propertyType) {
  5248. case 0:// Value
  5249. destination[property] = sourceProperty;
  5250. break;
  5251. case 1:// Texture
  5252. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5253. break;
  5254. case 2:// Color3
  5255. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  5256. break;
  5257. case 3:// FresnelParameters
  5258. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5259. break;
  5260. case 4:// Vector2
  5261. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5262. break;
  5263. case 5:// Vector3
  5264. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5265. break;
  5266. case 6:// Mesh reference
  5267. destination[property] = scene.getLastMeshByID(sourceProperty);
  5268. break;
  5269. case 7:// Color Curves
  5270. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5271. break;
  5272. case 8:// Color 4
  5273. destination[property] = BABYLON.Color4.FromArray(sourceProperty);
  5274. break;
  5275. case 9:// Image Processing
  5276. destination[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5277. break;
  5278. }
  5279. }
  5280. }
  5281. return destination;
  5282. };
  5283. SerializationHelper.Clone = function (creationFunction, source) {
  5284. return _copySource(creationFunction, source, false);
  5285. };
  5286. SerializationHelper.Instanciate = function (creationFunction, source) {
  5287. return _copySource(creationFunction, source, true);
  5288. };
  5289. return SerializationHelper;
  5290. }());
  5291. BABYLON.SerializationHelper = SerializationHelper;
  5292. })(BABYLON || (BABYLON = {}));
  5293. //# sourceMappingURL=babylon.decorators.js.map
  5294. var BABYLON;
  5295. (function (BABYLON) {
  5296. /**
  5297. * A class serves as a medium between the observable and its observers
  5298. */
  5299. var EventState = (function () {
  5300. /**
  5301. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5302. */
  5303. function EventState(mask, skipNextObservers) {
  5304. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5305. this.initalize(mask, skipNextObservers);
  5306. }
  5307. EventState.prototype.initalize = function (mask, skipNextObservers) {
  5308. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5309. this.mask = mask;
  5310. this.skipNextObservers = skipNextObservers;
  5311. return this;
  5312. };
  5313. return EventState;
  5314. }());
  5315. BABYLON.EventState = EventState;
  5316. /**
  5317. * Represent an Observer registered to a given Observable object.
  5318. */
  5319. var Observer = (function () {
  5320. function Observer(callback, mask) {
  5321. this.callback = callback;
  5322. this.mask = mask;
  5323. }
  5324. return Observer;
  5325. }());
  5326. BABYLON.Observer = Observer;
  5327. /**
  5328. * The Observable class is a simple implementation of the Observable pattern.
  5329. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  5330. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5331. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  5332. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  5333. */
  5334. var Observable = (function () {
  5335. function Observable() {
  5336. this._observers = new Array();
  5337. this._eventState = new EventState(0);
  5338. }
  5339. /**
  5340. * Create a new Observer with the specified callback
  5341. * @param callback the callback that will be executed for that Observer
  5342. * @param mask the mask used to filter observers
  5343. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  5344. */
  5345. Observable.prototype.add = function (callback, mask, insertFirst) {
  5346. if (mask === void 0) { mask = -1; }
  5347. if (insertFirst === void 0) { insertFirst = false; }
  5348. if (!callback) {
  5349. return null;
  5350. }
  5351. var observer = new Observer(callback, mask);
  5352. if (insertFirst) {
  5353. this._observers.unshift(observer);
  5354. }
  5355. else {
  5356. this._observers.push(observer);
  5357. }
  5358. return observer;
  5359. };
  5360. /**
  5361. * Remove an Observer from the Observable object
  5362. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5363. */
  5364. Observable.prototype.remove = function (observer) {
  5365. var index = this._observers.indexOf(observer);
  5366. if (index !== -1) {
  5367. this._observers.splice(index, 1);
  5368. return true;
  5369. }
  5370. return false;
  5371. };
  5372. /**
  5373. * Remove a callback from the Observable object
  5374. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5375. */
  5376. Observable.prototype.removeCallback = function (callback) {
  5377. for (var index = 0; index < this._observers.length; index++) {
  5378. if (this._observers[index].callback === callback) {
  5379. this._observers.splice(index, 1);
  5380. return true;
  5381. }
  5382. }
  5383. return false;
  5384. };
  5385. /**
  5386. * Notify all Observers by calling their respective callback with the given data
  5387. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5388. * @param eventData
  5389. * @param mask
  5390. */
  5391. Observable.prototype.notifyObservers = function (eventData, mask) {
  5392. if (mask === void 0) { mask = -1; }
  5393. var state = this._eventState;
  5394. state.mask = mask;
  5395. state.skipNextObservers = false;
  5396. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5397. var obs = _a[_i];
  5398. if (obs.mask & mask) {
  5399. obs.callback(eventData, state);
  5400. }
  5401. if (state.skipNextObservers) {
  5402. return false;
  5403. }
  5404. }
  5405. return true;
  5406. };
  5407. /**
  5408. * return true is the Observable has at least one Observer registered
  5409. */
  5410. Observable.prototype.hasObservers = function () {
  5411. return this._observers.length > 0;
  5412. };
  5413. /**
  5414. * Clear the list of observers
  5415. */
  5416. Observable.prototype.clear = function () {
  5417. this._observers = new Array();
  5418. };
  5419. /**
  5420. * Clone the current observable
  5421. */
  5422. Observable.prototype.clone = function () {
  5423. var result = new Observable();
  5424. result._observers = this._observers.slice(0);
  5425. return result;
  5426. };
  5427. /**
  5428. * Does this observable handles observer registered with a given mask
  5429. * @param {number} trigger - the mask to be tested
  5430. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5431. **/
  5432. Observable.prototype.hasSpecificMask = function (mask) {
  5433. if (mask === void 0) { mask = -1; }
  5434. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5435. var obs = _a[_i];
  5436. if (obs.mask & mask || obs.mask === mask) {
  5437. return true;
  5438. }
  5439. }
  5440. return false;
  5441. };
  5442. return Observable;
  5443. }());
  5444. BABYLON.Observable = Observable;
  5445. })(BABYLON || (BABYLON = {}));
  5446. //# sourceMappingURL=babylon.observable.js.map
  5447. var BABYLON;
  5448. (function (BABYLON) {
  5449. var SmartArray = (function () {
  5450. function SmartArray(capacity) {
  5451. this.length = 0;
  5452. this._duplicateId = 0;
  5453. this.data = new Array(capacity);
  5454. this._id = SmartArray._GlobalId++;
  5455. }
  5456. SmartArray.prototype.push = function (value) {
  5457. this.data[this.length++] = value;
  5458. if (this.length > this.data.length) {
  5459. this.data.length *= 2;
  5460. }
  5461. if (!value.__smartArrayFlags) {
  5462. value.__smartArrayFlags = {};
  5463. }
  5464. value.__smartArrayFlags[this._id] = this._duplicateId;
  5465. };
  5466. SmartArray.prototype.forEach = function (func) {
  5467. for (var index = 0; index < this.length; index++) {
  5468. func(this.data[index]);
  5469. }
  5470. };
  5471. SmartArray.prototype.pushNoDuplicate = function (value) {
  5472. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5473. return false;
  5474. }
  5475. this.push(value);
  5476. return true;
  5477. };
  5478. SmartArray.prototype.sort = function (compareFn) {
  5479. this.data.sort(compareFn);
  5480. };
  5481. SmartArray.prototype.reset = function () {
  5482. this.length = 0;
  5483. this._duplicateId++;
  5484. };
  5485. SmartArray.prototype.dispose = function () {
  5486. this.reset();
  5487. if (this.data) {
  5488. this.data.length = 0;
  5489. this.data = null;
  5490. }
  5491. };
  5492. SmartArray.prototype.concat = function (array) {
  5493. if (array.length === 0) {
  5494. return;
  5495. }
  5496. if (this.length + array.length > this.data.length) {
  5497. this.data.length = (this.length + array.length) * 2;
  5498. }
  5499. for (var index = 0; index < array.length; index++) {
  5500. this.data[this.length++] = (array.data || array)[index];
  5501. }
  5502. };
  5503. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5504. if (array.length === 0) {
  5505. return;
  5506. }
  5507. if (this.length + array.length > this.data.length) {
  5508. this.data.length = (this.length + array.length) * 2;
  5509. }
  5510. for (var index = 0; index < array.length; index++) {
  5511. var item = (array.data || array)[index];
  5512. this.pushNoDuplicate(item);
  5513. }
  5514. };
  5515. SmartArray.prototype.indexOf = function (value) {
  5516. var position = this.data.indexOf(value);
  5517. if (position >= this.length) {
  5518. return -1;
  5519. }
  5520. return position;
  5521. };
  5522. SmartArray.prototype.contains = function (value) {
  5523. return this.data.indexOf(value) !== -1;
  5524. };
  5525. // Statics
  5526. SmartArray._GlobalId = 0;
  5527. return SmartArray;
  5528. }());
  5529. BABYLON.SmartArray = SmartArray;
  5530. })(BABYLON || (BABYLON = {}));
  5531. //# sourceMappingURL=babylon.smartArray.js.map
  5532. var BABYLON;
  5533. (function (BABYLON) {
  5534. // Screenshots
  5535. var screenshotCanvas;
  5536. var cloneValue = function (source, destinationObject) {
  5537. if (!source)
  5538. return null;
  5539. if (source instanceof BABYLON.Mesh) {
  5540. return null;
  5541. }
  5542. if (source instanceof BABYLON.SubMesh) {
  5543. return source.clone(destinationObject);
  5544. }
  5545. else if (source.clone) {
  5546. return source.clone();
  5547. }
  5548. return null;
  5549. };
  5550. var Tools = (function () {
  5551. function Tools() {
  5552. }
  5553. ;
  5554. /**
  5555. * Interpolates between a and b via alpha
  5556. * @param a The lower value (returned when alpha = 0)
  5557. * @param b The upper value (returned when alpha = 1)
  5558. * @param alpha The interpolation-factor
  5559. * @return The mixed value
  5560. */
  5561. Tools.Mix = function (a, b, alpha) {
  5562. return a * (1 - alpha) + b * alpha;
  5563. };
  5564. Tools.Instantiate = function (className) {
  5565. var arr = className.split(".");
  5566. var fn = (window || this);
  5567. for (var i = 0, len = arr.length; i < len; i++) {
  5568. fn = fn[arr[i]];
  5569. }
  5570. if (typeof fn !== "function") {
  5571. return null;
  5572. }
  5573. return fn;
  5574. };
  5575. Tools.SetImmediate = function (action) {
  5576. if (window.setImmediate) {
  5577. window.setImmediate(action);
  5578. }
  5579. else {
  5580. setTimeout(action, 1);
  5581. }
  5582. };
  5583. Tools.IsExponentOfTwo = function (value) {
  5584. var count = 1;
  5585. do {
  5586. count *= 2;
  5587. } while (count < value);
  5588. return count === value;
  5589. };
  5590. /**
  5591. * Find the next highest power of two.
  5592. * @param x Number to start search from.
  5593. * @return Next highest power of two.
  5594. */
  5595. Tools.CeilingPOT = function (x) {
  5596. x--;
  5597. x |= x >> 1;
  5598. x |= x >> 2;
  5599. x |= x >> 4;
  5600. x |= x >> 8;
  5601. x |= x >> 16;
  5602. x++;
  5603. return x;
  5604. };
  5605. /**
  5606. * Find the next lowest power of two.
  5607. * @param x Number to start search from.
  5608. * @return Next lowest power of two.
  5609. */
  5610. Tools.FloorPOT = function (x) {
  5611. x = x | (x >> 1);
  5612. x = x | (x >> 2);
  5613. x = x | (x >> 4);
  5614. x = x | (x >> 8);
  5615. x = x | (x >> 16);
  5616. return x - (x >> 1);
  5617. };
  5618. /**
  5619. * Find the nearest power of two.
  5620. * @param x Number to start search from.
  5621. * @return Next nearest power of two.
  5622. */
  5623. Tools.NearestPOT = function (x) {
  5624. var c = Tools.CeilingPOT(x);
  5625. var f = Tools.FloorPOT(x);
  5626. return (c - x) > (x - f) ? f : c;
  5627. };
  5628. Tools.GetExponentOfTwo = function (value, max, mode) {
  5629. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5630. var pot;
  5631. switch (mode) {
  5632. case BABYLON.Engine.SCALEMODE_FLOOR:
  5633. pot = Tools.FloorPOT(value);
  5634. break;
  5635. case BABYLON.Engine.SCALEMODE_NEAREST:
  5636. pot = Tools.NearestPOT(value);
  5637. break;
  5638. case BABYLON.Engine.SCALEMODE_CEILING:
  5639. pot = Tools.CeilingPOT(value);
  5640. break;
  5641. }
  5642. return Math.min(pot, max);
  5643. };
  5644. Tools.GetFilename = function (path) {
  5645. var index = path.lastIndexOf("/");
  5646. if (index < 0)
  5647. return path;
  5648. return path.substring(index + 1);
  5649. };
  5650. Tools.GetDOMTextContent = function (element) {
  5651. var result = "";
  5652. var child = element.firstChild;
  5653. while (child) {
  5654. if (child.nodeType === 3) {
  5655. result += child.textContent;
  5656. }
  5657. child = child.nextSibling;
  5658. }
  5659. return result;
  5660. };
  5661. Tools.ToDegrees = function (angle) {
  5662. return angle * 180 / Math.PI;
  5663. };
  5664. Tools.ToRadians = function (angle) {
  5665. return angle * Math.PI / 180;
  5666. };
  5667. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5668. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5669. var output = "";
  5670. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5671. var i = 0;
  5672. var bytes = new Uint8Array(buffer);
  5673. while (i < bytes.length) {
  5674. chr1 = bytes[i++];
  5675. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5676. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5677. enc1 = chr1 >> 2;
  5678. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5679. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5680. enc4 = chr3 & 63;
  5681. if (isNaN(chr2)) {
  5682. enc3 = enc4 = 64;
  5683. }
  5684. else if (isNaN(chr3)) {
  5685. enc4 = 64;
  5686. }
  5687. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5688. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5689. }
  5690. return "data:image/png;base64," + output;
  5691. };
  5692. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5693. if (bias === void 0) { bias = null; }
  5694. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5695. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5696. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5697. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5698. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5699. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5700. }
  5701. if (bias) {
  5702. minimum.x -= minimum.x * bias.x + bias.y;
  5703. minimum.y -= minimum.y * bias.x + bias.y;
  5704. minimum.z -= minimum.z * bias.x + bias.y;
  5705. maximum.x += maximum.x * bias.x + bias.y;
  5706. maximum.y += maximum.y * bias.x + bias.y;
  5707. maximum.z += maximum.z * bias.x + bias.y;
  5708. }
  5709. return {
  5710. minimum: minimum,
  5711. maximum: maximum
  5712. };
  5713. };
  5714. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5715. if (bias === void 0) { bias = null; }
  5716. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5717. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5718. if (!stride) {
  5719. stride = 3;
  5720. }
  5721. for (var index = start; index < start + count; index++) {
  5722. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5723. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5724. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5725. }
  5726. if (bias) {
  5727. minimum.x -= minimum.x * bias.x + bias.y;
  5728. minimum.y -= minimum.y * bias.x + bias.y;
  5729. minimum.z -= minimum.z * bias.x + bias.y;
  5730. maximum.x += maximum.x * bias.x + bias.y;
  5731. maximum.y += maximum.y * bias.x + bias.y;
  5732. maximum.z += maximum.z * bias.x + bias.y;
  5733. }
  5734. return {
  5735. minimum: minimum,
  5736. maximum: maximum
  5737. };
  5738. };
  5739. Tools.Vector2ArrayFeeder = function (array) {
  5740. return function (index) {
  5741. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5742. var length = isFloatArray ? array.length / 2 : array.length;
  5743. if (index >= length) {
  5744. return null;
  5745. }
  5746. if (isFloatArray) {
  5747. var fa = array;
  5748. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5749. }
  5750. var a = array;
  5751. return a[index];
  5752. };
  5753. };
  5754. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5755. if (bias === void 0) { bias = null; }
  5756. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5757. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5758. var i = 0;
  5759. var cur = feeder(i++);
  5760. while (cur) {
  5761. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5762. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5763. cur = feeder(i++);
  5764. }
  5765. if (bias) {
  5766. minimum.x -= minimum.x * bias.x + bias.y;
  5767. minimum.y -= minimum.y * bias.x + bias.y;
  5768. maximum.x += maximum.x * bias.x + bias.y;
  5769. maximum.y += maximum.y * bias.x + bias.y;
  5770. }
  5771. return {
  5772. minimum: minimum,
  5773. maximum: maximum
  5774. };
  5775. };
  5776. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5777. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5778. return undefined;
  5779. return Array.isArray(obj) ? obj : [obj];
  5780. };
  5781. // Misc.
  5782. Tools.GetPointerPrefix = function () {
  5783. var eventPrefix = "pointer";
  5784. // Check if pointer events are supported
  5785. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5786. eventPrefix = "mouse";
  5787. }
  5788. return eventPrefix;
  5789. };
  5790. /**
  5791. * @param func - the function to be called
  5792. * @param requester - the object that will request the next frame. Falls back to window.
  5793. */
  5794. Tools.QueueNewFrame = function (func, requester) {
  5795. if (requester === void 0) { requester = window; }
  5796. if (requester.requestAnimationFrame) {
  5797. return requester.requestAnimationFrame(func);
  5798. }
  5799. else if (requester.msRequestAnimationFrame) {
  5800. return requester.msRequestAnimationFrame(func);
  5801. }
  5802. else if (requester.webkitRequestAnimationFrame) {
  5803. return requester.webkitRequestAnimationFrame(func);
  5804. }
  5805. else if (requester.mozRequestAnimationFrame) {
  5806. return requester.mozRequestAnimationFrame(func);
  5807. }
  5808. else if (requester.oRequestAnimationFrame) {
  5809. return requester.oRequestAnimationFrame(func);
  5810. }
  5811. else {
  5812. return window.setTimeout(func, 16);
  5813. }
  5814. };
  5815. Tools.RequestFullscreen = function (element) {
  5816. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5817. if (!requestFunction)
  5818. return;
  5819. requestFunction.call(element);
  5820. };
  5821. Tools.ExitFullscreen = function () {
  5822. if (document.exitFullscreen) {
  5823. document.exitFullscreen();
  5824. }
  5825. else if (document.mozCancelFullScreen) {
  5826. document.mozCancelFullScreen();
  5827. }
  5828. else if (document.webkitCancelFullScreen) {
  5829. document.webkitCancelFullScreen();
  5830. }
  5831. else if (document.msCancelFullScreen) {
  5832. document.msCancelFullScreen();
  5833. }
  5834. };
  5835. Tools.SetCorsBehavior = function (url, img) {
  5836. if (Tools.CorsBehavior) {
  5837. switch (typeof (Tools.CorsBehavior)) {
  5838. case "function":
  5839. var result = Tools.CorsBehavior(url);
  5840. if (result) {
  5841. img.crossOrigin = result;
  5842. }
  5843. break;
  5844. case "string":
  5845. default:
  5846. img.crossOrigin = Tools.CorsBehavior;
  5847. break;
  5848. }
  5849. }
  5850. };
  5851. // External files
  5852. Tools.CleanUrl = function (url) {
  5853. url = url.replace(/#/mg, "%23");
  5854. return url;
  5855. };
  5856. Tools.LoadImage = function (url, onload, onerror, database) {
  5857. if (url instanceof ArrayBuffer) {
  5858. url = Tools.EncodeArrayBufferTobase64(url);
  5859. }
  5860. url = Tools.CleanUrl(url);
  5861. url = Tools.PreprocessUrl(url);
  5862. var img = new Image();
  5863. if (url.substr(0, 5) !== "data:") {
  5864. Tools.SetCorsBehavior(url, img);
  5865. }
  5866. img.onload = function () {
  5867. onload(img);
  5868. };
  5869. img.onerror = function (err) {
  5870. Tools.Error("Error while trying to load image: " + url);
  5871. if (Tools.UseFallbackTexture) {
  5872. img.src = Tools.fallbackTexture;
  5873. onload(img);
  5874. }
  5875. else {
  5876. onerror();
  5877. }
  5878. };
  5879. var noIndexedDB = function () {
  5880. img.src = url;
  5881. };
  5882. var loadFromIndexedDB = function () {
  5883. database.loadImageFromDB(url, img);
  5884. };
  5885. //ANY database to do!
  5886. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5887. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5888. }
  5889. else {
  5890. if (url.indexOf("file:") !== 0) {
  5891. noIndexedDB();
  5892. }
  5893. else {
  5894. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  5895. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5896. try {
  5897. var blobURL;
  5898. try {
  5899. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5900. }
  5901. catch (ex) {
  5902. // Chrome doesn't support oneTimeOnly parameter
  5903. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5904. }
  5905. img.src = blobURL;
  5906. }
  5907. catch (e) {
  5908. img.src = null;
  5909. }
  5910. }
  5911. else {
  5912. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5913. img.src = Tools.fallbackTexture;
  5914. }
  5915. }
  5916. }
  5917. return img;
  5918. };
  5919. //ANY
  5920. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5921. url = Tools.CleanUrl(url);
  5922. url = Tools.PreprocessUrl(url);
  5923. var noIndexedDB = function () {
  5924. var request = new XMLHttpRequest();
  5925. var loadUrl = Tools.BaseUrl + url;
  5926. request.open('GET', loadUrl, true);
  5927. if (useArrayBuffer) {
  5928. request.responseType = "arraybuffer";
  5929. }
  5930. request.onprogress = progressCallBack;
  5931. request.onreadystatechange = function () {
  5932. // In case of undefined state in some browsers.
  5933. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5934. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5935. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5936. callback(!useArrayBuffer ? request.responseText : request.response);
  5937. }
  5938. else {
  5939. if (onError) {
  5940. onError(request);
  5941. }
  5942. else {
  5943. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5944. }
  5945. }
  5946. }
  5947. };
  5948. request.send(null);
  5949. };
  5950. var loadFromIndexedDB = function () {
  5951. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5952. };
  5953. if (url.indexOf("file:") !== -1) {
  5954. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  5955. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5956. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5957. }
  5958. else {
  5959. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5960. }
  5961. }
  5962. else {
  5963. // Caching all files
  5964. if (database && database.enableSceneOffline) {
  5965. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5966. }
  5967. else {
  5968. noIndexedDB();
  5969. }
  5970. }
  5971. };
  5972. /**
  5973. * Load a script (identified by an url). When the url returns, the
  5974. * content of this file is added into a new script element, attached to the DOM (body element)
  5975. */
  5976. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5977. var head = document.getElementsByTagName('head')[0];
  5978. var script = document.createElement('script');
  5979. script.type = 'text/javascript';
  5980. script.src = scriptUrl;
  5981. var self = this;
  5982. script.onload = function () {
  5983. if (onSuccess) {
  5984. onSuccess();
  5985. }
  5986. };
  5987. script.onerror = function () {
  5988. if (onError) {
  5989. onError();
  5990. }
  5991. };
  5992. head.appendChild(script);
  5993. };
  5994. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5995. var reader = new FileReader();
  5996. reader.onload = function (e) {
  5997. //target doesn't have result from ts 1.3
  5998. callback(e.target['result']);
  5999. };
  6000. reader.onprogress = progressCallback;
  6001. reader.readAsDataURL(fileToLoad);
  6002. };
  6003. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6004. var reader = new FileReader();
  6005. reader.onerror = function (e) {
  6006. Tools.Log("Error while reading file: " + fileToLoad.name);
  6007. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6008. };
  6009. reader.onload = function (e) {
  6010. //target doesn't have result from ts 1.3
  6011. callback(e.target['result']);
  6012. };
  6013. reader.onprogress = progressCallBack;
  6014. if (!useArrayBuffer) {
  6015. // Asynchronous read
  6016. reader.readAsText(fileToLoad);
  6017. }
  6018. else {
  6019. reader.readAsArrayBuffer(fileToLoad);
  6020. }
  6021. };
  6022. //returns a downloadable url to a file content.
  6023. Tools.FileAsURL = function (content) {
  6024. var fileBlob = new Blob([content]);
  6025. var url = window.URL || window.webkitURL;
  6026. var link = url.createObjectURL(fileBlob);
  6027. return link;
  6028. };
  6029. // Misc.
  6030. Tools.Format = function (value, decimals) {
  6031. if (decimals === void 0) { decimals = 2; }
  6032. return value.toFixed(decimals);
  6033. };
  6034. Tools.CheckExtends = function (v, min, max) {
  6035. if (v.x < min.x)
  6036. min.x = v.x;
  6037. if (v.y < min.y)
  6038. min.y = v.y;
  6039. if (v.z < min.z)
  6040. min.z = v.z;
  6041. if (v.x > max.x)
  6042. max.x = v.x;
  6043. if (v.y > max.y)
  6044. max.y = v.y;
  6045. if (v.z > max.z)
  6046. max.z = v.z;
  6047. };
  6048. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6049. for (var prop in source) {
  6050. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6051. continue;
  6052. }
  6053. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6054. continue;
  6055. }
  6056. var sourceValue = source[prop];
  6057. var typeOfSourceValue = typeof sourceValue;
  6058. if (typeOfSourceValue === "function") {
  6059. continue;
  6060. }
  6061. if (typeOfSourceValue === "object") {
  6062. if (sourceValue instanceof Array) {
  6063. destination[prop] = [];
  6064. if (sourceValue.length > 0) {
  6065. if (typeof sourceValue[0] == "object") {
  6066. for (var index = 0; index < sourceValue.length; index++) {
  6067. var clonedValue = cloneValue(sourceValue[index], destination);
  6068. if (destination[prop].indexOf(clonedValue) === -1) {
  6069. destination[prop].push(clonedValue);
  6070. }
  6071. }
  6072. }
  6073. else {
  6074. destination[prop] = sourceValue.slice(0);
  6075. }
  6076. }
  6077. }
  6078. else {
  6079. destination[prop] = cloneValue(sourceValue, destination);
  6080. }
  6081. }
  6082. else {
  6083. destination[prop] = sourceValue;
  6084. }
  6085. }
  6086. };
  6087. Tools.IsEmpty = function (obj) {
  6088. for (var i in obj) {
  6089. return false;
  6090. }
  6091. return true;
  6092. };
  6093. Tools.RegisterTopRootEvents = function (events) {
  6094. for (var index = 0; index < events.length; index++) {
  6095. var event = events[index];
  6096. window.addEventListener(event.name, event.handler, false);
  6097. try {
  6098. if (window.parent) {
  6099. window.parent.addEventListener(event.name, event.handler, false);
  6100. }
  6101. }
  6102. catch (e) {
  6103. // Silently fails...
  6104. }
  6105. }
  6106. };
  6107. Tools.UnregisterTopRootEvents = function (events) {
  6108. for (var index = 0; index < events.length; index++) {
  6109. var event = events[index];
  6110. window.removeEventListener(event.name, event.handler);
  6111. try {
  6112. if (window.parent) {
  6113. window.parent.removeEventListener(event.name, event.handler);
  6114. }
  6115. }
  6116. catch (e) {
  6117. // Silently fails...
  6118. }
  6119. }
  6120. };
  6121. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6122. if (mimeType === void 0) { mimeType = "image/png"; }
  6123. // Read the contents of the framebuffer
  6124. var numberOfChannelsByLine = width * 4;
  6125. var halfHeight = height / 2;
  6126. //Reading datas from WebGL
  6127. var data = engine.readPixels(0, 0, width, height);
  6128. //To flip image on Y axis.
  6129. for (var i = 0; i < halfHeight; i++) {
  6130. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6131. var currentCell = j + i * numberOfChannelsByLine;
  6132. var targetLine = height - i - 1;
  6133. var targetCell = j + targetLine * numberOfChannelsByLine;
  6134. var temp = data[currentCell];
  6135. data[currentCell] = data[targetCell];
  6136. data[targetCell] = temp;
  6137. }
  6138. }
  6139. // Create a 2D canvas to store the result
  6140. if (!screenshotCanvas) {
  6141. screenshotCanvas = document.createElement('canvas');
  6142. }
  6143. screenshotCanvas.width = width;
  6144. screenshotCanvas.height = height;
  6145. var context = screenshotCanvas.getContext('2d');
  6146. // Copy the pixels to a 2D canvas
  6147. var imageData = context.createImageData(width, height);
  6148. var castData = (imageData.data);
  6149. castData.set(data);
  6150. context.putImageData(imageData, 0, 0);
  6151. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6152. };
  6153. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6154. if (mimeType === void 0) { mimeType = "image/png"; }
  6155. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6156. if (successCallback) {
  6157. successCallback(base64Image);
  6158. }
  6159. else {
  6160. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6161. if (("download" in document.createElement("a"))) {
  6162. var a = window.document.createElement("a");
  6163. a.href = base64Image;
  6164. var date = new Date();
  6165. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6166. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6167. window.document.body.appendChild(a);
  6168. a.addEventListener("click", function () {
  6169. a.parentElement.removeChild(a);
  6170. });
  6171. a.click();
  6172. //Or opening a new tab with the image if it is not possible to automatically start download.
  6173. }
  6174. else {
  6175. var newWindow = window.open("");
  6176. var img = newWindow.document.createElement("img");
  6177. img.src = base64Image;
  6178. newWindow.document.body.appendChild(img);
  6179. }
  6180. }
  6181. };
  6182. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6183. if (mimeType === void 0) { mimeType = "image/png"; }
  6184. var width;
  6185. var height;
  6186. // If a precision value is specified
  6187. if (size.precision) {
  6188. width = Math.round(engine.getRenderWidth() * size.precision);
  6189. height = Math.round(width / engine.getAspectRatio(camera));
  6190. }
  6191. else if (size.width && size.height) {
  6192. width = size.width;
  6193. height = size.height;
  6194. }
  6195. else if (size.width && !size.height) {
  6196. width = size.width;
  6197. height = Math.round(width / engine.getAspectRatio(camera));
  6198. }
  6199. else if (size.height && !size.width) {
  6200. height = size.height;
  6201. width = Math.round(height * engine.getAspectRatio(camera));
  6202. }
  6203. else if (!isNaN(size)) {
  6204. height = size;
  6205. width = size;
  6206. }
  6207. else {
  6208. Tools.Error("Invalid 'size' parameter !");
  6209. return;
  6210. }
  6211. if (!screenshotCanvas) {
  6212. screenshotCanvas = document.createElement('canvas');
  6213. }
  6214. screenshotCanvas.width = width;
  6215. screenshotCanvas.height = height;
  6216. var renderContext = screenshotCanvas.getContext("2d");
  6217. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6218. var newWidth = width;
  6219. var newHeight = newWidth / ratio;
  6220. if (newHeight > height) {
  6221. newHeight = height;
  6222. newWidth = newHeight * ratio;
  6223. }
  6224. var offsetX = Math.max(0, width - newWidth) / 2;
  6225. var offsetY = Math.max(0, height - newHeight) / 2;
  6226. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6227. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6228. };
  6229. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6230. if (mimeType === void 0) { mimeType = "image/png"; }
  6231. if (samples === void 0) { samples = 1; }
  6232. var width;
  6233. var height;
  6234. //If a precision value is specified
  6235. if (size.precision) {
  6236. width = Math.round(engine.getRenderWidth() * size.precision);
  6237. height = Math.round(width / engine.getAspectRatio(camera));
  6238. size = { width: width, height: height };
  6239. }
  6240. else if (size.width && size.height) {
  6241. width = size.width;
  6242. height = size.height;
  6243. }
  6244. else if (size.width && !size.height) {
  6245. width = size.width;
  6246. height = Math.round(width / engine.getAspectRatio(camera));
  6247. size = { width: width, height: height };
  6248. }
  6249. else if (size.height && !size.width) {
  6250. height = size.height;
  6251. width = Math.round(height * engine.getAspectRatio(camera));
  6252. size = { width: width, height: height };
  6253. }
  6254. else if (!isNaN(size)) {
  6255. height = size;
  6256. width = size;
  6257. }
  6258. else {
  6259. Tools.Error("Invalid 'size' parameter !");
  6260. return;
  6261. }
  6262. var scene = camera.getScene();
  6263. var previousCamera = null;
  6264. if (scene.activeCamera !== camera) {
  6265. previousCamera = scene.activeCamera;
  6266. scene.activeCamera = camera;
  6267. }
  6268. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6269. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6270. texture.renderList = null;
  6271. texture.samples = samples;
  6272. texture.onAfterRenderObservable.add(function () {
  6273. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6274. });
  6275. scene.incrementRenderId();
  6276. scene.resetCachedMaterial();
  6277. texture.render(true);
  6278. texture.dispose();
  6279. if (previousCamera) {
  6280. scene.activeCamera = previousCamera;
  6281. }
  6282. camera.getProjectionMatrix(true); // Force cache refresh;
  6283. };
  6284. // XHR response validator for local file scenario
  6285. Tools.ValidateXHRData = function (xhr, dataType) {
  6286. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6287. if (dataType === void 0) { dataType = 7; }
  6288. try {
  6289. if (dataType & 1) {
  6290. if (xhr.responseText && xhr.responseText.length > 0) {
  6291. return true;
  6292. }
  6293. else if (dataType === 1) {
  6294. return false;
  6295. }
  6296. }
  6297. if (dataType & 2) {
  6298. // Check header width and height since there is no "TGA" magic number
  6299. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6300. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6301. return true;
  6302. }
  6303. else if (dataType === 2) {
  6304. return false;
  6305. }
  6306. }
  6307. if (dataType & 4) {
  6308. // Check for the "DDS" magic number
  6309. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6310. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6311. return true;
  6312. }
  6313. else {
  6314. return false;
  6315. }
  6316. }
  6317. }
  6318. catch (e) {
  6319. // Global protection
  6320. }
  6321. return false;
  6322. };
  6323. /**
  6324. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6325. * Be aware Math.random() could cause collisions, but:
  6326. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  6327. */
  6328. Tools.RandomId = function () {
  6329. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6330. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6331. return v.toString(16);
  6332. });
  6333. };
  6334. Object.defineProperty(Tools, "NoneLogLevel", {
  6335. get: function () {
  6336. return Tools._NoneLogLevel;
  6337. },
  6338. enumerable: true,
  6339. configurable: true
  6340. });
  6341. Object.defineProperty(Tools, "MessageLogLevel", {
  6342. get: function () {
  6343. return Tools._MessageLogLevel;
  6344. },
  6345. enumerable: true,
  6346. configurable: true
  6347. });
  6348. Object.defineProperty(Tools, "WarningLogLevel", {
  6349. get: function () {
  6350. return Tools._WarningLogLevel;
  6351. },
  6352. enumerable: true,
  6353. configurable: true
  6354. });
  6355. Object.defineProperty(Tools, "ErrorLogLevel", {
  6356. get: function () {
  6357. return Tools._ErrorLogLevel;
  6358. },
  6359. enumerable: true,
  6360. configurable: true
  6361. });
  6362. Object.defineProperty(Tools, "AllLogLevel", {
  6363. get: function () {
  6364. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6365. },
  6366. enumerable: true,
  6367. configurable: true
  6368. });
  6369. Tools._AddLogEntry = function (entry) {
  6370. Tools._LogCache = entry + Tools._LogCache;
  6371. if (Tools.OnNewCacheEntry) {
  6372. Tools.OnNewCacheEntry(entry);
  6373. }
  6374. };
  6375. Tools._FormatMessage = function (message) {
  6376. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6377. var date = new Date();
  6378. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6379. };
  6380. Tools._LogDisabled = function (message) {
  6381. // nothing to do
  6382. };
  6383. Tools._LogEnabled = function (message) {
  6384. var formattedMessage = Tools._FormatMessage(message);
  6385. console.log("BJS - " + formattedMessage);
  6386. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6387. Tools._AddLogEntry(entry);
  6388. };
  6389. Tools._WarnDisabled = function (message) {
  6390. // nothing to do
  6391. };
  6392. Tools._WarnEnabled = function (message) {
  6393. var formattedMessage = Tools._FormatMessage(message);
  6394. console.warn("BJS - " + formattedMessage);
  6395. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6396. Tools._AddLogEntry(entry);
  6397. };
  6398. Tools._ErrorDisabled = function (message) {
  6399. // nothing to do
  6400. };
  6401. Tools._ErrorEnabled = function (message) {
  6402. Tools.errorsCount++;
  6403. var formattedMessage = Tools._FormatMessage(message);
  6404. console.error("BJS - " + formattedMessage);
  6405. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6406. Tools._AddLogEntry(entry);
  6407. };
  6408. Object.defineProperty(Tools, "LogCache", {
  6409. get: function () {
  6410. return Tools._LogCache;
  6411. },
  6412. enumerable: true,
  6413. configurable: true
  6414. });
  6415. Tools.ClearLogCache = function () {
  6416. Tools._LogCache = "";
  6417. Tools.errorsCount = 0;
  6418. };
  6419. Object.defineProperty(Tools, "LogLevels", {
  6420. set: function (level) {
  6421. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6422. Tools.Log = Tools._LogEnabled;
  6423. }
  6424. else {
  6425. Tools.Log = Tools._LogDisabled;
  6426. }
  6427. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6428. Tools.Warn = Tools._WarnEnabled;
  6429. }
  6430. else {
  6431. Tools.Warn = Tools._WarnDisabled;
  6432. }
  6433. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6434. Tools.Error = Tools._ErrorEnabled;
  6435. }
  6436. else {
  6437. Tools.Error = Tools._ErrorDisabled;
  6438. }
  6439. },
  6440. enumerable: true,
  6441. configurable: true
  6442. });
  6443. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6444. get: function () {
  6445. return Tools._PerformanceNoneLogLevel;
  6446. },
  6447. enumerable: true,
  6448. configurable: true
  6449. });
  6450. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6451. get: function () {
  6452. return Tools._PerformanceUserMarkLogLevel;
  6453. },
  6454. enumerable: true,
  6455. configurable: true
  6456. });
  6457. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6458. get: function () {
  6459. return Tools._PerformanceConsoleLogLevel;
  6460. },
  6461. enumerable: true,
  6462. configurable: true
  6463. });
  6464. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6465. set: function (level) {
  6466. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6467. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6468. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6469. return;
  6470. }
  6471. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6472. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6473. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6474. return;
  6475. }
  6476. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6477. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6478. },
  6479. enumerable: true,
  6480. configurable: true
  6481. });
  6482. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6483. };
  6484. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6485. };
  6486. Tools._StartUserMark = function (counterName, condition) {
  6487. if (condition === void 0) { condition = true; }
  6488. if (!condition || !Tools._performance.mark) {
  6489. return;
  6490. }
  6491. Tools._performance.mark(counterName + "-Begin");
  6492. };
  6493. Tools._EndUserMark = function (counterName, condition) {
  6494. if (condition === void 0) { condition = true; }
  6495. if (!condition || !Tools._performance.mark) {
  6496. return;
  6497. }
  6498. Tools._performance.mark(counterName + "-End");
  6499. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6500. };
  6501. Tools._StartPerformanceConsole = function (counterName, condition) {
  6502. if (condition === void 0) { condition = true; }
  6503. if (!condition) {
  6504. return;
  6505. }
  6506. Tools._StartUserMark(counterName, condition);
  6507. if (console.time) {
  6508. console.time(counterName);
  6509. }
  6510. };
  6511. Tools._EndPerformanceConsole = function (counterName, condition) {
  6512. if (condition === void 0) { condition = true; }
  6513. if (!condition) {
  6514. return;
  6515. }
  6516. Tools._EndUserMark(counterName, condition);
  6517. if (console.time) {
  6518. console.timeEnd(counterName);
  6519. }
  6520. };
  6521. Object.defineProperty(Tools, "Now", {
  6522. get: function () {
  6523. if (window.performance && window.performance.now) {
  6524. return window.performance.now();
  6525. }
  6526. return new Date().getTime();
  6527. },
  6528. enumerable: true,
  6529. configurable: true
  6530. });
  6531. /**
  6532. * This method will return the name of the class used to create the instance of the given object.
  6533. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6534. * @param object the object to get the class name from
  6535. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6536. */
  6537. Tools.GetClassName = function (object, isType) {
  6538. if (isType === void 0) { isType = false; }
  6539. var name = null;
  6540. if (!isType && object.getClassName) {
  6541. name = object.getClassName();
  6542. }
  6543. else {
  6544. if (object instanceof Object) {
  6545. var classObj = isType ? object : Object.getPrototypeOf(object);
  6546. name = classObj.constructor["__bjsclassName__"];
  6547. }
  6548. if (!name) {
  6549. name = typeof object;
  6550. }
  6551. }
  6552. return name;
  6553. };
  6554. Tools.first = function (array, predicate) {
  6555. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6556. var el = array_1[_i];
  6557. if (predicate(el)) {
  6558. return el;
  6559. }
  6560. }
  6561. };
  6562. /**
  6563. * This method will return the name of the full name of the class, including its owning module (if any).
  6564. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  6565. * @param object the object to get the class name from
  6566. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  6567. */
  6568. Tools.getFullClassName = function (object, isType) {
  6569. if (isType === void 0) { isType = false; }
  6570. var className = null;
  6571. var moduleName = null;
  6572. if (!isType && object.getClassName) {
  6573. className = object.getClassName();
  6574. }
  6575. else {
  6576. if (object instanceof Object) {
  6577. var classObj = isType ? object : Object.getPrototypeOf(object);
  6578. className = classObj.constructor["__bjsclassName__"];
  6579. moduleName = classObj.constructor["__bjsmoduleName__"];
  6580. }
  6581. if (!className) {
  6582. className = typeof object;
  6583. }
  6584. }
  6585. if (!className) {
  6586. return null;
  6587. }
  6588. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6589. };
  6590. /**
  6591. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  6592. * @param array
  6593. */
  6594. Tools.arrayOrStringFeeder = function (array) {
  6595. return function (index) {
  6596. if (index >= array.length) {
  6597. return null;
  6598. }
  6599. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6600. if (val && val.getHashCode) {
  6601. val = val.getHashCode();
  6602. }
  6603. if (typeof val === "string") {
  6604. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6605. }
  6606. return val;
  6607. };
  6608. };
  6609. /**
  6610. * Compute the hashCode of a stream of number
  6611. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6612. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6613. * @return the hash code computed
  6614. */
  6615. Tools.hashCodeFromStream = function (feeder) {
  6616. // Based from here: http://stackoverflow.com/a/7616484/802124
  6617. var hash = 0;
  6618. var index = 0;
  6619. var chr = feeder(index++);
  6620. while (chr != null) {
  6621. hash = ((hash << 5) - hash) + chr;
  6622. hash |= 0; // Convert to 32bit integer
  6623. chr = feeder(index++);
  6624. }
  6625. return hash;
  6626. };
  6627. Tools.BaseUrl = "";
  6628. Tools.CorsBehavior = "anonymous";
  6629. Tools.UseFallbackTexture = true;
  6630. // Used in case of a texture loading problem
  6631. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  6632. Tools.PreprocessUrl = function (url) {
  6633. return url;
  6634. };
  6635. // Logs
  6636. Tools._NoneLogLevel = 0;
  6637. Tools._MessageLogLevel = 1;
  6638. Tools._WarningLogLevel = 2;
  6639. Tools._ErrorLogLevel = 4;
  6640. Tools._LogCache = "";
  6641. Tools.errorsCount = 0;
  6642. Tools.Log = Tools._LogEnabled;
  6643. Tools.Warn = Tools._WarnEnabled;
  6644. Tools.Error = Tools._ErrorEnabled;
  6645. // Performances
  6646. Tools._PerformanceNoneLogLevel = 0;
  6647. Tools._PerformanceUserMarkLogLevel = 1;
  6648. Tools._PerformanceConsoleLogLevel = 2;
  6649. Tools._performance = window.performance;
  6650. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6651. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6652. return Tools;
  6653. }());
  6654. BABYLON.Tools = Tools;
  6655. /**
  6656. * This class is used to track a performance counter which is number based.
  6657. * The user has access to many properties which give statistics of different nature
  6658. *
  6659. * The implementer can track two kinds of Performance Counter: time and count
  6660. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  6661. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  6662. */
  6663. var PerfCounter = (function () {
  6664. function PerfCounter() {
  6665. this._startMonitoringTime = 0;
  6666. this._min = 0;
  6667. this._max = 0;
  6668. this._average = 0;
  6669. this._lastSecAverage = 0;
  6670. this._current = 0;
  6671. this._totalValueCount = 0;
  6672. this._totalAccumulated = 0;
  6673. this._lastSecAccumulated = 0;
  6674. this._lastSecTime = 0;
  6675. this._lastSecValueCount = 0;
  6676. }
  6677. Object.defineProperty(PerfCounter.prototype, "min", {
  6678. /**
  6679. * Returns the smallest value ever
  6680. */
  6681. get: function () {
  6682. return this._min;
  6683. },
  6684. enumerable: true,
  6685. configurable: true
  6686. });
  6687. Object.defineProperty(PerfCounter.prototype, "max", {
  6688. /**
  6689. * Returns the biggest value ever
  6690. */
  6691. get: function () {
  6692. return this._max;
  6693. },
  6694. enumerable: true,
  6695. configurable: true
  6696. });
  6697. Object.defineProperty(PerfCounter.prototype, "average", {
  6698. /**
  6699. * Returns the average value since the performance counter is running
  6700. */
  6701. get: function () {
  6702. return this._average;
  6703. },
  6704. enumerable: true,
  6705. configurable: true
  6706. });
  6707. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6708. /**
  6709. * Returns the average value of the last second the counter was monitored
  6710. */
  6711. get: function () {
  6712. return this._lastSecAverage;
  6713. },
  6714. enumerable: true,
  6715. configurable: true
  6716. });
  6717. Object.defineProperty(PerfCounter.prototype, "current", {
  6718. /**
  6719. * Returns the current value
  6720. */
  6721. get: function () {
  6722. return this._current;
  6723. },
  6724. enumerable: true,
  6725. configurable: true
  6726. });
  6727. Object.defineProperty(PerfCounter.prototype, "total", {
  6728. get: function () {
  6729. return this._totalAccumulated;
  6730. },
  6731. enumerable: true,
  6732. configurable: true
  6733. });
  6734. /**
  6735. * Call this method to start monitoring a new frame.
  6736. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  6737. */
  6738. PerfCounter.prototype.fetchNewFrame = function () {
  6739. this._totalValueCount++;
  6740. this._current = 0;
  6741. this._lastSecValueCount++;
  6742. };
  6743. /**
  6744. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6745. * @param newCount the count value to add to the monitored count
  6746. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  6747. */
  6748. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6749. if (!PerfCounter.Enabled) {
  6750. return;
  6751. }
  6752. this._current += newCount;
  6753. if (fetchResult) {
  6754. this._fetchResult();
  6755. }
  6756. };
  6757. /**
  6758. * Start monitoring this performance counter
  6759. */
  6760. PerfCounter.prototype.beginMonitoring = function () {
  6761. if (!PerfCounter.Enabled) {
  6762. return;
  6763. }
  6764. this._startMonitoringTime = Tools.Now;
  6765. };
  6766. /**
  6767. * Compute the time lapsed since the previous beginMonitoring() call.
  6768. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  6769. */
  6770. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6771. if (newFrame === void 0) { newFrame = true; }
  6772. if (!PerfCounter.Enabled) {
  6773. return;
  6774. }
  6775. if (newFrame) {
  6776. this.fetchNewFrame();
  6777. }
  6778. var currentTime = Tools.Now;
  6779. this._current = currentTime - this._startMonitoringTime;
  6780. if (newFrame) {
  6781. this._fetchResult();
  6782. }
  6783. };
  6784. PerfCounter.prototype._fetchResult = function () {
  6785. this._totalAccumulated += this._current;
  6786. this._lastSecAccumulated += this._current;
  6787. // Min/Max update
  6788. this._min = Math.min(this._min, this._current);
  6789. this._max = Math.max(this._max, this._current);
  6790. this._average = this._totalAccumulated / this._totalValueCount;
  6791. // Reset last sec?
  6792. var now = Tools.Now;
  6793. if ((now - this._lastSecTime) > 1000) {
  6794. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6795. this._lastSecTime = now;
  6796. this._lastSecAccumulated = 0;
  6797. this._lastSecValueCount = 0;
  6798. }
  6799. };
  6800. PerfCounter.Enabled = true;
  6801. return PerfCounter;
  6802. }());
  6803. BABYLON.PerfCounter = PerfCounter;
  6804. /**
  6805. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6806. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6807. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6808. * @param name The name of the class, case should be preserved
  6809. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6810. */
  6811. function className(name, module) {
  6812. return function (target) {
  6813. target["__bjsclassName__"] = name;
  6814. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6815. };
  6816. }
  6817. BABYLON.className = className;
  6818. /**
  6819. * An implementation of a loop for asynchronous functions.
  6820. */
  6821. var AsyncLoop = (function () {
  6822. /**
  6823. * Constroctor.
  6824. * @param iterations the number of iterations.
  6825. * @param _fn the function to run each iteration
  6826. * @param _successCallback the callback that will be called upon succesful execution
  6827. * @param offset starting offset.
  6828. */
  6829. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6830. if (offset === void 0) { offset = 0; }
  6831. this.iterations = iterations;
  6832. this._fn = _fn;
  6833. this._successCallback = _successCallback;
  6834. this.index = offset - 1;
  6835. this._done = false;
  6836. }
  6837. /**
  6838. * Execute the next iteration. Must be called after the last iteration was finished.
  6839. */
  6840. AsyncLoop.prototype.executeNext = function () {
  6841. if (!this._done) {
  6842. if (this.index + 1 < this.iterations) {
  6843. ++this.index;
  6844. this._fn(this);
  6845. }
  6846. else {
  6847. this.breakLoop();
  6848. }
  6849. }
  6850. };
  6851. /**
  6852. * Break the loop and run the success callback.
  6853. */
  6854. AsyncLoop.prototype.breakLoop = function () {
  6855. this._done = true;
  6856. this._successCallback();
  6857. };
  6858. /**
  6859. * Helper function
  6860. */
  6861. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6862. if (offset === void 0) { offset = 0; }
  6863. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6864. loop.executeNext();
  6865. return loop;
  6866. };
  6867. /**
  6868. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6869. * @param iterations total number of iterations
  6870. * @param syncedIterations number of synchronous iterations in each async iteration.
  6871. * @param fn the function to call each iteration.
  6872. * @param callback a success call back that will be called when iterating stops.
  6873. * @param breakFunction a break condition (optional)
  6874. * @param timeout timeout settings for the setTimeout function. default - 0.
  6875. * @constructor
  6876. */
  6877. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6878. if (timeout === void 0) { timeout = 0; }
  6879. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6880. if (breakFunction && breakFunction())
  6881. loop.breakLoop();
  6882. else {
  6883. setTimeout(function () {
  6884. for (var i = 0; i < syncedIterations; ++i) {
  6885. var iteration = (loop.index * syncedIterations) + i;
  6886. if (iteration >= iterations)
  6887. break;
  6888. fn(iteration);
  6889. if (breakFunction && breakFunction()) {
  6890. loop.breakLoop();
  6891. break;
  6892. }
  6893. }
  6894. loop.executeNext();
  6895. }, timeout);
  6896. }
  6897. }, callback);
  6898. };
  6899. return AsyncLoop;
  6900. }());
  6901. BABYLON.AsyncLoop = AsyncLoop;
  6902. })(BABYLON || (BABYLON = {}));
  6903. //# sourceMappingURL=babylon.tools.js.map
  6904. var BABYLON;
  6905. (function (BABYLON) {
  6906. var Internals;
  6907. (function (Internals) {
  6908. var _AlphaState = (function () {
  6909. /**
  6910. * Initializes the state.
  6911. */
  6912. function _AlphaState() {
  6913. this._isAlphaBlendDirty = false;
  6914. this._isBlendFunctionParametersDirty = false;
  6915. this._isBlendEquationParametersDirty = false;
  6916. this._isBlendConstantsDirty = false;
  6917. this._alphaBlend = false;
  6918. this._blendFunctionParameters = new Array(4);
  6919. this._blendEquationParameters = new Array(2);
  6920. this._blendConstants = new Array(4);
  6921. this.reset();
  6922. }
  6923. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6924. get: function () {
  6925. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6926. },
  6927. enumerable: true,
  6928. configurable: true
  6929. });
  6930. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6931. get: function () {
  6932. return this._alphaBlend;
  6933. },
  6934. set: function (value) {
  6935. if (this._alphaBlend === value) {
  6936. return;
  6937. }
  6938. this._alphaBlend = value;
  6939. this._isAlphaBlendDirty = true;
  6940. },
  6941. enumerable: true,
  6942. configurable: true
  6943. });
  6944. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6945. if (this._blendConstants[0] === r &&
  6946. this._blendConstants[1] === g &&
  6947. this._blendConstants[2] === b &&
  6948. this._blendConstants[3] === a) {
  6949. return;
  6950. }
  6951. this._blendConstants[0] = r;
  6952. this._blendConstants[1] = g;
  6953. this._blendConstants[2] = b;
  6954. this._blendConstants[3] = a;
  6955. this._isBlendConstantsDirty = true;
  6956. };
  6957. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6958. if (this._blendFunctionParameters[0] === value0 &&
  6959. this._blendFunctionParameters[1] === value1 &&
  6960. this._blendFunctionParameters[2] === value2 &&
  6961. this._blendFunctionParameters[3] === value3) {
  6962. return;
  6963. }
  6964. this._blendFunctionParameters[0] = value0;
  6965. this._blendFunctionParameters[1] = value1;
  6966. this._blendFunctionParameters[2] = value2;
  6967. this._blendFunctionParameters[3] = value3;
  6968. this._isBlendFunctionParametersDirty = true;
  6969. };
  6970. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6971. if (this._blendEquationParameters[0] === rgb &&
  6972. this._blendEquationParameters[1] === alpha) {
  6973. return;
  6974. }
  6975. this._blendEquationParameters[0] = rgb;
  6976. this._blendEquationParameters[1] = alpha;
  6977. this._isBlendEquationParametersDirty = true;
  6978. };
  6979. _AlphaState.prototype.reset = function () {
  6980. this._alphaBlend = false;
  6981. this._blendFunctionParameters[0] = null;
  6982. this._blendFunctionParameters[1] = null;
  6983. this._blendFunctionParameters[2] = null;
  6984. this._blendFunctionParameters[3] = null;
  6985. this._blendEquationParameters[0] = null;
  6986. this._blendEquationParameters[1] = null;
  6987. this._blendConstants[0] = null;
  6988. this._blendConstants[1] = null;
  6989. this._blendConstants[2] = null;
  6990. this._blendConstants[3] = null;
  6991. this._isAlphaBlendDirty = true;
  6992. this._isBlendFunctionParametersDirty = false;
  6993. this._isBlendEquationParametersDirty = false;
  6994. this._isBlendConstantsDirty = false;
  6995. };
  6996. _AlphaState.prototype.apply = function (gl) {
  6997. if (!this.isDirty) {
  6998. return;
  6999. }
  7000. // Alpha blend
  7001. if (this._isAlphaBlendDirty) {
  7002. if (this._alphaBlend) {
  7003. gl.enable(gl.BLEND);
  7004. }
  7005. else {
  7006. gl.disable(gl.BLEND);
  7007. }
  7008. this._isAlphaBlendDirty = false;
  7009. }
  7010. // Alpha function
  7011. if (this._isBlendFunctionParametersDirty) {
  7012. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7013. this._isBlendFunctionParametersDirty = false;
  7014. }
  7015. // Alpha equation
  7016. if (this._isBlendEquationParametersDirty) {
  7017. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7018. this._isBlendEquationParametersDirty = false;
  7019. }
  7020. // Constants
  7021. if (this._isBlendConstantsDirty) {
  7022. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7023. this._isBlendConstantsDirty = false;
  7024. }
  7025. };
  7026. return _AlphaState;
  7027. }());
  7028. Internals._AlphaState = _AlphaState;
  7029. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7030. })(BABYLON || (BABYLON = {}));
  7031. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7032. var BABYLON;
  7033. (function (BABYLON) {
  7034. var Internals;
  7035. (function (Internals) {
  7036. var _DepthCullingState = (function () {
  7037. /**
  7038. * Initializes the state.
  7039. */
  7040. function _DepthCullingState() {
  7041. this._isDepthTestDirty = false;
  7042. this._isDepthMaskDirty = false;
  7043. this._isDepthFuncDirty = false;
  7044. this._isCullFaceDirty = false;
  7045. this._isCullDirty = false;
  7046. this._isZOffsetDirty = false;
  7047. this.reset();
  7048. }
  7049. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7050. get: function () {
  7051. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7052. },
  7053. enumerable: true,
  7054. configurable: true
  7055. });
  7056. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7057. get: function () {
  7058. return this._zOffset;
  7059. },
  7060. set: function (value) {
  7061. if (this._zOffset === value) {
  7062. return;
  7063. }
  7064. this._zOffset = value;
  7065. this._isZOffsetDirty = true;
  7066. },
  7067. enumerable: true,
  7068. configurable: true
  7069. });
  7070. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7071. get: function () {
  7072. return this._cullFace;
  7073. },
  7074. set: function (value) {
  7075. if (this._cullFace === value) {
  7076. return;
  7077. }
  7078. this._cullFace = value;
  7079. this._isCullFaceDirty = true;
  7080. },
  7081. enumerable: true,
  7082. configurable: true
  7083. });
  7084. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7085. get: function () {
  7086. return this._cull;
  7087. },
  7088. set: function (value) {
  7089. if (this._cull === value) {
  7090. return;
  7091. }
  7092. this._cull = value;
  7093. this._isCullDirty = true;
  7094. },
  7095. enumerable: true,
  7096. configurable: true
  7097. });
  7098. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7099. get: function () {
  7100. return this._depthFunc;
  7101. },
  7102. set: function (value) {
  7103. if (this._depthFunc === value) {
  7104. return;
  7105. }
  7106. this._depthFunc = value;
  7107. this._isDepthFuncDirty = true;
  7108. },
  7109. enumerable: true,
  7110. configurable: true
  7111. });
  7112. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7113. get: function () {
  7114. return this._depthMask;
  7115. },
  7116. set: function (value) {
  7117. if (this._depthMask === value) {
  7118. return;
  7119. }
  7120. this._depthMask = value;
  7121. this._isDepthMaskDirty = true;
  7122. },
  7123. enumerable: true,
  7124. configurable: true
  7125. });
  7126. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7127. get: function () {
  7128. return this._depthTest;
  7129. },
  7130. set: function (value) {
  7131. if (this._depthTest === value) {
  7132. return;
  7133. }
  7134. this._depthTest = value;
  7135. this._isDepthTestDirty = true;
  7136. },
  7137. enumerable: true,
  7138. configurable: true
  7139. });
  7140. _DepthCullingState.prototype.reset = function () {
  7141. this._depthMask = true;
  7142. this._depthTest = true;
  7143. this._depthFunc = null;
  7144. this._cullFace = null;
  7145. this._cull = null;
  7146. this._zOffset = 0;
  7147. this._isDepthTestDirty = true;
  7148. this._isDepthMaskDirty = true;
  7149. this._isDepthFuncDirty = false;
  7150. this._isCullFaceDirty = false;
  7151. this._isCullDirty = false;
  7152. this._isZOffsetDirty = false;
  7153. };
  7154. _DepthCullingState.prototype.apply = function (gl) {
  7155. if (!this.isDirty) {
  7156. return;
  7157. }
  7158. // Cull
  7159. if (this._isCullDirty) {
  7160. if (this.cull) {
  7161. gl.enable(gl.CULL_FACE);
  7162. }
  7163. else {
  7164. gl.disable(gl.CULL_FACE);
  7165. }
  7166. this._isCullDirty = false;
  7167. }
  7168. // Cull face
  7169. if (this._isCullFaceDirty) {
  7170. gl.cullFace(this.cullFace);
  7171. this._isCullFaceDirty = false;
  7172. }
  7173. // Depth mask
  7174. if (this._isDepthMaskDirty) {
  7175. gl.depthMask(this.depthMask);
  7176. this._isDepthMaskDirty = false;
  7177. }
  7178. // Depth test
  7179. if (this._isDepthTestDirty) {
  7180. if (this.depthTest) {
  7181. gl.enable(gl.DEPTH_TEST);
  7182. }
  7183. else {
  7184. gl.disable(gl.DEPTH_TEST);
  7185. }
  7186. this._isDepthTestDirty = false;
  7187. }
  7188. // Depth func
  7189. if (this._isDepthFuncDirty) {
  7190. gl.depthFunc(this.depthFunc);
  7191. this._isDepthFuncDirty = false;
  7192. }
  7193. // zOffset
  7194. if (this._isZOffsetDirty) {
  7195. if (this.zOffset) {
  7196. gl.enable(gl.POLYGON_OFFSET_FILL);
  7197. gl.polygonOffset(this.zOffset, 0);
  7198. }
  7199. else {
  7200. gl.disable(gl.POLYGON_OFFSET_FILL);
  7201. }
  7202. this._isZOffsetDirty = false;
  7203. }
  7204. };
  7205. return _DepthCullingState;
  7206. }());
  7207. Internals._DepthCullingState = _DepthCullingState;
  7208. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7209. })(BABYLON || (BABYLON = {}));
  7210. //# sourceMappingURL=babylon.depthCullingState.js.map
  7211. var BABYLON;
  7212. (function (BABYLON) {
  7213. var Internals;
  7214. (function (Internals) {
  7215. var _StencilState = (function () {
  7216. function _StencilState() {
  7217. this._isStencilTestDirty = false;
  7218. this._isStencilMaskDirty = false;
  7219. this._isStencilFuncDirty = false;
  7220. this._isStencilOpDirty = false;
  7221. this.reset();
  7222. }
  7223. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7224. get: function () {
  7225. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7226. },
  7227. enumerable: true,
  7228. configurable: true
  7229. });
  7230. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7231. get: function () {
  7232. return this._stencilFunc;
  7233. },
  7234. set: function (value) {
  7235. if (this._stencilFunc === value) {
  7236. return;
  7237. }
  7238. this._stencilFunc = value;
  7239. this._isStencilFuncDirty = true;
  7240. },
  7241. enumerable: true,
  7242. configurable: true
  7243. });
  7244. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7245. get: function () {
  7246. return this._stencilFuncRef;
  7247. },
  7248. set: function (value) {
  7249. if (this._stencilFuncRef === value) {
  7250. return;
  7251. }
  7252. this._stencilFuncRef = value;
  7253. this._isStencilFuncDirty = true;
  7254. },
  7255. enumerable: true,
  7256. configurable: true
  7257. });
  7258. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7259. get: function () {
  7260. return this._stencilFuncMask;
  7261. },
  7262. set: function (value) {
  7263. if (this._stencilFuncMask === value) {
  7264. return;
  7265. }
  7266. this._stencilFuncMask = value;
  7267. this._isStencilFuncDirty = true;
  7268. },
  7269. enumerable: true,
  7270. configurable: true
  7271. });
  7272. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7273. get: function () {
  7274. return this._stencilOpStencilFail;
  7275. },
  7276. set: function (value) {
  7277. if (this._stencilOpStencilFail === value) {
  7278. return;
  7279. }
  7280. this._stencilOpStencilFail = value;
  7281. this._isStencilOpDirty = true;
  7282. },
  7283. enumerable: true,
  7284. configurable: true
  7285. });
  7286. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7287. get: function () {
  7288. return this._stencilOpDepthFail;
  7289. },
  7290. set: function (value) {
  7291. if (this._stencilOpDepthFail === value) {
  7292. return;
  7293. }
  7294. this._stencilOpDepthFail = value;
  7295. this._isStencilOpDirty = true;
  7296. },
  7297. enumerable: true,
  7298. configurable: true
  7299. });
  7300. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7301. get: function () {
  7302. return this._stencilOpStencilDepthPass;
  7303. },
  7304. set: function (value) {
  7305. if (this._stencilOpStencilDepthPass === value) {
  7306. return;
  7307. }
  7308. this._stencilOpStencilDepthPass = value;
  7309. this._isStencilOpDirty = true;
  7310. },
  7311. enumerable: true,
  7312. configurable: true
  7313. });
  7314. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7315. get: function () {
  7316. return this._stencilMask;
  7317. },
  7318. set: function (value) {
  7319. if (this._stencilMask === value) {
  7320. return;
  7321. }
  7322. this._stencilMask = value;
  7323. this._isStencilMaskDirty = true;
  7324. },
  7325. enumerable: true,
  7326. configurable: true
  7327. });
  7328. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7329. get: function () {
  7330. return this._stencilTest;
  7331. },
  7332. set: function (value) {
  7333. if (this._stencilTest === value) {
  7334. return;
  7335. }
  7336. this._stencilTest = value;
  7337. this._isStencilTestDirty = true;
  7338. },
  7339. enumerable: true,
  7340. configurable: true
  7341. });
  7342. _StencilState.prototype.reset = function () {
  7343. this._stencilTest = false;
  7344. this._stencilMask = 0xFF;
  7345. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7346. this._stencilFuncRef = 1;
  7347. this._stencilFuncMask = 0xFF;
  7348. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7349. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7350. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7351. this._isStencilTestDirty = true;
  7352. this._isStencilMaskDirty = true;
  7353. this._isStencilFuncDirty = true;
  7354. this._isStencilOpDirty = true;
  7355. };
  7356. _StencilState.prototype.apply = function (gl) {
  7357. if (!this.isDirty) {
  7358. return;
  7359. }
  7360. // Stencil test
  7361. if (this._isStencilTestDirty) {
  7362. if (this.stencilTest) {
  7363. gl.enable(gl.STENCIL_TEST);
  7364. }
  7365. else {
  7366. gl.disable(gl.STENCIL_TEST);
  7367. }
  7368. this._isStencilTestDirty = false;
  7369. }
  7370. // Stencil mask
  7371. if (this._isStencilMaskDirty) {
  7372. gl.stencilMask(this.stencilMask);
  7373. this._isStencilMaskDirty = false;
  7374. }
  7375. // Stencil func
  7376. if (this._isStencilFuncDirty) {
  7377. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7378. this._isStencilFuncDirty = false;
  7379. }
  7380. // Stencil op
  7381. if (this._isStencilOpDirty) {
  7382. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7383. this._isStencilOpDirty = false;
  7384. }
  7385. };
  7386. return _StencilState;
  7387. }());
  7388. Internals._StencilState = _StencilState;
  7389. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7390. })(BABYLON || (BABYLON = {}));
  7391. //# sourceMappingURL=babylon.stencilState.js.map
  7392. var BABYLON;
  7393. (function (BABYLON) {
  7394. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7395. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7396. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7397. gl.compileShader(shader);
  7398. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7399. throw new Error(gl.getShaderInfoLog(shader));
  7400. }
  7401. return shader;
  7402. };
  7403. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7404. var magFilter = gl.NEAREST;
  7405. var minFilter = gl.NEAREST;
  7406. switch (samplingMode) {
  7407. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7408. magFilter = gl.LINEAR;
  7409. if (generateMipMaps) {
  7410. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7411. }
  7412. else {
  7413. minFilter = gl.LINEAR;
  7414. }
  7415. break;
  7416. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7417. magFilter = gl.LINEAR;
  7418. if (generateMipMaps) {
  7419. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7420. }
  7421. else {
  7422. minFilter = gl.LINEAR;
  7423. }
  7424. break;
  7425. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7426. magFilter = gl.NEAREST;
  7427. if (generateMipMaps) {
  7428. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7429. }
  7430. else {
  7431. minFilter = gl.NEAREST;
  7432. }
  7433. break;
  7434. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7435. magFilter = gl.NEAREST;
  7436. if (generateMipMaps) {
  7437. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7438. }
  7439. else {
  7440. minFilter = gl.NEAREST;
  7441. }
  7442. break;
  7443. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7444. magFilter = gl.NEAREST;
  7445. if (generateMipMaps) {
  7446. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7447. }
  7448. else {
  7449. minFilter = gl.LINEAR;
  7450. }
  7451. break;
  7452. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7453. magFilter = gl.NEAREST;
  7454. if (generateMipMaps) {
  7455. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7456. }
  7457. else {
  7458. minFilter = gl.LINEAR;
  7459. }
  7460. break;
  7461. case BABYLON.Texture.NEAREST_LINEAR:
  7462. magFilter = gl.NEAREST;
  7463. minFilter = gl.LINEAR;
  7464. break;
  7465. case BABYLON.Texture.NEAREST_NEAREST:
  7466. magFilter = gl.NEAREST;
  7467. minFilter = gl.NEAREST;
  7468. break;
  7469. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7470. magFilter = gl.LINEAR;
  7471. if (generateMipMaps) {
  7472. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7473. }
  7474. else {
  7475. minFilter = gl.NEAREST;
  7476. }
  7477. break;
  7478. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7479. magFilter = gl.LINEAR;
  7480. if (generateMipMaps) {
  7481. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7482. }
  7483. else {
  7484. minFilter = gl.NEAREST;
  7485. }
  7486. break;
  7487. case BABYLON.Texture.LINEAR_LINEAR:
  7488. magFilter = gl.LINEAR;
  7489. minFilter = gl.LINEAR;
  7490. break;
  7491. case BABYLON.Texture.LINEAR_NEAREST:
  7492. magFilter = gl.LINEAR;
  7493. minFilter = gl.NEAREST;
  7494. break;
  7495. }
  7496. return {
  7497. min: minFilter,
  7498. mag: magFilter
  7499. };
  7500. };
  7501. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7502. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7503. var img;
  7504. var onload = function () {
  7505. loadedImages[index] = img;
  7506. loadedImages._internalCount++;
  7507. if (scene) {
  7508. scene._removePendingData(img);
  7509. }
  7510. if (loadedImages._internalCount === 6) {
  7511. onfinish(loadedImages);
  7512. }
  7513. };
  7514. var onerror = function () {
  7515. if (scene) {
  7516. scene._removePendingData(img);
  7517. }
  7518. if (onErrorCallBack) {
  7519. onErrorCallBack();
  7520. }
  7521. };
  7522. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7523. if (scene) {
  7524. scene._addPendingData(img);
  7525. }
  7526. };
  7527. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7528. if (onError === void 0) { onError = null; }
  7529. var loadedImages = [];
  7530. loadedImages._internalCount = 0;
  7531. for (var index = 0; index < 6; index++) {
  7532. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7533. }
  7534. };
  7535. var BufferPointer = (function () {
  7536. function BufferPointer() {
  7537. }
  7538. return BufferPointer;
  7539. }());
  7540. var InstancingAttributeInfo = (function () {
  7541. function InstancingAttributeInfo() {
  7542. }
  7543. return InstancingAttributeInfo;
  7544. }());
  7545. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7546. /**
  7547. * Define options used to create a render target texture
  7548. */
  7549. var RenderTargetCreationOptions = (function () {
  7550. function RenderTargetCreationOptions() {
  7551. }
  7552. return RenderTargetCreationOptions;
  7553. }());
  7554. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7555. /**
  7556. * Regroup several parameters relative to the browser in use
  7557. */
  7558. var EngineCapabilities = (function () {
  7559. function EngineCapabilities() {
  7560. }
  7561. return EngineCapabilities;
  7562. }());
  7563. BABYLON.EngineCapabilities = EngineCapabilities;
  7564. /**
  7565. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7566. */
  7567. var Engine = (function () {
  7568. /**
  7569. * @constructor
  7570. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7571. * @param {boolean} [antialias] - enable antialias
  7572. * @param options - further options to be sent to the getContext function
  7573. */
  7574. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7575. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7576. var _this = this;
  7577. // Public members
  7578. this.forcePOTTextures = false;
  7579. this.isFullscreen = false;
  7580. this.isPointerLock = false;
  7581. this.cullBackFaces = true;
  7582. this.renderEvenInBackground = true;
  7583. this.preventCacheWipeBetweenFrames = false;
  7584. // To enable/disable IDB support and avoid XHR on .manifest
  7585. this.enableOfflineSupport = false;
  7586. this.scenes = new Array();
  7587. this.postProcesses = new Array();
  7588. // Observables
  7589. /**
  7590. * Observable event triggered each time the rendering canvas is resized
  7591. */
  7592. this.onResizeObservable = new BABYLON.Observable();
  7593. /**
  7594. * Observable event triggered each time the canvas loses focus
  7595. */
  7596. this.onCanvasBlurObservable = new BABYLON.Observable();
  7597. /**
  7598. * Observable event triggered each time the canvas gains focus
  7599. */
  7600. this.onCanvasFocusObservable = new BABYLON.Observable();
  7601. /**
  7602. * Observable event triggered each time the canvas receives pointerout event
  7603. */
  7604. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7605. // Uniform buffers list
  7606. this.disableUniformBuffers = false;
  7607. this._uniformBuffers = new Array();
  7608. this._windowIsBackground = false;
  7609. this._webGLVersion = 1.0;
  7610. this._badOS = false;
  7611. this._badDesktopOS = false;
  7612. this._colorWrite = true;
  7613. this._drawCalls = new BABYLON.PerfCounter();
  7614. this._renderingQueueLaunched = false;
  7615. this._activeRenderLoops = [];
  7616. // Deterministic lockstepMaxSteps
  7617. this._deterministicLockstep = false;
  7618. this._lockstepMaxSteps = 4;
  7619. // Lost context
  7620. this.onContextLostObservable = new BABYLON.Observable();
  7621. this.onContextRestoredObservable = new BABYLON.Observable();
  7622. this._contextWasLost = false;
  7623. this._doNotHandleContextLost = false;
  7624. // FPS
  7625. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7626. this._fps = 60;
  7627. this._deltaTime = 0;
  7628. /**
  7629. * Turn this value on if you want to pause FPS computation when in background
  7630. */
  7631. this.disablePerformanceMonitorInBackground = false;
  7632. // States
  7633. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7634. this._stencilState = new BABYLON.Internals._StencilState();
  7635. this._alphaState = new BABYLON.Internals._AlphaState();
  7636. this._alphaMode = Engine.ALPHA_DISABLE;
  7637. // Cache
  7638. this._internalTexturesCache = new Array();
  7639. this._maxTextureChannels = 16;
  7640. this._activeTexturesCache = {};
  7641. this._compiledEffects = {};
  7642. this._vertexAttribArraysEnabled = [];
  7643. this._uintIndicesCurrentlySet = false;
  7644. this._currentBoundBuffer = new Array();
  7645. this._currentBufferPointers = new Array();
  7646. this._currentInstanceLocations = new Array();
  7647. this._currentInstanceBuffers = new Array();
  7648. this._vaoRecordInProgress = false;
  7649. this._mustWipeVertexAttributes = false;
  7650. // Hardware supported Compressed Textures
  7651. this._texturesSupported = new Array();
  7652. this._onVRFullScreenTriggered = function () {
  7653. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7654. //get the old size before we change
  7655. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7656. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7657. //get the width and height, change the render size
  7658. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7659. var width, height;
  7660. _this.setHardwareScalingLevel(1);
  7661. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7662. }
  7663. else {
  7664. //When the specs are implemented, need to uncomment this.
  7665. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7666. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7667. _this._vrDisplayEnabled = undefined;
  7668. }
  7669. };
  7670. var canvas;
  7671. Engine.Instances.push(this);
  7672. options = options || {};
  7673. if (canvasOrContext.getContext) {
  7674. canvas = canvasOrContext;
  7675. this._renderingCanvas = canvas;
  7676. if (antialias != null) {
  7677. options.antialias = antialias;
  7678. }
  7679. if (options.deterministicLockstep === undefined) {
  7680. options.deterministicLockstep = false;
  7681. }
  7682. if (options.lockstepMaxSteps === undefined) {
  7683. options.lockstepMaxSteps = 4;
  7684. }
  7685. if (options.preserveDrawingBuffer === undefined) {
  7686. options.preserveDrawingBuffer = false;
  7687. }
  7688. if (options.audioEngine === undefined) {
  7689. options.audioEngine = true;
  7690. }
  7691. if (options.stencil === undefined) {
  7692. options.stencil = true;
  7693. }
  7694. this._deterministicLockstep = options.deterministicLockstep;
  7695. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7696. this._doNotHandleContextLost = options.doNotHandleContextLost;
  7697. // GL
  7698. if (!options.disableWebGL2Support) {
  7699. try {
  7700. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7701. if (this._gl) {
  7702. this._webGLVersion = 2.0;
  7703. }
  7704. }
  7705. catch (e) {
  7706. // Do nothing
  7707. }
  7708. }
  7709. if (!this._gl) {
  7710. if (!canvas) {
  7711. throw new Error("The provided canvas is null or undefined.");
  7712. }
  7713. try {
  7714. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7715. }
  7716. catch (e) {
  7717. throw new Error("WebGL not supported");
  7718. }
  7719. }
  7720. if (!this._gl) {
  7721. throw new Error("WebGL not supported");
  7722. }
  7723. this._onCanvasFocus = function () {
  7724. _this.onCanvasFocusObservable.notifyObservers(_this);
  7725. };
  7726. this._onCanvasBlur = function () {
  7727. _this.onCanvasBlurObservable.notifyObservers(_this);
  7728. };
  7729. canvas.addEventListener("focus", this._onCanvasFocus);
  7730. canvas.addEventListener("blur", this._onCanvasBlur);
  7731. this._onBlur = function () {
  7732. if (_this.disablePerformanceMonitorInBackground) {
  7733. _this._performanceMonitor.disable();
  7734. }
  7735. _this._windowIsBackground = true;
  7736. };
  7737. this._onFocus = function () {
  7738. if (_this.disablePerformanceMonitorInBackground) {
  7739. _this._performanceMonitor.enable();
  7740. }
  7741. _this._windowIsBackground = false;
  7742. };
  7743. this._onCanvasPointerOut = function () {
  7744. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  7745. };
  7746. window.addEventListener("blur", this._onBlur);
  7747. window.addEventListener("focus", this._onFocus);
  7748. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  7749. // Context lost
  7750. if (!this._doNotHandleContextLost) {
  7751. this._onContextLost = function (evt) {
  7752. evt.preventDefault();
  7753. _this._contextWasLost = true;
  7754. BABYLON.Tools.Warn("WebGL context lost.");
  7755. _this.onContextLostObservable.notifyObservers(_this);
  7756. };
  7757. this._onContextRestored = function (evt) {
  7758. // Adding a timeout to avoid race condition at browser level
  7759. setTimeout(function () {
  7760. // Rebuild gl context
  7761. _this._initGLContext();
  7762. // Rebuild effects
  7763. _this._rebuildEffects();
  7764. // Rebuild textures
  7765. _this._rebuildInternalTextures();
  7766. // Rebuild buffers
  7767. _this._rebuildBuffers();
  7768. // Cache
  7769. _this.wipeCaches(true);
  7770. BABYLON.Tools.Warn("WebGL context successfully restored.");
  7771. _this.onContextRestoredObservable.notifyObservers(_this);
  7772. _this._contextWasLost = false;
  7773. }, 0);
  7774. };
  7775. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  7776. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  7777. }
  7778. }
  7779. else {
  7780. this._gl = canvasOrContext;
  7781. this._renderingCanvas = this._gl.canvas;
  7782. if (this._gl.renderbufferStorageMultisample) {
  7783. this._webGLVersion = 2.0;
  7784. }
  7785. options.stencil = this._gl.getContextAttributes().stencil;
  7786. }
  7787. // Viewport
  7788. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7789. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7790. this.resize();
  7791. this._isStencilEnable = options.stencil;
  7792. this._initGLContext();
  7793. if (canvas) {
  7794. // Fullscreen
  7795. this._onFullscreenChange = function () {
  7796. if (document.fullscreen !== undefined) {
  7797. _this.isFullscreen = document.fullscreen;
  7798. }
  7799. else if (document.mozFullScreen !== undefined) {
  7800. _this.isFullscreen = document.mozFullScreen;
  7801. }
  7802. else if (document.webkitIsFullScreen !== undefined) {
  7803. _this.isFullscreen = document.webkitIsFullScreen;
  7804. }
  7805. else if (document.msIsFullScreen !== undefined) {
  7806. _this.isFullscreen = document.msIsFullScreen;
  7807. }
  7808. // Pointer lock
  7809. if (_this.isFullscreen && _this._pointerLockRequested) {
  7810. canvas.requestPointerLock = canvas.requestPointerLock ||
  7811. canvas.msRequestPointerLock ||
  7812. canvas.mozRequestPointerLock ||
  7813. canvas.webkitRequestPointerLock;
  7814. if (canvas.requestPointerLock) {
  7815. canvas.requestPointerLock();
  7816. }
  7817. }
  7818. };
  7819. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7820. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7821. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7822. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7823. // Pointer lock
  7824. this._onPointerLockChange = function () {
  7825. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7826. document.webkitPointerLockElement === canvas ||
  7827. document.msPointerLockElement === canvas ||
  7828. document.pointerLockElement === canvas);
  7829. };
  7830. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7831. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7832. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7833. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7834. this._onVRDisplayPointerRestricted = function () {
  7835. canvas.requestPointerLock();
  7836. };
  7837. this._onVRDisplayPointerUnrestricted = function () {
  7838. document.exitPointerLock();
  7839. };
  7840. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  7841. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  7842. }
  7843. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7844. Engine.audioEngine = new BABYLON.AudioEngine();
  7845. }
  7846. // Prepare buffer pointers
  7847. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  7848. this._currentBufferPointers[i] = new BufferPointer();
  7849. }
  7850. // Load WebVR Devices
  7851. if (options.autoEnableWebVR) {
  7852. this.initWebVR();
  7853. }
  7854. // Detect if we are running on a faulty buggy OS.
  7855. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  7856. // Detect if we are running on a faulty buggy desktop OS.
  7857. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  7858. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7859. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  7860. }
  7861. Object.defineProperty(Engine, "LastCreatedEngine", {
  7862. get: function () {
  7863. if (Engine.Instances.length === 0) {
  7864. return null;
  7865. }
  7866. return Engine.Instances[Engine.Instances.length - 1];
  7867. },
  7868. enumerable: true,
  7869. configurable: true
  7870. });
  7871. Object.defineProperty(Engine, "LastCreatedScene", {
  7872. get: function () {
  7873. var lastCreatedEngine = Engine.LastCreatedEngine;
  7874. if (!lastCreatedEngine) {
  7875. return null;
  7876. }
  7877. if (lastCreatedEngine.scenes.length === 0) {
  7878. return null;
  7879. }
  7880. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7881. },
  7882. enumerable: true,
  7883. configurable: true
  7884. });
  7885. /**
  7886. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7887. */
  7888. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7889. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7890. var engine = Engine.Instances[engineIndex];
  7891. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7892. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7893. }
  7894. }
  7895. };
  7896. Object.defineProperty(Engine, "NEVER", {
  7897. get: function () {
  7898. return Engine._NEVER;
  7899. },
  7900. enumerable: true,
  7901. configurable: true
  7902. });
  7903. Object.defineProperty(Engine, "ALWAYS", {
  7904. get: function () {
  7905. return Engine._ALWAYS;
  7906. },
  7907. enumerable: true,
  7908. configurable: true
  7909. });
  7910. Object.defineProperty(Engine, "LESS", {
  7911. get: function () {
  7912. return Engine._LESS;
  7913. },
  7914. enumerable: true,
  7915. configurable: true
  7916. });
  7917. Object.defineProperty(Engine, "EQUAL", {
  7918. get: function () {
  7919. return Engine._EQUAL;
  7920. },
  7921. enumerable: true,
  7922. configurable: true
  7923. });
  7924. Object.defineProperty(Engine, "LEQUAL", {
  7925. get: function () {
  7926. return Engine._LEQUAL;
  7927. },
  7928. enumerable: true,
  7929. configurable: true
  7930. });
  7931. Object.defineProperty(Engine, "GREATER", {
  7932. get: function () {
  7933. return Engine._GREATER;
  7934. },
  7935. enumerable: true,
  7936. configurable: true
  7937. });
  7938. Object.defineProperty(Engine, "GEQUAL", {
  7939. get: function () {
  7940. return Engine._GEQUAL;
  7941. },
  7942. enumerable: true,
  7943. configurable: true
  7944. });
  7945. Object.defineProperty(Engine, "NOTEQUAL", {
  7946. get: function () {
  7947. return Engine._NOTEQUAL;
  7948. },
  7949. enumerable: true,
  7950. configurable: true
  7951. });
  7952. Object.defineProperty(Engine, "KEEP", {
  7953. get: function () {
  7954. return Engine._KEEP;
  7955. },
  7956. enumerable: true,
  7957. configurable: true
  7958. });
  7959. Object.defineProperty(Engine, "REPLACE", {
  7960. get: function () {
  7961. return Engine._REPLACE;
  7962. },
  7963. enumerable: true,
  7964. configurable: true
  7965. });
  7966. Object.defineProperty(Engine, "INCR", {
  7967. get: function () {
  7968. return Engine._INCR;
  7969. },
  7970. enumerable: true,
  7971. configurable: true
  7972. });
  7973. Object.defineProperty(Engine, "DECR", {
  7974. get: function () {
  7975. return Engine._DECR;
  7976. },
  7977. enumerable: true,
  7978. configurable: true
  7979. });
  7980. Object.defineProperty(Engine, "INVERT", {
  7981. get: function () {
  7982. return Engine._INVERT;
  7983. },
  7984. enumerable: true,
  7985. configurable: true
  7986. });
  7987. Object.defineProperty(Engine, "INCR_WRAP", {
  7988. get: function () {
  7989. return Engine._INCR_WRAP;
  7990. },
  7991. enumerable: true,
  7992. configurable: true
  7993. });
  7994. Object.defineProperty(Engine, "DECR_WRAP", {
  7995. get: function () {
  7996. return Engine._DECR_WRAP;
  7997. },
  7998. enumerable: true,
  7999. configurable: true
  8000. });
  8001. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8002. get: function () {
  8003. return Engine._ALPHA_DISABLE;
  8004. },
  8005. enumerable: true,
  8006. configurable: true
  8007. });
  8008. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8009. get: function () {
  8010. return Engine._ALPHA_ONEONE;
  8011. },
  8012. enumerable: true,
  8013. configurable: true
  8014. });
  8015. Object.defineProperty(Engine, "ALPHA_ADD", {
  8016. get: function () {
  8017. return Engine._ALPHA_ADD;
  8018. },
  8019. enumerable: true,
  8020. configurable: true
  8021. });
  8022. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8023. get: function () {
  8024. return Engine._ALPHA_COMBINE;
  8025. },
  8026. enumerable: true,
  8027. configurable: true
  8028. });
  8029. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8030. get: function () {
  8031. return Engine._ALPHA_SUBTRACT;
  8032. },
  8033. enumerable: true,
  8034. configurable: true
  8035. });
  8036. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8037. get: function () {
  8038. return Engine._ALPHA_MULTIPLY;
  8039. },
  8040. enumerable: true,
  8041. configurable: true
  8042. });
  8043. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8044. get: function () {
  8045. return Engine._ALPHA_MAXIMIZED;
  8046. },
  8047. enumerable: true,
  8048. configurable: true
  8049. });
  8050. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8051. get: function () {
  8052. return Engine._ALPHA_PREMULTIPLIED;
  8053. },
  8054. enumerable: true,
  8055. configurable: true
  8056. });
  8057. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8058. get: function () {
  8059. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8060. },
  8061. enumerable: true,
  8062. configurable: true
  8063. });
  8064. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8065. get: function () {
  8066. return Engine._ALPHA_INTERPOLATE;
  8067. },
  8068. enumerable: true,
  8069. configurable: true
  8070. });
  8071. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8072. get: function () {
  8073. return Engine._ALPHA_SCREENMODE;
  8074. },
  8075. enumerable: true,
  8076. configurable: true
  8077. });
  8078. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8079. get: function () {
  8080. return Engine._DELAYLOADSTATE_NONE;
  8081. },
  8082. enumerable: true,
  8083. configurable: true
  8084. });
  8085. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8086. get: function () {
  8087. return Engine._DELAYLOADSTATE_LOADED;
  8088. },
  8089. enumerable: true,
  8090. configurable: true
  8091. });
  8092. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8093. get: function () {
  8094. return Engine._DELAYLOADSTATE_LOADING;
  8095. },
  8096. enumerable: true,
  8097. configurable: true
  8098. });
  8099. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8100. get: function () {
  8101. return Engine._DELAYLOADSTATE_NOTLOADED;
  8102. },
  8103. enumerable: true,
  8104. configurable: true
  8105. });
  8106. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8107. get: function () {
  8108. return Engine._TEXTUREFORMAT_ALPHA;
  8109. },
  8110. enumerable: true,
  8111. configurable: true
  8112. });
  8113. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8114. get: function () {
  8115. return Engine._TEXTUREFORMAT_LUMINANCE;
  8116. },
  8117. enumerable: true,
  8118. configurable: true
  8119. });
  8120. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8121. get: function () {
  8122. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8123. },
  8124. enumerable: true,
  8125. configurable: true
  8126. });
  8127. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8128. get: function () {
  8129. return Engine._TEXTUREFORMAT_RGB;
  8130. },
  8131. enumerable: true,
  8132. configurable: true
  8133. });
  8134. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8135. get: function () {
  8136. return Engine._TEXTUREFORMAT_RGBA;
  8137. },
  8138. enumerable: true,
  8139. configurable: true
  8140. });
  8141. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8142. get: function () {
  8143. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8144. },
  8145. enumerable: true,
  8146. configurable: true
  8147. });
  8148. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8149. get: function () {
  8150. return Engine._TEXTURETYPE_FLOAT;
  8151. },
  8152. enumerable: true,
  8153. configurable: true
  8154. });
  8155. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8156. get: function () {
  8157. return Engine._TEXTURETYPE_HALF_FLOAT;
  8158. },
  8159. enumerable: true,
  8160. configurable: true
  8161. });
  8162. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8163. get: function () {
  8164. return Engine._SCALEMODE_FLOOR;
  8165. },
  8166. enumerable: true,
  8167. configurable: true
  8168. });
  8169. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8170. get: function () {
  8171. return Engine._SCALEMODE_NEAREST;
  8172. },
  8173. enumerable: true,
  8174. configurable: true
  8175. });
  8176. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8177. get: function () {
  8178. return Engine._SCALEMODE_CEILING;
  8179. },
  8180. enumerable: true,
  8181. configurable: true
  8182. });
  8183. Object.defineProperty(Engine, "Version", {
  8184. get: function () {
  8185. return "3.1-alpha";
  8186. },
  8187. enumerable: true,
  8188. configurable: true
  8189. });
  8190. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8191. get: function () {
  8192. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8193. },
  8194. enumerable: true,
  8195. configurable: true
  8196. });
  8197. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8198. get: function () {
  8199. return this._webGLVersion < 2 || this.forcePOTTextures;
  8200. },
  8201. enumerable: true,
  8202. configurable: true
  8203. });
  8204. Object.defineProperty(Engine.prototype, "badOS", {
  8205. get: function () {
  8206. return this._badOS;
  8207. },
  8208. enumerable: true,
  8209. configurable: true
  8210. });
  8211. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8212. get: function () {
  8213. return this._badDesktopOS;
  8214. },
  8215. enumerable: true,
  8216. configurable: true
  8217. });
  8218. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8219. get: function () {
  8220. return this._performanceMonitor;
  8221. },
  8222. enumerable: true,
  8223. configurable: true
  8224. });
  8225. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8226. get: function () {
  8227. return this._texturesSupported;
  8228. },
  8229. enumerable: true,
  8230. configurable: true
  8231. });
  8232. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8233. get: function () {
  8234. return this._textureFormatInUse;
  8235. },
  8236. enumerable: true,
  8237. configurable: true
  8238. });
  8239. Object.defineProperty(Engine.prototype, "currentViewport", {
  8240. get: function () {
  8241. return this._cachedViewport;
  8242. },
  8243. enumerable: true,
  8244. configurable: true
  8245. });
  8246. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8247. // Empty texture
  8248. get: function () {
  8249. if (!this._emptyTexture) {
  8250. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8251. }
  8252. return this._emptyTexture;
  8253. },
  8254. enumerable: true,
  8255. configurable: true
  8256. });
  8257. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8258. get: function () {
  8259. if (!this._emptyCubeTexture) {
  8260. var faceData = new Uint8Array(4);
  8261. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8262. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8263. }
  8264. return this._emptyCubeTexture;
  8265. },
  8266. enumerable: true,
  8267. configurable: true
  8268. });
  8269. Engine.prototype._rebuildInternalTextures = function () {
  8270. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8271. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8272. var internalTexture = currentState_1[_i];
  8273. internalTexture._rebuild();
  8274. }
  8275. };
  8276. Engine.prototype._rebuildEffects = function () {
  8277. for (var key in this._compiledEffects) {
  8278. var effect = this._compiledEffects[key];
  8279. effect._prepareEffect();
  8280. }
  8281. BABYLON.Effect.ResetCache();
  8282. };
  8283. Engine.prototype._rebuildBuffers = function () {
  8284. // Index / Vertex
  8285. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8286. var scene = _a[_i];
  8287. scene.resetCachedMaterial();
  8288. scene._rebuildGeometries();
  8289. scene._rebuildTextures();
  8290. }
  8291. // Uniforms
  8292. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8293. var uniformBuffer = _c[_b];
  8294. uniformBuffer._rebuild();
  8295. }
  8296. };
  8297. Engine.prototype._initGLContext = function () {
  8298. // Caps
  8299. this._caps = new EngineCapabilities();
  8300. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8301. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8302. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8303. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8304. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8305. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8306. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8307. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8308. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8309. // Infos
  8310. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8311. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8312. if (rendererInfo != null) {
  8313. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8314. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8315. }
  8316. if (!this._glVendor) {
  8317. this._glVendor = "Unknown vendor";
  8318. }
  8319. if (!this._glRenderer) {
  8320. this._glRenderer = "Unknown renderer";
  8321. }
  8322. // Constants
  8323. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8324. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8325. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8326. this._gl.DEPTH24_STENCIL8 = 35056;
  8327. // Extensions
  8328. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8329. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8330. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8331. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8332. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8333. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8334. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8335. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  8336. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8337. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8338. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8339. this._caps.highPrecisionShaderSupported = true;
  8340. // Checks if some of the format renders first to allow the use of webgl inspector.
  8341. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8342. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8343. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8344. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8345. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8346. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8347. if (this._webGLVersion > 1) {
  8348. this._gl.HALF_FLOAT_OES = 0x140B;
  8349. }
  8350. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8351. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8352. // Draw buffers
  8353. if (this._webGLVersion > 1) {
  8354. this._caps.drawBuffersExtension = true;
  8355. }
  8356. else {
  8357. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8358. if (drawBuffersExtension !== null) {
  8359. this._caps.drawBuffersExtension = true;
  8360. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8361. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8362. for (var i = 0; i < 16; i++) {
  8363. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8364. }
  8365. }
  8366. else {
  8367. this._caps.drawBuffersExtension = false;
  8368. }
  8369. }
  8370. // Depth Texture
  8371. if (this._webGLVersion > 1) {
  8372. this._caps.depthTextureExtension = true;
  8373. }
  8374. else {
  8375. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8376. if (depthTextureExtension != null) {
  8377. this._caps.depthTextureExtension = true;
  8378. }
  8379. }
  8380. // Vertex array object
  8381. if (this._webGLVersion > 1) {
  8382. this._caps.vertexArrayObject = true;
  8383. }
  8384. else {
  8385. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8386. if (vertexArrayObjectExtension != null) {
  8387. this._caps.vertexArrayObject = true;
  8388. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8389. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8390. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8391. }
  8392. else {
  8393. this._caps.vertexArrayObject = false;
  8394. }
  8395. }
  8396. // Instances count
  8397. if (this._webGLVersion > 1) {
  8398. this._caps.instancedArrays = true;
  8399. }
  8400. else {
  8401. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8402. if (instanceExtension != null) {
  8403. this._caps.instancedArrays = true;
  8404. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8405. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8406. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8407. }
  8408. else {
  8409. this._caps.instancedArrays = false;
  8410. }
  8411. }
  8412. // Intelligently add supported compressed formats in order to check for.
  8413. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8414. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8415. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8416. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8417. if (this._caps.astc)
  8418. this.texturesSupported.push('-astc.ktx');
  8419. if (this._caps.s3tc)
  8420. this.texturesSupported.push('-dxt.ktx');
  8421. if (this._caps.pvrtc)
  8422. this.texturesSupported.push('-pvrtc.ktx');
  8423. if (this._caps.etc2)
  8424. this.texturesSupported.push('-etc2.ktx');
  8425. if (this._caps.etc1)
  8426. this.texturesSupported.push('-etc1.ktx');
  8427. if (this._gl.getShaderPrecisionFormat) {
  8428. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8429. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8430. }
  8431. // Depth buffer
  8432. this.setDepthBuffer(true);
  8433. this.setDepthFunctionToLessOrEqual();
  8434. this.setDepthWrite(true);
  8435. };
  8436. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8437. get: function () {
  8438. return this._webGLVersion;
  8439. },
  8440. enumerable: true,
  8441. configurable: true
  8442. });
  8443. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8444. /**
  8445. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8446. */
  8447. get: function () {
  8448. return this._isStencilEnable;
  8449. },
  8450. enumerable: true,
  8451. configurable: true
  8452. });
  8453. Engine.prototype._prepareWorkingCanvas = function () {
  8454. if (this._workingCanvas) {
  8455. return;
  8456. }
  8457. this._workingCanvas = document.createElement("canvas");
  8458. this._workingContext = this._workingCanvas.getContext("2d");
  8459. };
  8460. Engine.prototype.resetTextureCache = function () {
  8461. for (var key in this._activeTexturesCache) {
  8462. this._activeTexturesCache[key] = null;
  8463. }
  8464. };
  8465. Engine.prototype.isDeterministicLockStep = function () {
  8466. return this._deterministicLockstep;
  8467. };
  8468. Engine.prototype.getLockstepMaxSteps = function () {
  8469. return this._lockstepMaxSteps;
  8470. };
  8471. Engine.prototype.getGlInfo = function () {
  8472. return {
  8473. vendor: this._glVendor,
  8474. renderer: this._glRenderer,
  8475. version: this._glVersion
  8476. };
  8477. };
  8478. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8479. if (useScreen === void 0) { useScreen = false; }
  8480. var viewport = camera.viewport;
  8481. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8482. };
  8483. Engine.prototype.getRenderWidth = function (useScreen) {
  8484. if (useScreen === void 0) { useScreen = false; }
  8485. if (!useScreen && this._currentRenderTarget) {
  8486. return this._currentRenderTarget.width;
  8487. }
  8488. return this._gl.drawingBufferWidth;
  8489. };
  8490. Engine.prototype.getRenderHeight = function (useScreen) {
  8491. if (useScreen === void 0) { useScreen = false; }
  8492. if (!useScreen && this._currentRenderTarget) {
  8493. return this._currentRenderTarget.height;
  8494. }
  8495. return this._gl.drawingBufferHeight;
  8496. };
  8497. Engine.prototype.getRenderingCanvas = function () {
  8498. return this._renderingCanvas;
  8499. };
  8500. Engine.prototype.getRenderingCanvasClientRect = function () {
  8501. return this._renderingCanvas.getBoundingClientRect();
  8502. };
  8503. Engine.prototype.setHardwareScalingLevel = function (level) {
  8504. this._hardwareScalingLevel = level;
  8505. this.resize();
  8506. };
  8507. Engine.prototype.getHardwareScalingLevel = function () {
  8508. return this._hardwareScalingLevel;
  8509. };
  8510. Engine.prototype.getLoadedTexturesCache = function () {
  8511. return this._internalTexturesCache;
  8512. };
  8513. Engine.prototype.getCaps = function () {
  8514. return this._caps;
  8515. };
  8516. Object.defineProperty(Engine.prototype, "drawCalls", {
  8517. /** The number of draw calls submitted last frame */
  8518. get: function () {
  8519. return this._drawCalls.current;
  8520. },
  8521. enumerable: true,
  8522. configurable: true
  8523. });
  8524. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8525. get: function () {
  8526. return this._drawCalls;
  8527. },
  8528. enumerable: true,
  8529. configurable: true
  8530. });
  8531. Engine.prototype.getDepthFunction = function () {
  8532. return this._depthCullingState.depthFunc;
  8533. };
  8534. Engine.prototype.setDepthFunction = function (depthFunc) {
  8535. this._depthCullingState.depthFunc = depthFunc;
  8536. };
  8537. Engine.prototype.setDepthFunctionToGreater = function () {
  8538. this._depthCullingState.depthFunc = this._gl.GREATER;
  8539. };
  8540. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8541. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8542. };
  8543. Engine.prototype.setDepthFunctionToLess = function () {
  8544. this._depthCullingState.depthFunc = this._gl.LESS;
  8545. };
  8546. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8547. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8548. };
  8549. Engine.prototype.getStencilBuffer = function () {
  8550. return this._stencilState.stencilTest;
  8551. };
  8552. Engine.prototype.setStencilBuffer = function (enable) {
  8553. this._stencilState.stencilTest = enable;
  8554. };
  8555. Engine.prototype.getStencilMask = function () {
  8556. return this._stencilState.stencilMask;
  8557. };
  8558. Engine.prototype.setStencilMask = function (mask) {
  8559. this._stencilState.stencilMask = mask;
  8560. };
  8561. Engine.prototype.getStencilFunction = function () {
  8562. return this._stencilState.stencilFunc;
  8563. };
  8564. Engine.prototype.getStencilFunctionReference = function () {
  8565. return this._stencilState.stencilFuncRef;
  8566. };
  8567. Engine.prototype.getStencilFunctionMask = function () {
  8568. return this._stencilState.stencilFuncMask;
  8569. };
  8570. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8571. this._stencilState.stencilFunc = stencilFunc;
  8572. };
  8573. Engine.prototype.setStencilFunctionReference = function (reference) {
  8574. this._stencilState.stencilFuncRef = reference;
  8575. };
  8576. Engine.prototype.setStencilFunctionMask = function (mask) {
  8577. this._stencilState.stencilFuncMask = mask;
  8578. };
  8579. Engine.prototype.getStencilOperationFail = function () {
  8580. return this._stencilState.stencilOpStencilFail;
  8581. };
  8582. Engine.prototype.getStencilOperationDepthFail = function () {
  8583. return this._stencilState.stencilOpDepthFail;
  8584. };
  8585. Engine.prototype.getStencilOperationPass = function () {
  8586. return this._stencilState.stencilOpStencilDepthPass;
  8587. };
  8588. Engine.prototype.setStencilOperationFail = function (operation) {
  8589. this._stencilState.stencilOpStencilFail = operation;
  8590. };
  8591. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8592. this._stencilState.stencilOpDepthFail = operation;
  8593. };
  8594. Engine.prototype.setStencilOperationPass = function (operation) {
  8595. this._stencilState.stencilOpStencilDepthPass = operation;
  8596. };
  8597. Engine.prototype.setDitheringState = function (value) {
  8598. if (value) {
  8599. this._gl.enable(this._gl.DITHER);
  8600. }
  8601. else {
  8602. this._gl.disable(this._gl.DITHER);
  8603. }
  8604. };
  8605. /**
  8606. * stop executing a render loop function and remove it from the execution array
  8607. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8608. */
  8609. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8610. if (!renderFunction) {
  8611. this._activeRenderLoops = [];
  8612. return;
  8613. }
  8614. var index = this._activeRenderLoops.indexOf(renderFunction);
  8615. if (index >= 0) {
  8616. this._activeRenderLoops.splice(index, 1);
  8617. }
  8618. };
  8619. Engine.prototype._renderLoop = function () {
  8620. if (this._activeRenderLoops.length > 0) {
  8621. // Register new frame
  8622. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8623. }
  8624. else {
  8625. this._renderingQueueLaunched = false;
  8626. }
  8627. // Effective render
  8628. if (!this._contextWasLost) {
  8629. var shouldRender = true;
  8630. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8631. shouldRender = false;
  8632. }
  8633. if (shouldRender) {
  8634. // Start new frame
  8635. this.beginFrame();
  8636. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8637. var renderFunction = this._activeRenderLoops[index];
  8638. renderFunction();
  8639. }
  8640. // Present
  8641. this.endFrame();
  8642. }
  8643. }
  8644. };
  8645. /**
  8646. * Register and execute a render loop. The engine can have more than one render function.
  8647. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8648. * @example
  8649. * engine.runRenderLoop(function () {
  8650. * scene.render()
  8651. * })
  8652. */
  8653. Engine.prototype.runRenderLoop = function (renderFunction) {
  8654. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8655. return;
  8656. }
  8657. this._activeRenderLoops.push(renderFunction);
  8658. if (!this._renderingQueueLaunched) {
  8659. this._renderingQueueLaunched = true;
  8660. this._bindedRenderFunction = this._renderLoop.bind(this);
  8661. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8662. }
  8663. };
  8664. /**
  8665. * Toggle full screen mode.
  8666. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8667. * @param {any} options - an options object to be sent to the requestFullscreen function
  8668. */
  8669. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8670. if (this.isFullscreen) {
  8671. BABYLON.Tools.ExitFullscreen();
  8672. }
  8673. else {
  8674. this._pointerLockRequested = requestPointerLock;
  8675. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8676. }
  8677. };
  8678. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8679. if (stencil === void 0) { stencil = false; }
  8680. this.applyStates();
  8681. var mode = 0;
  8682. if (backBuffer && color) {
  8683. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8684. mode |= this._gl.COLOR_BUFFER_BIT;
  8685. }
  8686. if (depth) {
  8687. this._gl.clearDepth(1.0);
  8688. mode |= this._gl.DEPTH_BUFFER_BIT;
  8689. }
  8690. if (stencil) {
  8691. this._gl.clearStencil(0);
  8692. mode |= this._gl.STENCIL_BUFFER_BIT;
  8693. }
  8694. this._gl.clear(mode);
  8695. };
  8696. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8697. var gl = this._gl;
  8698. // Save state
  8699. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8700. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8701. // Change state
  8702. gl.enable(gl.SCISSOR_TEST);
  8703. gl.scissor(x, y, width, height);
  8704. // Clear
  8705. this.clear(clearColor, true, true, true);
  8706. // Restore state
  8707. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8708. if (curScissor === true) {
  8709. gl.enable(gl.SCISSOR_TEST);
  8710. }
  8711. else {
  8712. gl.disable(gl.SCISSOR_TEST);
  8713. }
  8714. };
  8715. /**
  8716. * Set the WebGL's viewport
  8717. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8718. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8719. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8720. */
  8721. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8722. var width = requiredWidth || this.getRenderWidth();
  8723. var height = requiredHeight || this.getRenderHeight();
  8724. var x = viewport.x || 0;
  8725. var y = viewport.y || 0;
  8726. this._cachedViewport = viewport;
  8727. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8728. };
  8729. /**
  8730. * Directly set the WebGL Viewport
  8731. * The x, y, width & height are directly passed to the WebGL call
  8732. * @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.
  8733. */
  8734. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8735. var currentViewport = this._cachedViewport;
  8736. this._cachedViewport = null;
  8737. this._gl.viewport(x, y, width, height);
  8738. return currentViewport;
  8739. };
  8740. Engine.prototype.beginFrame = function () {
  8741. this._measureFps();
  8742. };
  8743. Engine.prototype.endFrame = function () {
  8744. //force a flush in case we are using a bad OS.
  8745. if (this._badOS) {
  8746. this.flushFramebuffer();
  8747. }
  8748. //submit frame to the vr device, if enabled
  8749. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8750. this._vrDisplayEnabled.submitFrame();
  8751. }
  8752. };
  8753. /**
  8754. * resize the view according to the canvas' size.
  8755. * @example
  8756. * window.addEventListener("resize", function () {
  8757. * engine.resize();
  8758. * });
  8759. */
  8760. Engine.prototype.resize = function () {
  8761. // We're not resizing the size of the canvas while in VR mode & presenting
  8762. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8763. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8764. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8765. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8766. }
  8767. };
  8768. /**
  8769. * force a specific size of the canvas
  8770. * @param {number} width - the new canvas' width
  8771. * @param {number} height - the new canvas' height
  8772. */
  8773. Engine.prototype.setSize = function (width, height) {
  8774. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8775. return;
  8776. }
  8777. this._renderingCanvas.width = width;
  8778. this._renderingCanvas.height = height;
  8779. for (var index = 0; index < this.scenes.length; index++) {
  8780. var scene = this.scenes[index];
  8781. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8782. var cam = scene.cameras[camIndex];
  8783. cam._currentRenderId = 0;
  8784. }
  8785. }
  8786. if (this.onResizeObservable.hasObservers) {
  8787. this.onResizeObservable.notifyObservers(this);
  8788. }
  8789. };
  8790. //WebVR functions
  8791. Engine.prototype.isVRDevicePresent = function (callback) {
  8792. this.getVRDevice(null, function (device) {
  8793. callback(device !== null);
  8794. });
  8795. };
  8796. Engine.prototype.getVRDevice = function (name, callback) {
  8797. if (!this.vrDisplaysPromise) {
  8798. callback(null);
  8799. return;
  8800. }
  8801. this.vrDisplaysPromise.then(function (devices) {
  8802. if (devices.length > 0) {
  8803. if (name) {
  8804. var found = devices.some(function (device) {
  8805. if (device.displayName === name) {
  8806. callback(device);
  8807. return true;
  8808. }
  8809. else {
  8810. return false;
  8811. }
  8812. });
  8813. if (!found) {
  8814. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8815. callback(devices[0]);
  8816. }
  8817. }
  8818. else {
  8819. //choose the first one
  8820. callback(devices[0]);
  8821. }
  8822. }
  8823. else {
  8824. BABYLON.Tools.Error("No WebVR devices found!");
  8825. callback(null);
  8826. }
  8827. });
  8828. };
  8829. Engine.prototype.initWebVR = function () {
  8830. if (!this.vrDisplaysPromise) {
  8831. this._getVRDisplays();
  8832. }
  8833. };
  8834. Engine.prototype.enableVR = function (vrDevice) {
  8835. this._vrDisplayEnabled = vrDevice;
  8836. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8837. };
  8838. Engine.prototype.disableVR = function () {
  8839. if (this._vrDisplayEnabled) {
  8840. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8841. }
  8842. };
  8843. Engine.prototype._getVRDisplays = function () {
  8844. var _this = this;
  8845. var getWebVRDevices = function (devices) {
  8846. _this._vrDisplays = devices.filter(function (device) {
  8847. return device instanceof VRDisplay;
  8848. });
  8849. return _this._vrDisplays;
  8850. };
  8851. if (navigator.getVRDisplays) {
  8852. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8853. }
  8854. };
  8855. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  8856. if (this._currentRenderTarget) {
  8857. this.unBindFramebuffer(this._currentRenderTarget);
  8858. }
  8859. this._currentRenderTarget = texture;
  8860. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8861. var gl = this._gl;
  8862. if (texture.isCube) {
  8863. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  8864. }
  8865. if (this._cachedViewport && !forceFullscreenViewport) {
  8866. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  8867. }
  8868. else {
  8869. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  8870. }
  8871. this.wipeCaches();
  8872. };
  8873. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8874. if (this._currentFramebuffer !== framebuffer) {
  8875. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8876. this._currentFramebuffer = framebuffer;
  8877. }
  8878. };
  8879. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8880. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8881. this._currentRenderTarget = null;
  8882. // If MSAA, we need to bitblt back to main texture
  8883. var gl = this._gl;
  8884. if (texture._MSAAFramebuffer) {
  8885. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8886. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8887. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8888. }
  8889. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  8890. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8891. gl.generateMipmap(gl.TEXTURE_2D);
  8892. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8893. }
  8894. if (onBeforeUnbind) {
  8895. if (texture._MSAAFramebuffer) {
  8896. // Bind the correct framebuffer
  8897. this.bindUnboundFramebuffer(texture._framebuffer);
  8898. }
  8899. onBeforeUnbind();
  8900. }
  8901. this.bindUnboundFramebuffer(null);
  8902. };
  8903. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8904. if (texture.generateMipMaps) {
  8905. var gl = this._gl;
  8906. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8907. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8908. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8909. }
  8910. };
  8911. Engine.prototype.flushFramebuffer = function () {
  8912. this._gl.flush();
  8913. };
  8914. Engine.prototype.restoreDefaultFramebuffer = function () {
  8915. if (this._currentRenderTarget) {
  8916. this.unBindFramebuffer(this._currentRenderTarget);
  8917. }
  8918. else {
  8919. this.bindUnboundFramebuffer(null);
  8920. }
  8921. if (this._cachedViewport) {
  8922. this.setViewport(this._cachedViewport);
  8923. }
  8924. this.wipeCaches();
  8925. };
  8926. // UBOs
  8927. Engine.prototype.createUniformBuffer = function (elements) {
  8928. var ubo = this._gl.createBuffer();
  8929. this.bindUniformBuffer(ubo);
  8930. if (elements instanceof Float32Array) {
  8931. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8932. }
  8933. else {
  8934. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8935. }
  8936. this.bindUniformBuffer(null);
  8937. ubo.references = 1;
  8938. return ubo;
  8939. };
  8940. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8941. var ubo = this._gl.createBuffer();
  8942. this.bindUniformBuffer(ubo);
  8943. if (elements instanceof Float32Array) {
  8944. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8945. }
  8946. else {
  8947. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8948. }
  8949. this.bindUniformBuffer(null);
  8950. ubo.references = 1;
  8951. return ubo;
  8952. };
  8953. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8954. this.bindUniformBuffer(uniformBuffer);
  8955. if (offset === undefined) {
  8956. offset = 0;
  8957. }
  8958. if (count === undefined) {
  8959. if (elements instanceof Float32Array) {
  8960. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8961. }
  8962. else {
  8963. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8964. }
  8965. }
  8966. else {
  8967. if (elements instanceof Float32Array) {
  8968. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8969. }
  8970. else {
  8971. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8972. }
  8973. }
  8974. this.bindUniformBuffer(null);
  8975. };
  8976. // VBOs
  8977. Engine.prototype._resetVertexBufferBinding = function () {
  8978. this.bindArrayBuffer(null);
  8979. this._cachedVertexBuffers = null;
  8980. };
  8981. Engine.prototype.createVertexBuffer = function (vertices) {
  8982. var vbo = this._gl.createBuffer();
  8983. this.bindArrayBuffer(vbo);
  8984. if (vertices instanceof Float32Array) {
  8985. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8986. }
  8987. else {
  8988. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8989. }
  8990. this._resetVertexBufferBinding();
  8991. vbo.references = 1;
  8992. return vbo;
  8993. };
  8994. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8995. var vbo = this._gl.createBuffer();
  8996. this.bindArrayBuffer(vbo);
  8997. if (vertices instanceof Float32Array) {
  8998. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8999. }
  9000. else {
  9001. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9002. }
  9003. this._resetVertexBufferBinding();
  9004. vbo.references = 1;
  9005. return vbo;
  9006. };
  9007. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9008. this.bindArrayBuffer(vertexBuffer);
  9009. if (offset === undefined) {
  9010. offset = 0;
  9011. }
  9012. if (count === undefined) {
  9013. if (vertices instanceof Float32Array) {
  9014. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9015. }
  9016. else {
  9017. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9018. }
  9019. }
  9020. else {
  9021. if (vertices instanceof Float32Array) {
  9022. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9023. }
  9024. else {
  9025. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9026. }
  9027. }
  9028. this._resetVertexBufferBinding();
  9029. };
  9030. Engine.prototype._resetIndexBufferBinding = function () {
  9031. this.bindIndexBuffer(null);
  9032. this._cachedIndexBuffer = null;
  9033. };
  9034. Engine.prototype.createIndexBuffer = function (indices) {
  9035. var vbo = this._gl.createBuffer();
  9036. this.bindIndexBuffer(vbo);
  9037. // Check for 32 bits indices
  9038. var arrayBuffer;
  9039. var need32Bits = false;
  9040. if (indices instanceof Uint16Array) {
  9041. arrayBuffer = indices;
  9042. }
  9043. else {
  9044. //check 32 bit support
  9045. if (this._caps.uintIndices) {
  9046. if (indices instanceof Uint32Array) {
  9047. arrayBuffer = indices;
  9048. need32Bits = true;
  9049. }
  9050. else {
  9051. //number[] or Int32Array, check if 32 bit is necessary
  9052. for (var index = 0; index < indices.length; index++) {
  9053. if (indices[index] > 65535) {
  9054. need32Bits = true;
  9055. break;
  9056. }
  9057. }
  9058. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9059. }
  9060. }
  9061. else {
  9062. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9063. arrayBuffer = new Uint16Array(indices);
  9064. }
  9065. }
  9066. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  9067. this._resetIndexBufferBinding();
  9068. vbo.references = 1;
  9069. vbo.is32Bits = need32Bits;
  9070. return vbo;
  9071. };
  9072. Engine.prototype.bindArrayBuffer = function (buffer) {
  9073. if (!this._vaoRecordInProgress) {
  9074. this._unbindVertexArrayObject();
  9075. }
  9076. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9077. };
  9078. Engine.prototype.bindUniformBuffer = function (buffer) {
  9079. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9080. };
  9081. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9082. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9083. };
  9084. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9085. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9086. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9087. };
  9088. ;
  9089. Engine.prototype.bindIndexBuffer = function (buffer) {
  9090. if (!this._vaoRecordInProgress) {
  9091. this._unbindVertexArrayObject();
  9092. }
  9093. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9094. };
  9095. Engine.prototype.bindBuffer = function (buffer, target) {
  9096. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9097. this._gl.bindBuffer(target, buffer);
  9098. this._currentBoundBuffer[target] = buffer;
  9099. }
  9100. };
  9101. Engine.prototype.updateArrayBuffer = function (data) {
  9102. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9103. };
  9104. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9105. var pointer = this._currentBufferPointers[indx];
  9106. var changed = false;
  9107. if (!pointer.active) {
  9108. changed = true;
  9109. pointer.active = true;
  9110. pointer.index = indx;
  9111. pointer.size = size;
  9112. pointer.type = type;
  9113. pointer.normalized = normalized;
  9114. pointer.stride = stride;
  9115. pointer.offset = offset;
  9116. pointer.buffer = buffer;
  9117. }
  9118. else {
  9119. if (pointer.buffer !== buffer) {
  9120. pointer.buffer = buffer;
  9121. changed = true;
  9122. }
  9123. if (pointer.size !== size) {
  9124. pointer.size = size;
  9125. changed = true;
  9126. }
  9127. if (pointer.type !== type) {
  9128. pointer.type = type;
  9129. changed = true;
  9130. }
  9131. if (pointer.normalized !== normalized) {
  9132. pointer.normalized = normalized;
  9133. changed = true;
  9134. }
  9135. if (pointer.stride !== stride) {
  9136. pointer.stride = stride;
  9137. changed = true;
  9138. }
  9139. if (pointer.offset !== offset) {
  9140. pointer.offset = offset;
  9141. changed = true;
  9142. }
  9143. }
  9144. if (changed || this._vaoRecordInProgress) {
  9145. this.bindArrayBuffer(buffer);
  9146. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9147. }
  9148. };
  9149. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9150. if (indexBuffer == null) {
  9151. return;
  9152. }
  9153. if (this._cachedIndexBuffer !== indexBuffer) {
  9154. this._cachedIndexBuffer = indexBuffer;
  9155. this.bindIndexBuffer(indexBuffer);
  9156. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9157. }
  9158. };
  9159. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9160. var attributes = effect.getAttributesNames();
  9161. if (!this._vaoRecordInProgress) {
  9162. this._unbindVertexArrayObject();
  9163. }
  9164. this.unbindAllAttributes();
  9165. for (var index = 0; index < attributes.length; index++) {
  9166. var order = effect.getAttributeLocation(index);
  9167. if (order >= 0) {
  9168. var vertexBuffer = vertexBuffers[attributes[index]];
  9169. if (!vertexBuffer) {
  9170. continue;
  9171. }
  9172. this._gl.enableVertexAttribArray(order);
  9173. if (!this._vaoRecordInProgress) {
  9174. this._vertexAttribArraysEnabled[order] = true;
  9175. }
  9176. var buffer = vertexBuffer.getBuffer();
  9177. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9178. if (vertexBuffer.getIsInstanced()) {
  9179. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9180. if (!this._vaoRecordInProgress) {
  9181. this._currentInstanceLocations.push(order);
  9182. this._currentInstanceBuffers.push(buffer);
  9183. }
  9184. }
  9185. }
  9186. }
  9187. };
  9188. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9189. var vao = this._gl.createVertexArray();
  9190. this._vaoRecordInProgress = true;
  9191. this._gl.bindVertexArray(vao);
  9192. this._mustWipeVertexAttributes = true;
  9193. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9194. this.bindIndexBuffer(indexBuffer);
  9195. this._vaoRecordInProgress = false;
  9196. this._gl.bindVertexArray(null);
  9197. return vao;
  9198. };
  9199. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9200. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9201. this._cachedVertexArrayObject = vertexArrayObject;
  9202. this._gl.bindVertexArray(vertexArrayObject);
  9203. this._cachedVertexBuffers = null;
  9204. this._cachedIndexBuffer = null;
  9205. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9206. this._mustWipeVertexAttributes = true;
  9207. }
  9208. };
  9209. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9210. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9211. this._cachedVertexBuffers = vertexBuffer;
  9212. this._cachedEffectForVertexBuffers = effect;
  9213. var attributesCount = effect.getAttributesCount();
  9214. this._unbindVertexArrayObject();
  9215. this.unbindAllAttributes();
  9216. var offset = 0;
  9217. for (var index = 0; index < attributesCount; index++) {
  9218. if (index < vertexDeclaration.length) {
  9219. var order = effect.getAttributeLocation(index);
  9220. if (order >= 0) {
  9221. this._gl.enableVertexAttribArray(order);
  9222. this._vertexAttribArraysEnabled[order] = true;
  9223. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9224. }
  9225. offset += vertexDeclaration[index] * 4;
  9226. }
  9227. }
  9228. }
  9229. this._bindIndexBufferWithCache(indexBuffer);
  9230. };
  9231. Engine.prototype._unbindVertexArrayObject = function () {
  9232. if (!this._cachedVertexArrayObject) {
  9233. return;
  9234. }
  9235. this._cachedVertexArrayObject = null;
  9236. this._gl.bindVertexArray(null);
  9237. };
  9238. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9239. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9240. this._cachedVertexBuffers = vertexBuffers;
  9241. this._cachedEffectForVertexBuffers = effect;
  9242. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9243. }
  9244. this._bindIndexBufferWithCache(indexBuffer);
  9245. };
  9246. Engine.prototype.unbindInstanceAttributes = function () {
  9247. var boundBuffer;
  9248. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9249. var instancesBuffer = this._currentInstanceBuffers[i];
  9250. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9251. boundBuffer = instancesBuffer;
  9252. this.bindArrayBuffer(instancesBuffer);
  9253. }
  9254. var offsetLocation = this._currentInstanceLocations[i];
  9255. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9256. }
  9257. this._currentInstanceBuffers.length = 0;
  9258. this._currentInstanceLocations.length = 0;
  9259. };
  9260. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9261. this._gl.deleteVertexArray(vao);
  9262. };
  9263. Engine.prototype._releaseBuffer = function (buffer) {
  9264. buffer.references--;
  9265. if (buffer.references === 0) {
  9266. this._gl.deleteBuffer(buffer);
  9267. return true;
  9268. }
  9269. return false;
  9270. };
  9271. Engine.prototype.createInstancesBuffer = function (capacity) {
  9272. var buffer = this._gl.createBuffer();
  9273. buffer.capacity = capacity;
  9274. this.bindArrayBuffer(buffer);
  9275. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9276. return buffer;
  9277. };
  9278. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9279. this._gl.deleteBuffer(buffer);
  9280. };
  9281. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9282. this.bindArrayBuffer(instancesBuffer);
  9283. if (data) {
  9284. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9285. }
  9286. if (offsetLocations[0].index !== undefined) {
  9287. var stride = 0;
  9288. for (var i = 0; i < offsetLocations.length; i++) {
  9289. var ai = offsetLocations[i];
  9290. stride += ai.attributeSize * 4;
  9291. }
  9292. for (var i = 0; i < offsetLocations.length; i++) {
  9293. var ai = offsetLocations[i];
  9294. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9295. this._gl.enableVertexAttribArray(ai.index);
  9296. this._vertexAttribArraysEnabled[ai.index] = true;
  9297. }
  9298. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9299. this._gl.vertexAttribDivisor(ai.index, 1);
  9300. this._currentInstanceLocations.push(ai.index);
  9301. this._currentInstanceBuffers.push(instancesBuffer);
  9302. }
  9303. }
  9304. else {
  9305. for (var index = 0; index < 4; index++) {
  9306. var offsetLocation = offsetLocations[index];
  9307. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9308. this._gl.enableVertexAttribArray(offsetLocation);
  9309. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9310. }
  9311. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9312. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9313. this._currentInstanceLocations.push(offsetLocation);
  9314. this._currentInstanceBuffers.push(instancesBuffer);
  9315. }
  9316. }
  9317. };
  9318. Engine.prototype.applyStates = function () {
  9319. this._depthCullingState.apply(this._gl);
  9320. this._stencilState.apply(this._gl);
  9321. this._alphaState.apply(this._gl);
  9322. };
  9323. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9324. // Apply states
  9325. this.applyStates();
  9326. this._drawCalls.addCount(1, false);
  9327. // Render
  9328. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9329. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9330. if (instancesCount) {
  9331. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9332. return;
  9333. }
  9334. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9335. };
  9336. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9337. // Apply states
  9338. this.applyStates();
  9339. this._drawCalls.addCount(1, false);
  9340. if (instancesCount) {
  9341. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9342. return;
  9343. }
  9344. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9345. };
  9346. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9347. // Apply states
  9348. this.applyStates();
  9349. this._drawCalls.addCount(1, false);
  9350. if (instancesCount) {
  9351. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9352. return;
  9353. }
  9354. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9355. };
  9356. // Shaders
  9357. Engine.prototype._releaseEffect = function (effect) {
  9358. if (this._compiledEffects[effect._key]) {
  9359. delete this._compiledEffects[effect._key];
  9360. if (effect.getProgram()) {
  9361. this._gl.deleteProgram(effect.getProgram());
  9362. }
  9363. }
  9364. };
  9365. /**
  9366. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9367. * @param samplers An array of string used to represent textures
  9368. */
  9369. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9370. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9371. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9372. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9373. if (this._compiledEffects[name]) {
  9374. var compiledEffect = this._compiledEffects[name];
  9375. if (onCompiled && compiledEffect.isReady()) {
  9376. onCompiled(compiledEffect);
  9377. }
  9378. return compiledEffect;
  9379. }
  9380. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9381. effect._key = name;
  9382. this._compiledEffects[name] = effect;
  9383. return effect;
  9384. };
  9385. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9386. if (uniformsNames === void 0) { uniformsNames = []; }
  9387. if (samplers === void 0) { samplers = []; }
  9388. if (defines === void 0) { defines = ""; }
  9389. return this.createEffect({
  9390. vertex: "particles",
  9391. fragmentElement: fragmentName
  9392. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9393. };
  9394. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9395. context = context || this._gl;
  9396. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9397. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9398. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9399. var shaderProgram = context.createProgram();
  9400. context.attachShader(shaderProgram, vertexShader);
  9401. context.attachShader(shaderProgram, fragmentShader);
  9402. context.linkProgram(shaderProgram);
  9403. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9404. if (!linked) {
  9405. context.validateProgram(shaderProgram);
  9406. var error = context.getProgramInfoLog(shaderProgram);
  9407. if (error) {
  9408. throw new Error(error);
  9409. }
  9410. }
  9411. context.deleteShader(vertexShader);
  9412. context.deleteShader(fragmentShader);
  9413. return shaderProgram;
  9414. };
  9415. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9416. var results = [];
  9417. for (var index = 0; index < uniformsNames.length; index++) {
  9418. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9419. }
  9420. return results;
  9421. };
  9422. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9423. var results = [];
  9424. for (var index = 0; index < attributesNames.length; index++) {
  9425. try {
  9426. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9427. }
  9428. catch (e) {
  9429. results.push(-1);
  9430. }
  9431. }
  9432. return results;
  9433. };
  9434. Engine.prototype.enableEffect = function (effect) {
  9435. // Use program
  9436. this.setProgram(effect.getProgram());
  9437. this._currentEffect = effect;
  9438. if (effect.onBind) {
  9439. effect.onBind(effect);
  9440. }
  9441. effect.onBindObservable.notifyObservers(effect);
  9442. };
  9443. Engine.prototype.setIntArray = function (uniform, array) {
  9444. if (!uniform)
  9445. return;
  9446. this._gl.uniform1iv(uniform, array);
  9447. };
  9448. Engine.prototype.setIntArray2 = function (uniform, array) {
  9449. if (!uniform || array.length % 2 !== 0)
  9450. return;
  9451. this._gl.uniform2iv(uniform, array);
  9452. };
  9453. Engine.prototype.setIntArray3 = function (uniform, array) {
  9454. if (!uniform || array.length % 3 !== 0)
  9455. return;
  9456. this._gl.uniform3iv(uniform, array);
  9457. };
  9458. Engine.prototype.setIntArray4 = function (uniform, array) {
  9459. if (!uniform || array.length % 4 !== 0)
  9460. return;
  9461. this._gl.uniform4iv(uniform, array);
  9462. };
  9463. Engine.prototype.setFloatArray = function (uniform, array) {
  9464. if (!uniform)
  9465. return;
  9466. this._gl.uniform1fv(uniform, array);
  9467. };
  9468. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9469. if (!uniform || array.length % 2 !== 0)
  9470. return;
  9471. this._gl.uniform2fv(uniform, array);
  9472. };
  9473. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9474. if (!uniform || array.length % 3 !== 0)
  9475. return;
  9476. this._gl.uniform3fv(uniform, array);
  9477. };
  9478. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9479. if (!uniform || array.length % 4 !== 0)
  9480. return;
  9481. this._gl.uniform4fv(uniform, array);
  9482. };
  9483. Engine.prototype.setArray = function (uniform, array) {
  9484. if (!uniform)
  9485. return;
  9486. this._gl.uniform1fv(uniform, array);
  9487. };
  9488. Engine.prototype.setArray2 = function (uniform, array) {
  9489. if (!uniform || array.length % 2 !== 0)
  9490. return;
  9491. this._gl.uniform2fv(uniform, array);
  9492. };
  9493. Engine.prototype.setArray3 = function (uniform, array) {
  9494. if (!uniform || array.length % 3 !== 0)
  9495. return;
  9496. this._gl.uniform3fv(uniform, array);
  9497. };
  9498. Engine.prototype.setArray4 = function (uniform, array) {
  9499. if (!uniform || array.length % 4 !== 0)
  9500. return;
  9501. this._gl.uniform4fv(uniform, array);
  9502. };
  9503. Engine.prototype.setMatrices = function (uniform, matrices) {
  9504. if (!uniform)
  9505. return;
  9506. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9507. };
  9508. Engine.prototype.setMatrix = function (uniform, matrix) {
  9509. if (!uniform)
  9510. return;
  9511. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9512. };
  9513. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9514. if (!uniform)
  9515. return;
  9516. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9517. };
  9518. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9519. if (!uniform)
  9520. return;
  9521. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9522. };
  9523. Engine.prototype.setFloat = function (uniform, value) {
  9524. if (!uniform)
  9525. return;
  9526. this._gl.uniform1f(uniform, value);
  9527. };
  9528. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9529. if (!uniform)
  9530. return;
  9531. this._gl.uniform2f(uniform, x, y);
  9532. };
  9533. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9534. if (!uniform)
  9535. return;
  9536. this._gl.uniform3f(uniform, x, y, z);
  9537. };
  9538. Engine.prototype.setBool = function (uniform, bool) {
  9539. if (!uniform)
  9540. return;
  9541. this._gl.uniform1i(uniform, bool);
  9542. };
  9543. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9544. if (!uniform)
  9545. return;
  9546. this._gl.uniform4f(uniform, x, y, z, w);
  9547. };
  9548. Engine.prototype.setColor3 = function (uniform, color3) {
  9549. if (!uniform)
  9550. return;
  9551. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9552. };
  9553. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9554. if (!uniform)
  9555. return;
  9556. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9557. };
  9558. // States
  9559. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9560. if (zOffset === void 0) { zOffset = 0; }
  9561. if (reverseSide === void 0) { reverseSide = false; }
  9562. // Culling
  9563. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9564. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9565. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9566. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9567. if (culling) {
  9568. this._depthCullingState.cullFace = cullFace;
  9569. this._depthCullingState.cull = true;
  9570. }
  9571. else {
  9572. this._depthCullingState.cull = false;
  9573. }
  9574. }
  9575. // Z offset
  9576. this.setZOffset(zOffset);
  9577. };
  9578. Engine.prototype.setZOffset = function (value) {
  9579. this._depthCullingState.zOffset = value;
  9580. };
  9581. Engine.prototype.getZOffset = function () {
  9582. return this._depthCullingState.zOffset;
  9583. };
  9584. Engine.prototype.setDepthBuffer = function (enable) {
  9585. this._depthCullingState.depthTest = enable;
  9586. };
  9587. Engine.prototype.getDepthWrite = function () {
  9588. return this._depthCullingState.depthMask;
  9589. };
  9590. Engine.prototype.setDepthWrite = function (enable) {
  9591. this._depthCullingState.depthMask = enable;
  9592. };
  9593. Engine.prototype.setColorWrite = function (enable) {
  9594. this._gl.colorMask(enable, enable, enable, enable);
  9595. this._colorWrite = enable;
  9596. };
  9597. Engine.prototype.getColorWrite = function () {
  9598. return this._colorWrite;
  9599. };
  9600. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9601. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9602. };
  9603. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9604. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9605. if (this._alphaMode === mode) {
  9606. return;
  9607. }
  9608. switch (mode) {
  9609. case Engine.ALPHA_DISABLE:
  9610. this._alphaState.alphaBlend = false;
  9611. break;
  9612. case Engine.ALPHA_PREMULTIPLIED:
  9613. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9614. this._alphaState.alphaBlend = true;
  9615. break;
  9616. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9617. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9618. this._alphaState.alphaBlend = true;
  9619. break;
  9620. case Engine.ALPHA_COMBINE:
  9621. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9622. this._alphaState.alphaBlend = true;
  9623. break;
  9624. case Engine.ALPHA_ONEONE:
  9625. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9626. this._alphaState.alphaBlend = true;
  9627. break;
  9628. case Engine.ALPHA_ADD:
  9629. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9630. this._alphaState.alphaBlend = true;
  9631. break;
  9632. case Engine.ALPHA_SUBTRACT:
  9633. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9634. this._alphaState.alphaBlend = true;
  9635. break;
  9636. case Engine.ALPHA_MULTIPLY:
  9637. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9638. this._alphaState.alphaBlend = true;
  9639. break;
  9640. case Engine.ALPHA_MAXIMIZED:
  9641. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9642. this._alphaState.alphaBlend = true;
  9643. break;
  9644. case Engine.ALPHA_INTERPOLATE:
  9645. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9646. this._alphaState.alphaBlend = true;
  9647. break;
  9648. case Engine.ALPHA_SCREENMODE:
  9649. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9650. this._alphaState.alphaBlend = true;
  9651. break;
  9652. }
  9653. if (!noDepthWriteChange) {
  9654. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9655. }
  9656. this._alphaMode = mode;
  9657. };
  9658. Engine.prototype.getAlphaMode = function () {
  9659. return this._alphaMode;
  9660. };
  9661. Engine.prototype.setAlphaTesting = function (enable) {
  9662. this._alphaTest = enable;
  9663. };
  9664. Engine.prototype.getAlphaTesting = function () {
  9665. return !!this._alphaTest;
  9666. };
  9667. // Textures
  9668. Engine.prototype.wipeCaches = function (bruteForce) {
  9669. if (this.preventCacheWipeBetweenFrames) {
  9670. return;
  9671. }
  9672. this.resetTextureCache();
  9673. this._currentEffect = null;
  9674. // 6/8/2017: deltakosh: Should not be required anymore.
  9675. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9676. if (bruteForce) {
  9677. this._currentProgram = null;
  9678. this._stencilState.reset();
  9679. this._depthCullingState.reset();
  9680. this.setDepthFunctionToLessOrEqual();
  9681. this._alphaState.reset();
  9682. }
  9683. this._cachedVertexBuffers = null;
  9684. this._cachedIndexBuffer = null;
  9685. this._cachedEffectForVertexBuffers = null;
  9686. this._unbindVertexArrayObject();
  9687. this.bindIndexBuffer(null);
  9688. this.bindArrayBuffer(null);
  9689. };
  9690. /**
  9691. * Set the compressed texture format to use, based on the formats you have, and the formats
  9692. * supported by the hardware / browser.
  9693. *
  9694. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9695. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9696. * to API arguments needed to compressed textures. This puts the burden on the container
  9697. * generator to house the arcane code for determining these for current & future formats.
  9698. *
  9699. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9700. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9701. *
  9702. * Note: The result of this call is not taken into account when a texture is base64.
  9703. *
  9704. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9705. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9706. *
  9707. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9708. * @returns The extension selected.
  9709. */
  9710. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9711. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9712. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9713. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9714. return this._textureFormatInUse = this._texturesSupported[i];
  9715. }
  9716. }
  9717. }
  9718. // actively set format to nothing, to allow this to be called more than once
  9719. // and possibly fail the 2nd time
  9720. return this._textureFormatInUse = null;
  9721. };
  9722. Engine.prototype._createTexture = function () {
  9723. return this._gl.createTexture();
  9724. };
  9725. /**
  9726. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9727. * @param {string} urlArg- This contains one of the following:
  9728. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9729. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9730. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9731. *
  9732. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9733. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9734. * @param {Scene} scene- Needed for loading to the correct scene.
  9735. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9736. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9737. * @param {callback} onError- Optional callback to be called upon failure.
  9738. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9739. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9740. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9741. *
  9742. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9743. */
  9744. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9745. var _this = this;
  9746. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9747. if (onLoad === void 0) { onLoad = null; }
  9748. if (onError === void 0) { onError = null; }
  9749. if (buffer === void 0) { buffer = null; }
  9750. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9751. var fromData = url.substr(0, 5) === "data:";
  9752. var fromBlob = url.substr(0, 5) === "blob:";
  9753. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9754. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  9755. // establish the file extension, if possible
  9756. var lastDot = url.lastIndexOf('.');
  9757. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9758. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9759. var isTGA = (extension === ".tga");
  9760. // determine if a ktx file should be substituted
  9761. var isKTX = false;
  9762. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9763. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9764. isKTX = true;
  9765. }
  9766. if (scene) {
  9767. scene._addPendingData(texture);
  9768. }
  9769. texture.url = url;
  9770. texture.generateMipMaps = !noMipmap;
  9771. texture.samplingMode = samplingMode;
  9772. texture.invertY = invertY;
  9773. if (!this._doNotHandleContextLost) {
  9774. // Keep a link to the buffer only if we plan to handle context lost
  9775. texture._buffer = buffer;
  9776. }
  9777. if (onLoad) {
  9778. texture.onLoadedObservable.add(onLoad);
  9779. }
  9780. if (!fallBack)
  9781. this._internalTexturesCache.push(texture);
  9782. var onerror = function () {
  9783. if (scene) {
  9784. scene._removePendingData(texture);
  9785. }
  9786. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9787. if (isKTX) {
  9788. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9789. }
  9790. else if (onError) {
  9791. onError();
  9792. }
  9793. };
  9794. var callback;
  9795. // processing for non-image formats
  9796. if (isKTX || isTGA || isDDS) {
  9797. if (isKTX) {
  9798. callback = function (data) {
  9799. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9800. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9801. ktx.uploadLevels(_this._gl, !noMipmap);
  9802. return false;
  9803. }, samplingMode);
  9804. };
  9805. }
  9806. else if (isTGA) {
  9807. callback = function (arrayBuffer) {
  9808. var data = new Uint8Array(arrayBuffer);
  9809. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9810. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9811. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9812. return false;
  9813. }, samplingMode);
  9814. };
  9815. }
  9816. else if (isDDS) {
  9817. callback = function (data) {
  9818. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9819. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9820. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9821. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  9822. return false;
  9823. }, samplingMode);
  9824. };
  9825. }
  9826. if (!buffer) {
  9827. BABYLON.Tools.LoadFile(url, function (data) {
  9828. callback(data);
  9829. }, null, scene ? scene.database : null, true, onerror);
  9830. }
  9831. else {
  9832. callback(buffer);
  9833. }
  9834. // image format processing
  9835. }
  9836. else {
  9837. var onload = function (img) {
  9838. if (fromBlob && !_this._doNotHandleContextLost) {
  9839. // We need to store the image if we need to rebuild the texture
  9840. // in case of a webgl context lost
  9841. texture._buffer = img;
  9842. }
  9843. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  9844. var gl = _this._gl;
  9845. var isPot = (img.width === potWidth && img.height === potHeight);
  9846. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  9847. if (isPot) {
  9848. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9849. return false;
  9850. }
  9851. // Using shaders to rescale because canvas.drawImage is lossy
  9852. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  9853. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  9854. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9855. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9856. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  9857. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9858. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9859. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  9860. _this._releaseTexture(source);
  9861. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9862. continuationCallback();
  9863. });
  9864. return true;
  9865. }, samplingMode);
  9866. };
  9867. if (!fromData || isBase64)
  9868. if (buffer instanceof HTMLImageElement) {
  9869. onload(buffer);
  9870. }
  9871. else {
  9872. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9873. }
  9874. else if (buffer instanceof Array || typeof buffer === "string")
  9875. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  9876. else
  9877. onload(buffer);
  9878. }
  9879. return texture;
  9880. };
  9881. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  9882. var _this = this;
  9883. var rtt = this.createRenderTargetTexture({
  9884. width: destination.width,
  9885. height: destination.height,
  9886. }, {
  9887. generateMipMaps: false,
  9888. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  9889. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  9890. generateDepthBuffer: false,
  9891. generateStencilBuffer: false
  9892. });
  9893. if (!this._rescalePostProcess) {
  9894. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  9895. }
  9896. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  9897. _this._rescalePostProcess.onApply = function (effect) {
  9898. effect._bindTexture("textureSampler", source);
  9899. };
  9900. var hostingScene = scene;
  9901. if (!hostingScene) {
  9902. hostingScene = _this.scenes[_this.scenes.length - 1];
  9903. }
  9904. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  9905. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  9906. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  9907. _this.unBindFramebuffer(rtt);
  9908. _this._releaseTexture(rtt);
  9909. if (onComplete) {
  9910. onComplete();
  9911. }
  9912. });
  9913. };
  9914. Engine.prototype._getInternalFormat = function (format) {
  9915. var internalFormat = this._gl.RGBA;
  9916. switch (format) {
  9917. case Engine.TEXTUREFORMAT_ALPHA:
  9918. internalFormat = this._gl.ALPHA;
  9919. break;
  9920. case Engine.TEXTUREFORMAT_LUMINANCE:
  9921. internalFormat = this._gl.LUMINANCE;
  9922. break;
  9923. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9924. internalFormat = this._gl.LUMINANCE_ALPHA;
  9925. break;
  9926. case Engine.TEXTUREFORMAT_RGB:
  9927. internalFormat = this._gl.RGB;
  9928. break;
  9929. case Engine.TEXTUREFORMAT_RGBA:
  9930. internalFormat = this._gl.RGBA;
  9931. break;
  9932. }
  9933. return internalFormat;
  9934. };
  9935. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9936. if (compression === void 0) { compression = null; }
  9937. var internalFormat = this._getInternalFormat(format);
  9938. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9939. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9940. if (!this._doNotHandleContextLost) {
  9941. texture._bufferView = data;
  9942. texture.format = format;
  9943. texture.invertY = invertY;
  9944. texture._compression = compression;
  9945. }
  9946. if (texture.width % 4 !== 0) {
  9947. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9948. }
  9949. if (compression) {
  9950. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  9951. }
  9952. else {
  9953. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9954. }
  9955. if (texture.generateMipMaps) {
  9956. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9957. }
  9958. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9959. this.resetTextureCache();
  9960. texture.isReady = true;
  9961. };
  9962. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9963. if (compression === void 0) { compression = null; }
  9964. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  9965. texture.baseWidth = width;
  9966. texture.baseHeight = height;
  9967. texture.width = width;
  9968. texture.height = height;
  9969. texture.format = format;
  9970. texture.generateMipMaps = generateMipMaps;
  9971. texture.samplingMode = samplingMode;
  9972. texture.invertY = invertY;
  9973. texture._compression = compression;
  9974. if (!this._doNotHandleContextLost) {
  9975. texture._bufferView = data;
  9976. }
  9977. this.updateRawTexture(texture, data, format, invertY, compression);
  9978. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9979. // Filters
  9980. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9981. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9982. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9983. if (generateMipMaps) {
  9984. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9985. }
  9986. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9987. this._internalTexturesCache.push(texture);
  9988. return texture;
  9989. };
  9990. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9991. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  9992. texture.baseWidth = width;
  9993. texture.baseHeight = height;
  9994. if (generateMipMaps) {
  9995. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  9996. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  9997. }
  9998. this.resetTextureCache();
  9999. texture.width = width;
  10000. texture.height = height;
  10001. texture.isReady = false;
  10002. texture.generateMipMaps = generateMipMaps;
  10003. texture.samplingMode = samplingMode;
  10004. this.updateTextureSamplingMode(samplingMode, texture);
  10005. this._internalTexturesCache.push(texture);
  10006. return texture;
  10007. };
  10008. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10009. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10010. if (texture.isCube) {
  10011. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10012. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10013. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10014. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10015. }
  10016. else {
  10017. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10018. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10019. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10020. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10021. }
  10022. texture.samplingMode = samplingMode;
  10023. };
  10024. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10025. if (premulAlpha === void 0) { premulAlpha = false; }
  10026. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10027. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10028. if (premulAlpha) {
  10029. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10030. }
  10031. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10032. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10033. if (texture.generateMipMaps) {
  10034. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10035. }
  10036. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10037. if (premulAlpha) {
  10038. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10039. }
  10040. this.resetTextureCache();
  10041. texture.isReady = true;
  10042. };
  10043. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10044. if (texture._isDisabled) {
  10045. return;
  10046. }
  10047. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10048. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10049. try {
  10050. // Testing video texture support
  10051. if (this._videoTextureSupported === undefined) {
  10052. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10053. if (this._gl.getError() !== 0) {
  10054. this._videoTextureSupported = false;
  10055. }
  10056. else {
  10057. this._videoTextureSupported = true;
  10058. }
  10059. }
  10060. // Copy video through the current working canvas if video texture is not supported
  10061. if (!this._videoTextureSupported) {
  10062. if (!texture._workingCanvas) {
  10063. texture._workingCanvas = document.createElement("canvas");
  10064. texture._workingContext = texture._workingCanvas.getContext("2d");
  10065. texture._workingCanvas.width = texture.width;
  10066. texture._workingCanvas.height = texture.height;
  10067. }
  10068. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10069. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10070. }
  10071. else {
  10072. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10073. }
  10074. if (texture.generateMipMaps) {
  10075. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10076. }
  10077. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10078. this.resetTextureCache();
  10079. texture.isReady = true;
  10080. }
  10081. catch (ex) {
  10082. // Something unexpected
  10083. // Let's disable the texture
  10084. texture._isDisabled = true;
  10085. }
  10086. };
  10087. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10088. var fullOptions = new RenderTargetCreationOptions();
  10089. if (options !== undefined && typeof options === "object") {
  10090. fullOptions.generateMipMaps = options.generateMipMaps;
  10091. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10092. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10093. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10094. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10095. }
  10096. else {
  10097. fullOptions.generateMipMaps = options;
  10098. fullOptions.generateDepthBuffer = true;
  10099. fullOptions.generateStencilBuffer = false;
  10100. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10101. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10102. }
  10103. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10104. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10105. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10106. }
  10107. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10108. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10109. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10110. }
  10111. var gl = this._gl;
  10112. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10113. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10114. var width = size.width || size;
  10115. var height = size.height || size;
  10116. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  10117. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10118. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10119. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10120. }
  10121. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10122. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10123. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10124. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10125. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10126. // Create the framebuffer
  10127. var framebuffer = gl.createFramebuffer();
  10128. this.bindUnboundFramebuffer(framebuffer);
  10129. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10130. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, width, height);
  10131. if (fullOptions.generateMipMaps) {
  10132. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10133. }
  10134. // Unbind
  10135. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10136. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10137. this.bindUnboundFramebuffer(null);
  10138. texture._framebuffer = framebuffer;
  10139. texture.baseWidth = width;
  10140. texture.baseHeight = height;
  10141. texture.width = width;
  10142. texture.height = height;
  10143. texture.isReady = true;
  10144. texture.samples = 1;
  10145. texture.generateMipMaps = fullOptions.generateMipMaps;
  10146. texture.samplingMode = fullOptions.samplingMode;
  10147. texture.type = fullOptions.type;
  10148. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10149. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  10150. this.resetTextureCache();
  10151. this._internalTexturesCache.push(texture);
  10152. return texture;
  10153. };
  10154. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10155. var generateMipMaps = false;
  10156. var generateDepthBuffer = true;
  10157. var generateStencilBuffer = false;
  10158. var generateDepthTexture = false;
  10159. var textureCount = 1;
  10160. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10161. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10162. var types = [], samplingModes = [];
  10163. if (options !== undefined) {
  10164. generateMipMaps = options.generateMipMaps;
  10165. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10166. generateStencilBuffer = options.generateStencilBuffer;
  10167. generateDepthTexture = options.generateDepthTexture;
  10168. textureCount = options.textureCount || 1;
  10169. if (options.types) {
  10170. types = options.types;
  10171. }
  10172. if (options.samplingModes) {
  10173. samplingModes = options.samplingModes;
  10174. }
  10175. }
  10176. var gl = this._gl;
  10177. // Create the framebuffer
  10178. var framebuffer = gl.createFramebuffer();
  10179. this.bindUnboundFramebuffer(framebuffer);
  10180. var width = size.width || size;
  10181. var height = size.height || size;
  10182. var textures = [];
  10183. var attachments = [];
  10184. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10185. for (var i = 0; i < textureCount; i++) {
  10186. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10187. var type = types[i] || defaultType;
  10188. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10189. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10190. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10191. }
  10192. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10193. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10194. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10195. }
  10196. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10197. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10198. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10199. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10200. }
  10201. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10202. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10203. textures.push(texture);
  10204. attachments.push(attachment);
  10205. gl.activeTexture(gl["TEXTURE" + i]);
  10206. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10207. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10208. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10209. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10210. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10211. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10212. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10213. if (generateMipMaps) {
  10214. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10215. }
  10216. // Unbind
  10217. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10218. texture._framebuffer = framebuffer;
  10219. texture._depthStencilBuffer = depthStencilBuffer;
  10220. texture.baseWidth = width;
  10221. texture.baseHeight = height;
  10222. texture.width = width;
  10223. texture.height = height;
  10224. texture.isReady = true;
  10225. texture.samples = 1;
  10226. texture.generateMipMaps = generateMipMaps;
  10227. texture.samplingMode = samplingMode;
  10228. texture.type = type;
  10229. texture._generateDepthBuffer = generateDepthBuffer;
  10230. texture._generateStencilBuffer = generateStencilBuffer;
  10231. this._internalTexturesCache.push(texture);
  10232. }
  10233. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10234. // Depth texture
  10235. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10236. gl.activeTexture(gl.TEXTURE0);
  10237. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10238. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10239. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10240. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10241. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10242. 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);
  10243. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10244. depthTexture._framebuffer = framebuffer;
  10245. depthTexture.baseWidth = width;
  10246. depthTexture.baseHeight = height;
  10247. depthTexture.width = width;
  10248. depthTexture.height = height;
  10249. depthTexture.isReady = true;
  10250. depthTexture.samples = 1;
  10251. depthTexture.generateMipMaps = generateMipMaps;
  10252. depthTexture.samplingMode = gl.NEAREST;
  10253. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10254. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10255. textures.push(depthTexture);
  10256. this._internalTexturesCache.push(depthTexture);
  10257. }
  10258. gl.drawBuffers(attachments);
  10259. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10260. this.bindUnboundFramebuffer(null);
  10261. this.resetTextureCache();
  10262. return textures;
  10263. };
  10264. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10265. if (samples === void 0) { samples = 1; }
  10266. var depthStencilBuffer = null;
  10267. var gl = this._gl;
  10268. // Create the depth/stencil buffer
  10269. if (generateStencilBuffer) {
  10270. depthStencilBuffer = gl.createRenderbuffer();
  10271. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10272. if (samples > 1) {
  10273. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10274. }
  10275. else {
  10276. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10277. }
  10278. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10279. }
  10280. else if (generateDepthBuffer) {
  10281. depthStencilBuffer = gl.createRenderbuffer();
  10282. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10283. if (samples > 1) {
  10284. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10285. }
  10286. else {
  10287. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10288. }
  10289. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10290. }
  10291. return depthStencilBuffer;
  10292. };
  10293. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10294. if (this.webGLVersion < 2) {
  10295. return 1;
  10296. }
  10297. if (texture.samples === samples) {
  10298. return samples;
  10299. }
  10300. var gl = this._gl;
  10301. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10302. // Dispose previous render buffers
  10303. if (texture._depthStencilBuffer) {
  10304. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10305. }
  10306. if (texture._MSAAFramebuffer) {
  10307. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10308. }
  10309. if (texture._MSAARenderBuffer) {
  10310. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10311. }
  10312. if (samples > 1) {
  10313. texture._MSAAFramebuffer = gl.createFramebuffer();
  10314. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10315. var colorRenderbuffer = gl.createRenderbuffer();
  10316. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10317. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10318. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10319. texture._MSAARenderBuffer = colorRenderbuffer;
  10320. }
  10321. else {
  10322. this.bindUnboundFramebuffer(texture._framebuffer);
  10323. }
  10324. texture.samples = samples;
  10325. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10326. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10327. this.bindUnboundFramebuffer(null);
  10328. return samples;
  10329. };
  10330. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10331. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10332. };
  10333. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10334. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10335. };
  10336. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10337. var gl = this._gl;
  10338. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10339. var generateMipMaps = true;
  10340. var generateDepthBuffer = true;
  10341. var generateStencilBuffer = false;
  10342. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10343. if (options !== undefined) {
  10344. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10345. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10346. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  10347. if (options.samplingMode !== undefined) {
  10348. samplingMode = options.samplingMode;
  10349. }
  10350. }
  10351. texture.isCube = true;
  10352. texture.generateMipMaps = generateMipMaps;
  10353. texture.samples = 1;
  10354. texture.samplingMode = samplingMode;
  10355. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10356. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10357. for (var face = 0; face < 6; face++) {
  10358. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10359. }
  10360. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10361. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10362. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10363. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10364. // Create the framebuffer
  10365. var framebuffer = gl.createFramebuffer();
  10366. this.bindUnboundFramebuffer(framebuffer);
  10367. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10368. // Mipmaps
  10369. if (texture.generateMipMaps) {
  10370. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10371. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10372. }
  10373. // Unbind
  10374. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10375. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10376. this.bindUnboundFramebuffer(null);
  10377. texture._framebuffer = framebuffer;
  10378. texture.width = size;
  10379. texture.height = size;
  10380. texture.isReady = true;
  10381. this.resetTextureCache();
  10382. this._internalTexturesCache.push(texture);
  10383. return texture;
  10384. };
  10385. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10386. var _this = this;
  10387. if (onError === void 0) { onError = null; }
  10388. if (forcedExtension === void 0) { forcedExtension = null; }
  10389. var callback = function (loadData) {
  10390. if (!loadData) {
  10391. if (onLoad) {
  10392. onLoad(null);
  10393. }
  10394. return;
  10395. }
  10396. var texture = loadData.texture;
  10397. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10398. texture._lodGenerationScale = scale;
  10399. texture._lodGenerationOffset = offset;
  10400. if (_this._caps.textureLOD) {
  10401. // Do not add extra process if texture lod is supported.
  10402. if (onLoad) {
  10403. onLoad(texture);
  10404. }
  10405. return;
  10406. }
  10407. var mipSlices = 3;
  10408. var gl = _this._gl;
  10409. var width = loadData.width;
  10410. if (!width) {
  10411. return;
  10412. }
  10413. var textures = [];
  10414. for (var i = 0; i < mipSlices; i++) {
  10415. //compute LOD from even spacing in smoothness (matching shader calculation)
  10416. var smoothness = i / (mipSlices - 1);
  10417. var roughness = 1 - smoothness;
  10418. var minLODIndex = offset; // roughness = 0
  10419. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10420. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10421. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10422. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10423. glTextureFromLod.isCube = true;
  10424. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10425. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10426. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10427. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10428. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10429. if (loadData.isDDS) {
  10430. var info = loadData.info;
  10431. var data = loadData.data;
  10432. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10433. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10434. }
  10435. else {
  10436. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10437. }
  10438. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10439. // Wrap in a base texture for easy binding.
  10440. var lodTexture = new BABYLON.BaseTexture(scene);
  10441. lodTexture.isCube = true;
  10442. lodTexture._texture = glTextureFromLod;
  10443. glTextureFromLod.isReady = true;
  10444. textures.push(lodTexture);
  10445. }
  10446. texture._lodTextureHigh = textures[2];
  10447. texture._lodTextureMid = textures[1];
  10448. texture._lodTextureLow = textures[0];
  10449. if (onLoad) {
  10450. onLoad(texture);
  10451. }
  10452. };
  10453. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10454. };
  10455. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10456. var _this = this;
  10457. if (onLoad === void 0) { onLoad = null; }
  10458. if (onError === void 0) { onError = null; }
  10459. if (forcedExtension === void 0) { forcedExtension = null; }
  10460. var gl = this._gl;
  10461. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10462. texture.isCube = true;
  10463. texture.url = rootUrl;
  10464. texture.generateMipMaps = !noMipmap;
  10465. if (!this._doNotHandleContextLost) {
  10466. texture._extension = forcedExtension;
  10467. texture._files = files;
  10468. }
  10469. var isKTX = false;
  10470. var isDDS = false;
  10471. var lastDot = rootUrl.lastIndexOf('.');
  10472. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  10473. if (this._textureFormatInUse) {
  10474. extension = this._textureFormatInUse;
  10475. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10476. isKTX = true;
  10477. }
  10478. else {
  10479. isDDS = (extension === ".dds");
  10480. }
  10481. if (isKTX) {
  10482. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10483. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10484. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10485. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10486. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10487. ktx.uploadLevels(_this._gl, !noMipmap);
  10488. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10489. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10490. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10491. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10492. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10493. _this.resetTextureCache();
  10494. texture.width = ktx.pixelWidth;
  10495. texture.height = ktx.pixelHeight;
  10496. texture.isReady = true;
  10497. }, null, null, true, onError);
  10498. }
  10499. else if (isDDS) {
  10500. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10501. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10502. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10503. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10504. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10505. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10506. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10507. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10508. }
  10509. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10510. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10511. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10512. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10513. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10514. _this.resetTextureCache();
  10515. texture.width = info.width;
  10516. texture.height = info.height;
  10517. texture.isReady = true;
  10518. texture.type = info.textureType;
  10519. if (onLoad) {
  10520. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10521. }
  10522. }, null, null, true, onError);
  10523. }
  10524. else {
  10525. cascadeLoad(rootUrl, scene, function (imgs) {
  10526. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10527. var height = width;
  10528. _this._prepareWorkingCanvas();
  10529. _this._workingCanvas.width = width;
  10530. _this._workingCanvas.height = height;
  10531. var faces = [
  10532. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10533. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10534. ];
  10535. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10536. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10537. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10538. for (var index = 0; index < faces.length; index++) {
  10539. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10540. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10541. }
  10542. if (!noMipmap) {
  10543. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10544. }
  10545. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10546. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10547. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10548. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10549. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10550. _this.resetTextureCache();
  10551. texture.width = width;
  10552. texture.height = height;
  10553. texture.isReady = true;
  10554. texture.format = format;
  10555. texture.onLoadedObservable.notifyObservers(texture);
  10556. texture.onLoadedObservable.clear();
  10557. if (onLoad) {
  10558. onLoad();
  10559. }
  10560. }, files, onError);
  10561. }
  10562. this._internalTexturesCache.push(texture);
  10563. return texture;
  10564. };
  10565. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10566. if (compression === void 0) { compression = null; }
  10567. if (level === void 0) { level = 0; }
  10568. texture._bufferViewArray = data;
  10569. texture.format = format;
  10570. texture.type = type;
  10571. texture.invertY = invertY;
  10572. texture._compression = compression;
  10573. var gl = this._gl;
  10574. var textureType = this._getWebGLTextureType(type);
  10575. var internalFormat = this._getInternalFormat(format);
  10576. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10577. var needConversion = false;
  10578. if (internalFormat === gl.RGB) {
  10579. internalFormat = gl.RGBA;
  10580. needConversion = true;
  10581. }
  10582. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10583. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10584. if (texture.width % 4 !== 0) {
  10585. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  10586. }
  10587. // Data are known to be in +X +Y +Z -X -Y -Z
  10588. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10589. var faceData = data[faceIndex];
  10590. if (compression) {
  10591. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, faceData);
  10592. }
  10593. else {
  10594. if (needConversion) {
  10595. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  10596. }
  10597. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  10598. }
  10599. }
  10600. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10601. if (isPot && texture.generateMipMaps && level === 0) {
  10602. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10603. }
  10604. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10605. this.resetTextureCache();
  10606. texture.isReady = true;
  10607. };
  10608. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  10609. if (compression === void 0) { compression = null; }
  10610. var gl = this._gl;
  10611. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  10612. texture.isCube = true;
  10613. texture.generateMipMaps = generateMipMaps;
  10614. texture.format = format;
  10615. texture.type = type;
  10616. if (!this._doNotHandleContextLost) {
  10617. texture._bufferViewArray = data;
  10618. }
  10619. var textureType = this._getWebGLTextureType(type);
  10620. var internalFormat = this._getInternalFormat(format);
  10621. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10622. var needConversion = false;
  10623. if (internalFormat === gl.RGB) {
  10624. internalFormat = gl.RGBA;
  10625. needConversion = true;
  10626. }
  10627. var width = size;
  10628. var height = width;
  10629. texture.width = width;
  10630. texture.height = height;
  10631. // Double check on POT to generate Mips.
  10632. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10633. if (!isPot) {
  10634. generateMipMaps = false;
  10635. }
  10636. // Upload data if needed. The texture won't be ready until then.
  10637. if (data) {
  10638. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  10639. }
  10640. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10641. // Filters
  10642. if (data && generateMipMaps) {
  10643. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10644. }
  10645. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  10646. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10647. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10648. }
  10649. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  10650. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10651. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10652. }
  10653. else {
  10654. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10655. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10656. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10657. }
  10658. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10659. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10660. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10661. return texture;
  10662. };
  10663. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  10664. var _this = this;
  10665. if (onLoad === void 0) { onLoad = null; }
  10666. if (onError === void 0) { onError = null; }
  10667. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10668. if (invertY === void 0) { invertY = false; }
  10669. var gl = this._gl;
  10670. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  10671. scene._addPendingData(texture);
  10672. texture.url = url;
  10673. this._internalTexturesCache.push(texture);
  10674. var onerror = function () {
  10675. scene._removePendingData(texture);
  10676. if (onError) {
  10677. onError();
  10678. }
  10679. };
  10680. var internalCallback = function (data) {
  10681. var width = texture.width;
  10682. var height = texture.height;
  10683. var faceDataArrays = callback(data);
  10684. if (mipmmapGenerator) {
  10685. var textureType = _this._getWebGLTextureType(type);
  10686. var internalFormat = _this._getInternalFormat(format);
  10687. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  10688. var needConversion = false;
  10689. if (internalFormat === gl.RGB) {
  10690. internalFormat = gl.RGBA;
  10691. needConversion = true;
  10692. }
  10693. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10694. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10695. var mipData = mipmmapGenerator(faceDataArrays);
  10696. for (var level = 0; level < mipData.length; level++) {
  10697. var mipSize = width >> level;
  10698. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10699. var mipFaceData = mipData[level][faceIndex];
  10700. if (needConversion) {
  10701. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10702. }
  10703. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10704. }
  10705. }
  10706. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10707. }
  10708. else {
  10709. texture.generateMipMaps = !noMipmap;
  10710. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  10711. }
  10712. texture.isReady = true;
  10713. _this.resetTextureCache();
  10714. scene._removePendingData(texture);
  10715. if (onLoad) {
  10716. onLoad();
  10717. }
  10718. };
  10719. BABYLON.Tools.LoadFile(url, function (data) {
  10720. internalCallback(data);
  10721. }, onerror, scene.database, true);
  10722. return texture;
  10723. };
  10724. ;
  10725. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  10726. var gl = this._gl;
  10727. if (!gl) {
  10728. return;
  10729. }
  10730. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  10731. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10732. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10733. if (!noMipmap && !isCompressed) {
  10734. gl.generateMipmap(gl.TEXTURE_2D);
  10735. }
  10736. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10737. this.resetTextureCache();
  10738. if (scene) {
  10739. scene._removePendingData(texture);
  10740. }
  10741. texture.onLoadedObservable.notifyObservers(texture);
  10742. texture.onLoadedObservable.clear();
  10743. };
  10744. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  10745. var _this = this;
  10746. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10747. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  10748. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  10749. var gl = this._gl;
  10750. if (!gl) {
  10751. return;
  10752. }
  10753. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10754. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10755. texture.baseWidth = width;
  10756. texture.baseHeight = height;
  10757. texture.width = potWidth;
  10758. texture.height = potHeight;
  10759. texture.isReady = true;
  10760. if (processFunction(potWidth, potHeight, function () {
  10761. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10762. })) {
  10763. // Returning as texture needs extra async steps
  10764. return;
  10765. }
  10766. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10767. };
  10768. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10769. // Create new RGBA data container.
  10770. var rgbaData;
  10771. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10772. rgbaData = new Float32Array(width * height * 4);
  10773. }
  10774. else {
  10775. rgbaData = new Uint32Array(width * height * 4);
  10776. }
  10777. // Convert each pixel.
  10778. for (var x = 0; x < width; x++) {
  10779. for (var y = 0; y < height; y++) {
  10780. var index = (y * width + x) * 3;
  10781. var newIndex = (y * width + x) * 4;
  10782. // Map Old Value to new value.
  10783. rgbaData[newIndex + 0] = rgbData[index + 0];
  10784. rgbaData[newIndex + 1] = rgbData[index + 1];
  10785. rgbaData[newIndex + 2] = rgbData[index + 2];
  10786. // Add fully opaque alpha channel.
  10787. rgbaData[newIndex + 3] = 1;
  10788. }
  10789. }
  10790. return rgbaData;
  10791. };
  10792. Engine.prototype._releaseFramebufferObjects = function (texture) {
  10793. var gl = this._gl;
  10794. if (texture._framebuffer) {
  10795. gl.deleteFramebuffer(texture._framebuffer);
  10796. texture._framebuffer = null;
  10797. }
  10798. if (texture._depthStencilBuffer) {
  10799. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10800. texture._depthStencilBuffer = null;
  10801. }
  10802. if (texture._MSAAFramebuffer) {
  10803. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10804. texture._MSAAFramebuffer = null;
  10805. }
  10806. if (texture._MSAARenderBuffer) {
  10807. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10808. texture._MSAARenderBuffer = null;
  10809. }
  10810. };
  10811. Engine.prototype._releaseTexture = function (texture) {
  10812. var gl = this._gl;
  10813. this._releaseFramebufferObjects(texture);
  10814. gl.deleteTexture(texture._webGLTexture);
  10815. // Unbind channels
  10816. this.unbindAllTextures();
  10817. var index = this._internalTexturesCache.indexOf(texture);
  10818. if (index !== -1) {
  10819. this._internalTexturesCache.splice(index, 1);
  10820. }
  10821. // Integrated fixed lod samplers.
  10822. if (texture._lodTextureHigh) {
  10823. texture._lodTextureHigh.dispose();
  10824. }
  10825. if (texture._lodTextureMid) {
  10826. texture._lodTextureMid.dispose();
  10827. }
  10828. if (texture._lodTextureLow) {
  10829. texture._lodTextureLow.dispose();
  10830. }
  10831. };
  10832. Engine.prototype.setProgram = function (program) {
  10833. if (this._currentProgram !== program) {
  10834. this._gl.useProgram(program);
  10835. this._currentProgram = program;
  10836. }
  10837. };
  10838. Engine.prototype.bindSamplers = function (effect) {
  10839. this.setProgram(effect.getProgram());
  10840. var samplers = effect.getSamplers();
  10841. for (var index = 0; index < samplers.length; index++) {
  10842. var uniform = effect.getUniform(samplers[index]);
  10843. this._gl.uniform1i(uniform, index);
  10844. }
  10845. this._currentEffect = null;
  10846. };
  10847. Engine.prototype.activateTexture = function (texture) {
  10848. if (this._activeTexture !== texture) {
  10849. this._gl.activeTexture(texture);
  10850. this._activeTexture = texture;
  10851. }
  10852. };
  10853. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10854. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10855. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  10856. this._activeTexturesCache[this._activeTexture] = texture;
  10857. }
  10858. };
  10859. Engine.prototype._bindTexture = function (channel, texture) {
  10860. if (channel < 0) {
  10861. return;
  10862. }
  10863. this.activateTexture(this._gl.TEXTURE0 + channel);
  10864. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10865. };
  10866. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10867. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10868. };
  10869. Engine.prototype.unbindAllTextures = function () {
  10870. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10871. this.activateTexture(this._gl["TEXTURE" + channel]);
  10872. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10873. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10874. }
  10875. };
  10876. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10877. if (channel < 0) {
  10878. return;
  10879. }
  10880. this._gl.uniform1i(uniform, channel);
  10881. this._setTexture(channel, texture);
  10882. };
  10883. Engine.prototype._setTexture = function (channel, texture) {
  10884. // Not ready?
  10885. if (!texture) {
  10886. if (this._activeTexturesCache[channel] != null) {
  10887. this.activateTexture(this._gl["TEXTURE" + channel]);
  10888. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10889. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10890. }
  10891. return;
  10892. }
  10893. // Video
  10894. var alreadyActivated = false;
  10895. if (texture.video) {
  10896. this.activateTexture(this._gl["TEXTURE" + channel]);
  10897. alreadyActivated = true;
  10898. texture.update();
  10899. }
  10900. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10901. texture.delayLoad();
  10902. return;
  10903. }
  10904. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10905. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10906. if (this._activeTexturesCache[channel] === internalTexture) {
  10907. return;
  10908. }
  10909. if (!alreadyActivated) {
  10910. this.activateTexture(this._gl["TEXTURE" + channel]);
  10911. }
  10912. if (internalTexture.isCube) {
  10913. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10914. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10915. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10916. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10917. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10918. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10919. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10920. }
  10921. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10922. }
  10923. else {
  10924. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10925. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10926. internalTexture._cachedWrapU = texture.wrapU;
  10927. switch (texture.wrapU) {
  10928. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10929. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10930. break;
  10931. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10932. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10933. break;
  10934. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10935. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10936. break;
  10937. }
  10938. }
  10939. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10940. internalTexture._cachedWrapV = texture.wrapV;
  10941. switch (texture.wrapV) {
  10942. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10943. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10944. break;
  10945. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10946. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10947. break;
  10948. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10949. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10950. break;
  10951. }
  10952. }
  10953. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10954. }
  10955. };
  10956. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10957. if (channel < 0) {
  10958. return;
  10959. }
  10960. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10961. this._textureUnits = new Int32Array(textures.length);
  10962. }
  10963. for (var i = 0; i < textures.length; i++) {
  10964. this._textureUnits[i] = channel + i;
  10965. }
  10966. this._gl.uniform1iv(uniform, this._textureUnits);
  10967. for (var index = 0; index < textures.length; index++) {
  10968. this._setTexture(channel + index, textures[index]);
  10969. }
  10970. };
  10971. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10972. var internalTexture = texture.getInternalTexture();
  10973. if (!internalTexture) {
  10974. return;
  10975. }
  10976. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10977. var value = texture.anisotropicFilteringLevel;
  10978. if (internalTexture.samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10979. value = 1;
  10980. }
  10981. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  10982. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10983. internalTexture._cachedAnisotropicFilteringLevel = value;
  10984. }
  10985. };
  10986. Engine.prototype.readPixels = function (x, y, width, height) {
  10987. var data = new Uint8Array(height * width * 4);
  10988. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10989. return data;
  10990. };
  10991. /**
  10992. * Add an externaly attached data from its key.
  10993. * This method call will fail and return false, if such key already exists.
  10994. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10995. * @param key the unique key that identifies the data
  10996. * @param data the data object to associate to the key for this Engine instance
  10997. * @return true if no such key were already present and the data was added successfully, false otherwise
  10998. */
  10999. Engine.prototype.addExternalData = function (key, data) {
  11000. if (!this._externalData) {
  11001. this._externalData = new BABYLON.StringDictionary();
  11002. }
  11003. return this._externalData.add(key, data);
  11004. };
  11005. /**
  11006. * Get an externaly attached data from its key
  11007. * @param key the unique key that identifies the data
  11008. * @return the associated data, if present (can be null), or undefined if not present
  11009. */
  11010. Engine.prototype.getExternalData = function (key) {
  11011. if (!this._externalData) {
  11012. this._externalData = new BABYLON.StringDictionary();
  11013. }
  11014. return this._externalData.get(key);
  11015. };
  11016. /**
  11017. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11018. * @param key the unique key that identifies the data
  11019. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11020. * @return the associated data, can be null if the factory returned null.
  11021. */
  11022. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11023. if (!this._externalData) {
  11024. this._externalData = new BABYLON.StringDictionary();
  11025. }
  11026. return this._externalData.getOrAddWithFactory(key, factory);
  11027. };
  11028. /**
  11029. * Remove an externaly attached data from the Engine instance
  11030. * @param key the unique key that identifies the data
  11031. * @return true if the data was successfully removed, false if it doesn't exist
  11032. */
  11033. Engine.prototype.removeExternalData = function (key) {
  11034. if (!this._externalData) {
  11035. this._externalData = new BABYLON.StringDictionary();
  11036. }
  11037. return this._externalData.remove(key);
  11038. };
  11039. Engine.prototype.unbindAllAttributes = function () {
  11040. if (this._mustWipeVertexAttributes) {
  11041. this._mustWipeVertexAttributes = false;
  11042. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11043. this._gl.disableVertexAttribArray(i);
  11044. this._vertexAttribArraysEnabled[i] = false;
  11045. this._currentBufferPointers[i].active = false;
  11046. }
  11047. return;
  11048. }
  11049. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11050. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11051. continue;
  11052. }
  11053. this._gl.disableVertexAttribArray(i);
  11054. this._vertexAttribArraysEnabled[i] = false;
  11055. this._currentBufferPointers[i].active = false;
  11056. }
  11057. };
  11058. Engine.prototype.releaseEffects = function () {
  11059. for (var name in this._compiledEffects) {
  11060. this._gl.deleteProgram(this._compiledEffects[name]._program);
  11061. }
  11062. this._compiledEffects = {};
  11063. };
  11064. // Dispose
  11065. Engine.prototype.dispose = function () {
  11066. this.hideLoadingUI();
  11067. this.stopRenderLoop();
  11068. // Release postProcesses
  11069. while (this.postProcesses.length) {
  11070. this.postProcesses[0].dispose();
  11071. }
  11072. // Empty texture
  11073. if (this._emptyTexture) {
  11074. this._releaseTexture(this._emptyTexture);
  11075. this._emptyTexture = null;
  11076. }
  11077. if (this._emptyCubeTexture) {
  11078. this._releaseTexture(this._emptyCubeTexture);
  11079. this._emptyCubeTexture = null;
  11080. }
  11081. // Rescale PP
  11082. if (this._rescalePostProcess) {
  11083. this._rescalePostProcess.dispose();
  11084. }
  11085. // Release scenes
  11086. while (this.scenes.length) {
  11087. this.scenes[0].dispose();
  11088. }
  11089. // Release audio engine
  11090. if (Engine.audioEngine) {
  11091. Engine.audioEngine.dispose();
  11092. }
  11093. // Release effects
  11094. this.releaseEffects();
  11095. // Unbind
  11096. this.unbindAllAttributes();
  11097. if (this._dummyFramebuffer) {
  11098. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11099. }
  11100. this._gl = null;
  11101. //WebVR
  11102. this.disableVR();
  11103. // Events
  11104. window.removeEventListener("blur", this._onBlur);
  11105. window.removeEventListener("focus", this._onFocus);
  11106. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11107. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11108. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11109. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11110. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11111. if (!this._doNotHandleContextLost) {
  11112. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11113. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11114. }
  11115. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11116. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11117. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11118. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11119. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11120. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11121. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11122. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11123. // Remove from Instances
  11124. var index = Engine.Instances.indexOf(this);
  11125. if (index >= 0) {
  11126. Engine.Instances.splice(index, 1);
  11127. }
  11128. this._workingCanvas = null;
  11129. this._workingContext = null;
  11130. this._currentBufferPointers = null;
  11131. this._renderingCanvas = null;
  11132. this._currentProgram = null;
  11133. this.onResizeObservable.clear();
  11134. this.onCanvasBlurObservable.clear();
  11135. this.onCanvasFocusObservable.clear();
  11136. this.onCanvasPointerOutObservable.clear();
  11137. BABYLON.Effect.ResetCache();
  11138. };
  11139. // Loading screen
  11140. Engine.prototype.displayLoadingUI = function () {
  11141. var loadingScreen = this.loadingScreen;
  11142. if (loadingScreen) {
  11143. loadingScreen.displayLoadingUI();
  11144. }
  11145. };
  11146. Engine.prototype.hideLoadingUI = function () {
  11147. var loadingScreen = this.loadingScreen;
  11148. if (loadingScreen) {
  11149. loadingScreen.hideLoadingUI();
  11150. }
  11151. };
  11152. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11153. get: function () {
  11154. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  11155. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11156. return this._loadingScreen;
  11157. },
  11158. set: function (loadingScreen) {
  11159. this._loadingScreen = loadingScreen;
  11160. },
  11161. enumerable: true,
  11162. configurable: true
  11163. });
  11164. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11165. set: function (text) {
  11166. this.loadingScreen.loadingUIText = text;
  11167. },
  11168. enumerable: true,
  11169. configurable: true
  11170. });
  11171. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11172. set: function (color) {
  11173. this.loadingScreen.loadingUIBackgroundColor = color;
  11174. },
  11175. enumerable: true,
  11176. configurable: true
  11177. });
  11178. Engine.prototype.attachContextLostEvent = function (callback) {
  11179. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11180. };
  11181. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11182. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11183. };
  11184. Engine.prototype.getVertexShaderSource = function (program) {
  11185. var shaders = this._gl.getAttachedShaders(program);
  11186. return this._gl.getShaderSource(shaders[0]);
  11187. };
  11188. Engine.prototype.getFragmentShaderSource = function (program) {
  11189. var shaders = this._gl.getAttachedShaders(program);
  11190. return this._gl.getShaderSource(shaders[1]);
  11191. };
  11192. Engine.prototype.getError = function () {
  11193. return this._gl.getError();
  11194. };
  11195. // FPS
  11196. Engine.prototype.getFps = function () {
  11197. return this._fps;
  11198. };
  11199. Engine.prototype.getDeltaTime = function () {
  11200. return this._deltaTime;
  11201. };
  11202. Engine.prototype._measureFps = function () {
  11203. this._performanceMonitor.sampleFrame();
  11204. this._fps = this._performanceMonitor.averageFPS;
  11205. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11206. };
  11207. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11208. if (faceIndex === void 0) { faceIndex = -1; }
  11209. var gl = this._gl;
  11210. if (!this._dummyFramebuffer) {
  11211. this._dummyFramebuffer = gl.createFramebuffer();
  11212. }
  11213. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11214. if (faceIndex > -1) {
  11215. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11216. }
  11217. else {
  11218. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11219. }
  11220. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11221. var buffer;
  11222. switch (readType) {
  11223. case gl.UNSIGNED_BYTE:
  11224. buffer = new Uint8Array(4 * width * height);
  11225. readType = gl.UNSIGNED_BYTE;
  11226. break;
  11227. default:
  11228. buffer = new Float32Array(4 * width * height);
  11229. readType = gl.FLOAT;
  11230. break;
  11231. }
  11232. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11233. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11234. return buffer;
  11235. };
  11236. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11237. if (this._webGLVersion > 1) {
  11238. return this._caps.colorBufferFloat;
  11239. }
  11240. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11241. };
  11242. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11243. if (this._webGLVersion > 1) {
  11244. return this._caps.colorBufferFloat;
  11245. }
  11246. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11247. };
  11248. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11249. Engine.prototype._canRenderToFramebuffer = function (type) {
  11250. var gl = this._gl;
  11251. //clear existing errors
  11252. while (gl.getError() !== gl.NO_ERROR) { }
  11253. var successful = true;
  11254. var texture = gl.createTexture();
  11255. gl.bindTexture(gl.TEXTURE_2D, texture);
  11256. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11257. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11258. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11259. var fb = gl.createFramebuffer();
  11260. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11261. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11262. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11263. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11264. successful = successful && (gl.getError() === gl.NO_ERROR);
  11265. //try render by clearing frame buffer's color buffer
  11266. if (successful) {
  11267. gl.clear(gl.COLOR_BUFFER_BIT);
  11268. successful = successful && (gl.getError() === gl.NO_ERROR);
  11269. }
  11270. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11271. if (successful) {
  11272. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11273. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11274. var readFormat = gl.RGBA;
  11275. var readType = gl.UNSIGNED_BYTE;
  11276. var buffer = new Uint8Array(4);
  11277. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11278. successful = successful && (gl.getError() === gl.NO_ERROR);
  11279. }
  11280. //clean up
  11281. gl.deleteTexture(texture);
  11282. gl.deleteFramebuffer(fb);
  11283. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11284. //clear accumulated errors
  11285. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11286. return successful;
  11287. };
  11288. Engine.prototype._getWebGLTextureType = function (type) {
  11289. if (type === Engine.TEXTURETYPE_FLOAT) {
  11290. return this._gl.FLOAT;
  11291. }
  11292. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11293. // Add Half Float Constant.
  11294. return this._gl.HALF_FLOAT_OES;
  11295. }
  11296. return this._gl.UNSIGNED_BYTE;
  11297. };
  11298. ;
  11299. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11300. if (this._webGLVersion === 1) {
  11301. return this._gl.RGBA;
  11302. }
  11303. if (type === Engine.TEXTURETYPE_FLOAT) {
  11304. return this._gl.RGBA32F;
  11305. }
  11306. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11307. return this._gl.RGBA16F;
  11308. }
  11309. return this._gl.RGBA;
  11310. };
  11311. ;
  11312. Engine.prototype.createQuery = function () {
  11313. return this._gl.createQuery();
  11314. };
  11315. Engine.prototype.deleteQuery = function (query) {
  11316. this._gl.deleteQuery(query);
  11317. return this;
  11318. };
  11319. Engine.prototype.isQueryResultAvailable = function (query) {
  11320. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11321. };
  11322. Engine.prototype.getQueryResult = function (query) {
  11323. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11324. };
  11325. Engine.prototype.beginQuery = function (algorithmType, query) {
  11326. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11327. this._gl.beginQuery(glAlgorithm, query);
  11328. };
  11329. Engine.prototype.endQuery = function (algorithmType) {
  11330. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11331. this._gl.endQuery(glAlgorithm);
  11332. return this;
  11333. };
  11334. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  11335. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  11336. };
  11337. // Statics
  11338. Engine.isSupported = function () {
  11339. try {
  11340. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  11341. if (navigator.isCocoonJS) {
  11342. return true;
  11343. }
  11344. var tempcanvas = document.createElement("canvas");
  11345. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  11346. return gl != null && !!window.WebGLRenderingContext;
  11347. }
  11348. catch (e) {
  11349. return false;
  11350. }
  11351. };
  11352. Engine.Instances = new Array();
  11353. // Const statics
  11354. Engine._ALPHA_DISABLE = 0;
  11355. Engine._ALPHA_ADD = 1;
  11356. Engine._ALPHA_COMBINE = 2;
  11357. Engine._ALPHA_SUBTRACT = 3;
  11358. Engine._ALPHA_MULTIPLY = 4;
  11359. Engine._ALPHA_MAXIMIZED = 5;
  11360. Engine._ALPHA_ONEONE = 6;
  11361. Engine._ALPHA_PREMULTIPLIED = 7;
  11362. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  11363. Engine._ALPHA_INTERPOLATE = 9;
  11364. Engine._ALPHA_SCREENMODE = 10;
  11365. Engine._DELAYLOADSTATE_NONE = 0;
  11366. Engine._DELAYLOADSTATE_LOADED = 1;
  11367. Engine._DELAYLOADSTATE_LOADING = 2;
  11368. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  11369. Engine._TEXTUREFORMAT_ALPHA = 0;
  11370. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  11371. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  11372. Engine._TEXTUREFORMAT_RGB = 4;
  11373. Engine._TEXTUREFORMAT_RGBA = 5;
  11374. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  11375. Engine._TEXTURETYPE_FLOAT = 1;
  11376. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  11377. // Depht or Stencil test Constants.
  11378. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  11379. 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.
  11380. 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.
  11381. 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.
  11382. 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.
  11383. 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.
  11384. 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.
  11385. 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.
  11386. // Stencil Actions Constants.
  11387. Engine._KEEP = 0x1E00;
  11388. Engine._REPLACE = 0x1E01;
  11389. Engine._INCR = 0x1E02;
  11390. Engine._DECR = 0x1E03;
  11391. Engine._INVERT = 0x150A;
  11392. Engine._INCR_WRAP = 0x8507;
  11393. Engine._DECR_WRAP = 0x8508;
  11394. // Texture rescaling mode
  11395. Engine._SCALEMODE_FLOOR = 1;
  11396. Engine._SCALEMODE_NEAREST = 2;
  11397. Engine._SCALEMODE_CEILING = 3;
  11398. // Updatable statics so stick with vars here
  11399. Engine.CollisionsEpsilon = 0.001;
  11400. Engine.CodeRepository = "src/";
  11401. Engine.ShadersRepository = "src/Shaders/";
  11402. return Engine;
  11403. }());
  11404. BABYLON.Engine = Engine;
  11405. })(BABYLON || (BABYLON = {}));
  11406. //# sourceMappingURL=babylon.engine.js.map
  11407. /// <reference path="Tools\babylon.decorators.ts" />
  11408. var BABYLON;
  11409. (function (BABYLON) {
  11410. /**
  11411. * Node is the basic class for all scene objects (Mesh, Light Camera).
  11412. */
  11413. var Node = (function () {
  11414. /**
  11415. * @constructor
  11416. * @param {string} name - the name and id to be given to this node
  11417. * @param {BABYLON.Scene} the scene this node will be added to
  11418. */
  11419. function Node(name, scene) {
  11420. this.state = "";
  11421. this.metadata = null;
  11422. this.doNotSerialize = false;
  11423. this.animations = new Array();
  11424. this._ranges = {};
  11425. this._childrenFlag = -1;
  11426. this._isEnabled = true;
  11427. this._isReady = true;
  11428. this._currentRenderId = -1;
  11429. this._parentRenderId = -1;
  11430. /**
  11431. * An event triggered when the mesh is disposed.
  11432. * @type {BABYLON.Observable}
  11433. */
  11434. this.onDisposeObservable = new BABYLON.Observable();
  11435. // Behaviors
  11436. this._behaviors = new Array();
  11437. this.name = name;
  11438. this.id = name;
  11439. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  11440. this._initCache();
  11441. }
  11442. Object.defineProperty(Node.prototype, "parent", {
  11443. get: function () {
  11444. return this._parentNode;
  11445. },
  11446. set: function (parent) {
  11447. if (this._parentNode === parent) {
  11448. return;
  11449. }
  11450. if (this._parentNode) {
  11451. var index = this._parentNode._children.indexOf(this);
  11452. if (index !== -1) {
  11453. this._parentNode._children.splice(index, 1);
  11454. }
  11455. }
  11456. this._parentNode = parent;
  11457. if (this._parentNode) {
  11458. if (!this._parentNode._children) {
  11459. this._parentNode._children = new Array();
  11460. }
  11461. this._parentNode._children.push(this);
  11462. }
  11463. },
  11464. enumerable: true,
  11465. configurable: true
  11466. });
  11467. Node.prototype.getClassName = function () {
  11468. return "Node";
  11469. };
  11470. Object.defineProperty(Node.prototype, "onDispose", {
  11471. set: function (callback) {
  11472. if (this._onDisposeObserver) {
  11473. this.onDisposeObservable.remove(this._onDisposeObserver);
  11474. }
  11475. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  11476. },
  11477. enumerable: true,
  11478. configurable: true
  11479. });
  11480. Node.prototype.getScene = function () {
  11481. return this._scene;
  11482. };
  11483. Node.prototype.getEngine = function () {
  11484. return this._scene.getEngine();
  11485. };
  11486. Node.prototype.addBehavior = function (behavior) {
  11487. var index = this._behaviors.indexOf(behavior);
  11488. if (index !== -1) {
  11489. return;
  11490. }
  11491. behavior.attach(this);
  11492. this._behaviors.push(behavior);
  11493. return this;
  11494. };
  11495. Node.prototype.removeBehavior = function (behavior) {
  11496. var index = this._behaviors.indexOf(behavior);
  11497. if (index === -1) {
  11498. return;
  11499. }
  11500. this._behaviors[index].detach();
  11501. this._behaviors.splice(index, 1);
  11502. return this;
  11503. };
  11504. Object.defineProperty(Node.prototype, "behaviors", {
  11505. get: function () {
  11506. return this._behaviors;
  11507. },
  11508. enumerable: true,
  11509. configurable: true
  11510. });
  11511. Node.prototype.getBehaviorByName = function (name) {
  11512. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11513. var behavior = _a[_i];
  11514. if (behavior.name === name) {
  11515. return behavior;
  11516. }
  11517. }
  11518. return null;
  11519. };
  11520. // override it in derived class
  11521. Node.prototype.getWorldMatrix = function () {
  11522. return BABYLON.Matrix.Identity();
  11523. };
  11524. // override it in derived class if you add new variables to the cache
  11525. // and call the parent class method
  11526. Node.prototype._initCache = function () {
  11527. this._cache = {};
  11528. this._cache.parent = undefined;
  11529. };
  11530. Node.prototype.updateCache = function (force) {
  11531. if (!force && this.isSynchronized())
  11532. return;
  11533. this._cache.parent = this.parent;
  11534. this._updateCache();
  11535. };
  11536. // override it in derived class if you add new variables to the cache
  11537. // and call the parent class method if !ignoreParentClass
  11538. Node.prototype._updateCache = function (ignoreParentClass) {
  11539. };
  11540. // override it in derived class if you add new variables to the cache
  11541. Node.prototype._isSynchronized = function () {
  11542. return true;
  11543. };
  11544. Node.prototype._markSyncedWithParent = function () {
  11545. this._parentRenderId = this.parent._currentRenderId;
  11546. };
  11547. Node.prototype.isSynchronizedWithParent = function () {
  11548. if (!this.parent) {
  11549. return true;
  11550. }
  11551. if (this._parentRenderId !== this.parent._currentRenderId) {
  11552. return false;
  11553. }
  11554. return this.parent.isSynchronized();
  11555. };
  11556. Node.prototype.isSynchronized = function (updateCache) {
  11557. var check = this.hasNewParent();
  11558. check = check || !this.isSynchronizedWithParent();
  11559. check = check || !this._isSynchronized();
  11560. if (updateCache)
  11561. this.updateCache(true);
  11562. return !check;
  11563. };
  11564. Node.prototype.hasNewParent = function (update) {
  11565. if (this._cache.parent === this.parent)
  11566. return false;
  11567. if (update)
  11568. this._cache.parent = this.parent;
  11569. return true;
  11570. };
  11571. /**
  11572. * Is this node ready to be used/rendered
  11573. * @return {boolean} is it ready
  11574. */
  11575. Node.prototype.isReady = function () {
  11576. return this._isReady;
  11577. };
  11578. /**
  11579. * Is this node enabled.
  11580. * If the node has a parent and is enabled, the parent will be inspected as well.
  11581. * @return {boolean} whether this node (and its parent) is enabled.
  11582. * @see setEnabled
  11583. */
  11584. Node.prototype.isEnabled = function () {
  11585. if (!this._isEnabled) {
  11586. return false;
  11587. }
  11588. if (this.parent) {
  11589. return this.parent.isEnabled();
  11590. }
  11591. return true;
  11592. };
  11593. /**
  11594. * Set the enabled state of this node.
  11595. * @param {boolean} value - the new enabled state
  11596. * @see isEnabled
  11597. */
  11598. Node.prototype.setEnabled = function (value) {
  11599. this._isEnabled = value;
  11600. };
  11601. /**
  11602. * Is this node a descendant of the given node.
  11603. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  11604. * @param {BABYLON.Node} ancestor - The parent node to inspect
  11605. * @see parent
  11606. */
  11607. Node.prototype.isDescendantOf = function (ancestor) {
  11608. if (this.parent) {
  11609. if (this.parent === ancestor) {
  11610. return true;
  11611. }
  11612. return this.parent.isDescendantOf(ancestor);
  11613. }
  11614. return false;
  11615. };
  11616. /**
  11617. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  11618. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  11619. * @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.
  11620. * @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.
  11621. */
  11622. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  11623. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  11624. if (!this._children) {
  11625. return;
  11626. }
  11627. for (var index = 0; index < this._children.length; index++) {
  11628. var item = this._children[index];
  11629. if (!predicate || predicate(item)) {
  11630. results.push(item);
  11631. }
  11632. if (!directDescendantsOnly) {
  11633. item._getDescendants(results, false, predicate);
  11634. }
  11635. }
  11636. };
  11637. /**
  11638. * Will return all nodes that have this node as ascendant.
  11639. * @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.
  11640. * @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.
  11641. * @return {BABYLON.Node[]} all children nodes of all types.
  11642. */
  11643. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  11644. var results = [];
  11645. this._getDescendants(results, directDescendantsOnly, predicate);
  11646. return results;
  11647. };
  11648. /**
  11649. * Get all child-meshes of this node.
  11650. */
  11651. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  11652. var results = [];
  11653. this._getDescendants(results, directDecendantsOnly, function (node) {
  11654. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  11655. });
  11656. return results;
  11657. };
  11658. /**
  11659. * Get all direct children of this node.
  11660. */
  11661. Node.prototype.getChildren = function (predicate) {
  11662. return this.getDescendants(true, predicate);
  11663. };
  11664. Node.prototype._setReady = function (state) {
  11665. if (state === this._isReady) {
  11666. return;
  11667. }
  11668. if (!state) {
  11669. this._isReady = false;
  11670. return;
  11671. }
  11672. this._isReady = true;
  11673. if (this.onReady) {
  11674. this.onReady(this);
  11675. }
  11676. };
  11677. Node.prototype.getAnimationByName = function (name) {
  11678. for (var i = 0; i < this.animations.length; i++) {
  11679. var animation = this.animations[i];
  11680. if (animation.name === name) {
  11681. return animation;
  11682. }
  11683. }
  11684. return null;
  11685. };
  11686. Node.prototype.createAnimationRange = function (name, from, to) {
  11687. // check name not already in use
  11688. if (!this._ranges[name]) {
  11689. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11690. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11691. if (this.animations[i]) {
  11692. this.animations[i].createRange(name, from, to);
  11693. }
  11694. }
  11695. }
  11696. };
  11697. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11698. if (deleteFrames === void 0) { deleteFrames = true; }
  11699. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11700. if (this.animations[i]) {
  11701. this.animations[i].deleteRange(name, deleteFrames);
  11702. }
  11703. }
  11704. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11705. };
  11706. Node.prototype.getAnimationRange = function (name) {
  11707. return this._ranges[name];
  11708. };
  11709. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11710. var range = this.getAnimationRange(name);
  11711. if (!range) {
  11712. return null;
  11713. }
  11714. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11715. };
  11716. Node.prototype.serializeAnimationRanges = function () {
  11717. var serializationRanges = [];
  11718. for (var name in this._ranges) {
  11719. var range = {};
  11720. range.name = name;
  11721. range.from = this._ranges[name].from;
  11722. range.to = this._ranges[name].to;
  11723. serializationRanges.push(range);
  11724. }
  11725. return serializationRanges;
  11726. };
  11727. Node.prototype.dispose = function () {
  11728. this.parent = null;
  11729. // Callback
  11730. this.onDisposeObservable.notifyObservers(this);
  11731. this.onDisposeObservable.clear();
  11732. // Behaviors
  11733. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11734. var behavior = _a[_i];
  11735. behavior.detach();
  11736. }
  11737. this._behaviors = [];
  11738. };
  11739. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11740. if (parsedNode.ranges) {
  11741. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11742. var data = parsedNode.ranges[index];
  11743. node.createAnimationRange(data.name, data.from, data.to);
  11744. }
  11745. }
  11746. };
  11747. __decorate([
  11748. BABYLON.serialize()
  11749. ], Node.prototype, "name", void 0);
  11750. __decorate([
  11751. BABYLON.serialize()
  11752. ], Node.prototype, "id", void 0);
  11753. __decorate([
  11754. BABYLON.serialize()
  11755. ], Node.prototype, "uniqueId", void 0);
  11756. __decorate([
  11757. BABYLON.serialize()
  11758. ], Node.prototype, "state", void 0);
  11759. __decorate([
  11760. BABYLON.serialize()
  11761. ], Node.prototype, "metadata", void 0);
  11762. return Node;
  11763. }());
  11764. BABYLON.Node = Node;
  11765. })(BABYLON || (BABYLON = {}));
  11766. //# sourceMappingURL=babylon.node.js.map
  11767. var BABYLON;
  11768. (function (BABYLON) {
  11769. var BoundingSphere = (function () {
  11770. function BoundingSphere(minimum, maximum) {
  11771. this.minimum = minimum;
  11772. this.maximum = maximum;
  11773. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11774. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11775. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11776. this.radius = distance * 0.5;
  11777. this.centerWorld = BABYLON.Vector3.Zero();
  11778. this._update(BABYLON.Matrix.Identity());
  11779. }
  11780. // Methods
  11781. BoundingSphere.prototype._update = function (world) {
  11782. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11783. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11784. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11785. };
  11786. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11787. for (var i = 0; i < 6; i++) {
  11788. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11789. return false;
  11790. }
  11791. return true;
  11792. };
  11793. BoundingSphere.prototype.intersectsPoint = function (point) {
  11794. var x = this.centerWorld.x - point.x;
  11795. var y = this.centerWorld.y - point.y;
  11796. var z = this.centerWorld.z - point.z;
  11797. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11798. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11799. return false;
  11800. return true;
  11801. };
  11802. // Statics
  11803. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11804. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11805. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11806. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11807. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11808. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11809. return false;
  11810. return true;
  11811. };
  11812. return BoundingSphere;
  11813. }());
  11814. BABYLON.BoundingSphere = BoundingSphere;
  11815. })(BABYLON || (BABYLON = {}));
  11816. //# sourceMappingURL=babylon.boundingSphere.js.map
  11817. var BABYLON;
  11818. (function (BABYLON) {
  11819. var BoundingBox = (function () {
  11820. function BoundingBox(minimum, maximum) {
  11821. this.minimum = minimum;
  11822. this.maximum = maximum;
  11823. this.vectors = new Array();
  11824. this.vectorsWorld = new Array();
  11825. // Bounding vectors
  11826. this.vectors.push(this.minimum.clone());
  11827. this.vectors.push(this.maximum.clone());
  11828. this.vectors.push(this.minimum.clone());
  11829. this.vectors[2].x = this.maximum.x;
  11830. this.vectors.push(this.minimum.clone());
  11831. this.vectors[3].y = this.maximum.y;
  11832. this.vectors.push(this.minimum.clone());
  11833. this.vectors[4].z = this.maximum.z;
  11834. this.vectors.push(this.maximum.clone());
  11835. this.vectors[5].z = this.minimum.z;
  11836. this.vectors.push(this.maximum.clone());
  11837. this.vectors[6].x = this.minimum.x;
  11838. this.vectors.push(this.maximum.clone());
  11839. this.vectors[7].y = this.minimum.y;
  11840. // OBB
  11841. this.center = this.maximum.add(this.minimum).scale(0.5);
  11842. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11843. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11844. // World
  11845. for (var index = 0; index < this.vectors.length; index++) {
  11846. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11847. }
  11848. this.minimumWorld = BABYLON.Vector3.Zero();
  11849. this.maximumWorld = BABYLON.Vector3.Zero();
  11850. this.centerWorld = BABYLON.Vector3.Zero();
  11851. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11852. this._update(BABYLON.Matrix.Identity());
  11853. }
  11854. // Methods
  11855. BoundingBox.prototype.getWorldMatrix = function () {
  11856. return this._worldMatrix;
  11857. };
  11858. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11859. this._worldMatrix.copyFrom(matrix);
  11860. return this;
  11861. };
  11862. BoundingBox.prototype._update = function (world) {
  11863. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11864. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11865. for (var index = 0; index < this.vectors.length; index++) {
  11866. var v = this.vectorsWorld[index];
  11867. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11868. if (v.x < this.minimumWorld.x)
  11869. this.minimumWorld.x = v.x;
  11870. if (v.y < this.minimumWorld.y)
  11871. this.minimumWorld.y = v.y;
  11872. if (v.z < this.minimumWorld.z)
  11873. this.minimumWorld.z = v.z;
  11874. if (v.x > this.maximumWorld.x)
  11875. this.maximumWorld.x = v.x;
  11876. if (v.y > this.maximumWorld.y)
  11877. this.maximumWorld.y = v.y;
  11878. if (v.z > this.maximumWorld.z)
  11879. this.maximumWorld.z = v.z;
  11880. }
  11881. // Extend
  11882. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11883. this.extendSizeWorld.scaleInPlace(0.5);
  11884. // OBB
  11885. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11886. this.centerWorld.scaleInPlace(0.5);
  11887. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11888. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11889. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11890. this._worldMatrix = world;
  11891. };
  11892. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11893. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11894. };
  11895. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11896. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11897. };
  11898. BoundingBox.prototype.intersectsPoint = function (point) {
  11899. var delta = -BABYLON.Epsilon;
  11900. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11901. return false;
  11902. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11903. return false;
  11904. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11905. return false;
  11906. return true;
  11907. };
  11908. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11909. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11910. };
  11911. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11912. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11913. return false;
  11914. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11915. return false;
  11916. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11917. return false;
  11918. return true;
  11919. };
  11920. // Statics
  11921. BoundingBox.Intersects = function (box0, box1) {
  11922. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11923. return false;
  11924. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11925. return false;
  11926. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11927. return false;
  11928. return true;
  11929. };
  11930. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11931. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11932. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11933. return (num <= (sphereRadius * sphereRadius));
  11934. };
  11935. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11936. for (var p = 0; p < 6; p++) {
  11937. for (var i = 0; i < 8; i++) {
  11938. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11939. return false;
  11940. }
  11941. }
  11942. }
  11943. return true;
  11944. };
  11945. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11946. for (var p = 0; p < 6; p++) {
  11947. var inCount = 8;
  11948. for (var i = 0; i < 8; i++) {
  11949. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11950. --inCount;
  11951. }
  11952. else {
  11953. break;
  11954. }
  11955. }
  11956. if (inCount === 0)
  11957. return false;
  11958. }
  11959. return true;
  11960. };
  11961. return BoundingBox;
  11962. }());
  11963. BABYLON.BoundingBox = BoundingBox;
  11964. })(BABYLON || (BABYLON = {}));
  11965. //# sourceMappingURL=babylon.boundingBox.js.map
  11966. var BABYLON;
  11967. (function (BABYLON) {
  11968. var computeBoxExtents = function (axis, box) {
  11969. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11970. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11971. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11972. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11973. var r = r0 + r1 + r2;
  11974. return {
  11975. min: p - r,
  11976. max: p + r
  11977. };
  11978. };
  11979. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11980. var axisOverlap = function (axis, box0, box1) {
  11981. var result0 = computeBoxExtents(axis, box0);
  11982. var result1 = computeBoxExtents(axis, box1);
  11983. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11984. };
  11985. var BoundingInfo = (function () {
  11986. function BoundingInfo(minimum, maximum) {
  11987. this.minimum = minimum;
  11988. this.maximum = maximum;
  11989. this._isLocked = false;
  11990. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11991. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11992. }
  11993. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11994. get: function () {
  11995. return this._isLocked;
  11996. },
  11997. set: function (value) {
  11998. this._isLocked = value;
  11999. },
  12000. enumerable: true,
  12001. configurable: true
  12002. });
  12003. // Methods
  12004. BoundingInfo.prototype.update = function (world) {
  12005. if (this._isLocked) {
  12006. return;
  12007. }
  12008. this.boundingBox._update(world);
  12009. this.boundingSphere._update(world);
  12010. };
  12011. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12012. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12013. return false;
  12014. return this.boundingBox.isInFrustum(frustumPlanes);
  12015. };
  12016. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12017. /**
  12018. * Gets the world distance between the min and max points of the bounding box
  12019. */
  12020. get: function () {
  12021. var boundingBox = this.boundingBox;
  12022. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12023. return size.length();
  12024. },
  12025. enumerable: true,
  12026. configurable: true
  12027. });
  12028. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12029. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12030. };
  12031. BoundingInfo.prototype._checkCollision = function (collider) {
  12032. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12033. };
  12034. BoundingInfo.prototype.intersectsPoint = function (point) {
  12035. if (!this.boundingSphere.centerWorld) {
  12036. return false;
  12037. }
  12038. if (!this.boundingSphere.intersectsPoint(point)) {
  12039. return false;
  12040. }
  12041. if (!this.boundingBox.intersectsPoint(point)) {
  12042. return false;
  12043. }
  12044. return true;
  12045. };
  12046. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12047. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12048. return false;
  12049. }
  12050. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12051. return false;
  12052. }
  12053. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12054. return false;
  12055. }
  12056. if (!precise) {
  12057. return true;
  12058. }
  12059. var box0 = this.boundingBox;
  12060. var box1 = boundingInfo.boundingBox;
  12061. if (!axisOverlap(box0.directions[0], box0, box1))
  12062. return false;
  12063. if (!axisOverlap(box0.directions[1], box0, box1))
  12064. return false;
  12065. if (!axisOverlap(box0.directions[2], box0, box1))
  12066. return false;
  12067. if (!axisOverlap(box1.directions[0], box0, box1))
  12068. return false;
  12069. if (!axisOverlap(box1.directions[1], box0, box1))
  12070. return false;
  12071. if (!axisOverlap(box1.directions[2], box0, box1))
  12072. return false;
  12073. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12074. return false;
  12075. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12076. return false;
  12077. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12078. return false;
  12079. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12080. return false;
  12081. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12082. return false;
  12083. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12084. return false;
  12085. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12086. return false;
  12087. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12088. return false;
  12089. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12090. return false;
  12091. return true;
  12092. };
  12093. return BoundingInfo;
  12094. }());
  12095. BABYLON.BoundingInfo = BoundingInfo;
  12096. })(BABYLON || (BABYLON = {}));
  12097. //# sourceMappingURL=babylon.boundingInfo.js.map
  12098. var BABYLON;
  12099. (function (BABYLON) {
  12100. var AbstractMesh = (function (_super) {
  12101. __extends(AbstractMesh, _super);
  12102. // Constructor
  12103. function AbstractMesh(name, scene) {
  12104. var _this = _super.call(this, name, scene) || this;
  12105. _this._facetNb = 0; // facet number
  12106. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12107. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12108. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12109. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12110. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12111. _this._subDiv = {
  12112. max: 1,
  12113. X: 1,
  12114. Y: 1,
  12115. Z: 1
  12116. };
  12117. // Events
  12118. /**
  12119. * An event triggered when this mesh collides with another one
  12120. * @type {BABYLON.Observable}
  12121. */
  12122. _this.onCollideObservable = new BABYLON.Observable();
  12123. /**
  12124. * An event triggered when the collision's position changes
  12125. * @type {BABYLON.Observable}
  12126. */
  12127. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12128. /**
  12129. * An event triggered after the world matrix is updated
  12130. * @type {BABYLON.Observable}
  12131. */
  12132. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12133. /**
  12134. * An event triggered when material is changed
  12135. * @type {BABYLON.Observable}
  12136. */
  12137. _this.onMaterialChangedObservable = new BABYLON.Observable();
  12138. // Properties
  12139. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12140. _this.position = BABYLON.Vector3.Zero();
  12141. /**
  12142. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  12143. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  12144. * or
  12145. * 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.
  12146. * for more info check WebGl documentations
  12147. */
  12148. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  12149. /**
  12150. * 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:
  12151. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  12152. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  12153. * 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.
  12154. */
  12155. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  12156. /**
  12157. * 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.
  12158. * The default value is -1 which means don't break the query and wait till the result.
  12159. */
  12160. _this.occlusionRetryCount = -1;
  12161. _this._occlusionInternalRetryCounter = 0;
  12162. _this._isOccluded = false;
  12163. _this._isOcclusionQueryInProgress = false;
  12164. _this._rotation = BABYLON.Vector3.Zero();
  12165. _this._scaling = BABYLON.Vector3.One();
  12166. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12167. _this.visibility = 1.0;
  12168. _this.alphaIndex = Number.MAX_VALUE;
  12169. _this.infiniteDistance = false;
  12170. _this.isVisible = true;
  12171. _this.isPickable = true;
  12172. _this.showBoundingBox = false;
  12173. _this.showSubMeshesBoundingBox = false;
  12174. _this.isBlocker = false;
  12175. _this.enablePointerMoveEvents = false;
  12176. _this.renderingGroupId = 0;
  12177. _this._receiveShadows = false;
  12178. _this.renderOutline = false;
  12179. _this.outlineColor = BABYLON.Color3.Red();
  12180. _this.outlineWidth = 0.02;
  12181. _this.renderOverlay = false;
  12182. _this.overlayColor = BABYLON.Color3.Red();
  12183. _this.overlayAlpha = 0.5;
  12184. _this._hasVertexAlpha = false;
  12185. _this._useVertexColors = true;
  12186. _this._computeBonesUsingShaders = true;
  12187. _this._numBoneInfluencers = 4;
  12188. _this._applyFog = true;
  12189. _this.scalingDeterminant = 1;
  12190. _this.useOctreeForRenderingSelection = true;
  12191. _this.useOctreeForPicking = true;
  12192. _this.useOctreeForCollisions = true;
  12193. _this._layerMask = 0x0FFFFFFF;
  12194. /**
  12195. * True if the mesh must be rendered in any case.
  12196. */
  12197. _this.alwaysSelectAsActiveMesh = false;
  12198. // Collisions
  12199. _this._checkCollisions = false;
  12200. _this._collisionMask = -1;
  12201. _this._collisionGroup = -1;
  12202. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12203. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12204. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12205. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12206. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12207. // Edges
  12208. _this.edgesWidth = 1;
  12209. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12210. // Cache
  12211. _this._localWorld = BABYLON.Matrix.Zero();
  12212. _this._worldMatrix = BABYLON.Matrix.Zero();
  12213. _this._absolutePosition = BABYLON.Vector3.Zero();
  12214. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12215. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12216. _this._isDirty = false;
  12217. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12218. _this._isDisposed = false;
  12219. _this._renderId = 0;
  12220. _this._intersectionsInProgress = new Array();
  12221. _this._isWorldMatrixFrozen = false;
  12222. _this._unIndexed = false;
  12223. _this._lightSources = new Array();
  12224. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12225. if (collidedMesh === void 0) { collidedMesh = null; }
  12226. //TODO move this to the collision coordinator!
  12227. if (_this.getScene().workerCollisions)
  12228. newPosition.multiplyInPlace(_this._collider.radius);
  12229. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12230. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12231. _this.position.addInPlace(_this._diffPositionForCollisions);
  12232. }
  12233. if (collidedMesh) {
  12234. _this.onCollideObservable.notifyObservers(collidedMesh);
  12235. }
  12236. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12237. };
  12238. _this.getScene().addMesh(_this);
  12239. _this._resyncLightSources();
  12240. return _this;
  12241. }
  12242. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12243. get: function () {
  12244. return AbstractMesh._BILLBOARDMODE_NONE;
  12245. },
  12246. enumerable: true,
  12247. configurable: true
  12248. });
  12249. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12250. get: function () {
  12251. return AbstractMesh._BILLBOARDMODE_X;
  12252. },
  12253. enumerable: true,
  12254. configurable: true
  12255. });
  12256. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12257. get: function () {
  12258. return AbstractMesh._BILLBOARDMODE_Y;
  12259. },
  12260. enumerable: true,
  12261. configurable: true
  12262. });
  12263. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12264. get: function () {
  12265. return AbstractMesh._BILLBOARDMODE_Z;
  12266. },
  12267. enumerable: true,
  12268. configurable: true
  12269. });
  12270. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12271. get: function () {
  12272. return AbstractMesh._BILLBOARDMODE_ALL;
  12273. },
  12274. enumerable: true,
  12275. configurable: true
  12276. });
  12277. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12278. /**
  12279. * Read-only : the number of facets in the mesh
  12280. */
  12281. get: function () {
  12282. return this._facetNb;
  12283. },
  12284. enumerable: true,
  12285. configurable: true
  12286. });
  12287. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12288. /**
  12289. * The number (integer) of subdivisions per axis in the partioning space
  12290. */
  12291. get: function () {
  12292. return this._partitioningSubdivisions;
  12293. },
  12294. set: function (nb) {
  12295. this._partitioningSubdivisions = nb;
  12296. },
  12297. enumerable: true,
  12298. configurable: true
  12299. });
  12300. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12301. /**
  12302. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12303. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12304. */
  12305. get: function () {
  12306. return this._partitioningBBoxRatio;
  12307. },
  12308. set: function (ratio) {
  12309. this._partitioningBBoxRatio = ratio;
  12310. },
  12311. enumerable: true,
  12312. configurable: true
  12313. });
  12314. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12315. /**
  12316. * Read-only boolean : is the feature facetData enabled ?
  12317. */
  12318. get: function () {
  12319. return this._facetDataEnabled;
  12320. },
  12321. enumerable: true,
  12322. configurable: true
  12323. });
  12324. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12325. set: function (callback) {
  12326. if (this._onCollideObserver) {
  12327. this.onCollideObservable.remove(this._onCollideObserver);
  12328. }
  12329. this._onCollideObserver = this.onCollideObservable.add(callback);
  12330. },
  12331. enumerable: true,
  12332. configurable: true
  12333. });
  12334. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12335. set: function (callback) {
  12336. if (this._onCollisionPositionChangeObserver) {
  12337. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12338. }
  12339. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12340. },
  12341. enumerable: true,
  12342. configurable: true
  12343. });
  12344. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  12345. /**
  12346. * 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.
  12347. */
  12348. get: function () {
  12349. return this._isOccluded;
  12350. },
  12351. set: function (value) {
  12352. this._isOccluded = value;
  12353. },
  12354. enumerable: true,
  12355. configurable: true
  12356. });
  12357. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  12358. /**
  12359. * Flag to check the progress status of the query
  12360. */
  12361. get: function () {
  12362. return this._isOcclusionQueryInProgress;
  12363. },
  12364. enumerable: true,
  12365. configurable: true
  12366. });
  12367. Object.defineProperty(AbstractMesh.prototype, "material", {
  12368. get: function () {
  12369. return this._material;
  12370. },
  12371. set: function (value) {
  12372. if (this._material === value) {
  12373. return;
  12374. }
  12375. this._material = value;
  12376. if (this.onMaterialChangedObservable.hasObservers) {
  12377. this.onMaterialChangedObservable.notifyObservers(this);
  12378. }
  12379. if (!this.subMeshes) {
  12380. return;
  12381. }
  12382. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12383. var subMesh = _a[_i];
  12384. subMesh.setEffect(null);
  12385. }
  12386. },
  12387. enumerable: true,
  12388. configurable: true
  12389. });
  12390. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  12391. get: function () {
  12392. return this._receiveShadows;
  12393. },
  12394. set: function (value) {
  12395. if (this._receiveShadows === value) {
  12396. return;
  12397. }
  12398. this._receiveShadows = value;
  12399. this._markSubMeshesAsLightDirty();
  12400. },
  12401. enumerable: true,
  12402. configurable: true
  12403. });
  12404. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  12405. get: function () {
  12406. return this._hasVertexAlpha;
  12407. },
  12408. set: function (value) {
  12409. if (this._hasVertexAlpha === value) {
  12410. return;
  12411. }
  12412. this._hasVertexAlpha = value;
  12413. this._markSubMeshesAsAttributesDirty();
  12414. },
  12415. enumerable: true,
  12416. configurable: true
  12417. });
  12418. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  12419. get: function () {
  12420. return this._useVertexColors;
  12421. },
  12422. set: function (value) {
  12423. if (this._useVertexColors === value) {
  12424. return;
  12425. }
  12426. this._useVertexColors = value;
  12427. this._markSubMeshesAsAttributesDirty();
  12428. },
  12429. enumerable: true,
  12430. configurable: true
  12431. });
  12432. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  12433. get: function () {
  12434. return this._computeBonesUsingShaders;
  12435. },
  12436. set: function (value) {
  12437. if (this._computeBonesUsingShaders === value) {
  12438. return;
  12439. }
  12440. this._computeBonesUsingShaders = value;
  12441. this._markSubMeshesAsAttributesDirty();
  12442. },
  12443. enumerable: true,
  12444. configurable: true
  12445. });
  12446. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  12447. get: function () {
  12448. return this._numBoneInfluencers;
  12449. },
  12450. set: function (value) {
  12451. if (this._numBoneInfluencers === value) {
  12452. return;
  12453. }
  12454. this._numBoneInfluencers = value;
  12455. this._markSubMeshesAsAttributesDirty();
  12456. },
  12457. enumerable: true,
  12458. configurable: true
  12459. });
  12460. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  12461. get: function () {
  12462. return this._applyFog;
  12463. },
  12464. set: function (value) {
  12465. if (this._applyFog === value) {
  12466. return;
  12467. }
  12468. this._applyFog = value;
  12469. this._markSubMeshesAsMiscDirty();
  12470. },
  12471. enumerable: true,
  12472. configurable: true
  12473. });
  12474. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  12475. get: function () {
  12476. return this._layerMask;
  12477. },
  12478. set: function (value) {
  12479. if (value === this._layerMask) {
  12480. return;
  12481. }
  12482. this._layerMask = value;
  12483. this._resyncLightSources();
  12484. },
  12485. enumerable: true,
  12486. configurable: true
  12487. });
  12488. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12489. get: function () {
  12490. return this._collisionMask;
  12491. },
  12492. set: function (mask) {
  12493. this._collisionMask = !isNaN(mask) ? mask : -1;
  12494. },
  12495. enumerable: true,
  12496. configurable: true
  12497. });
  12498. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12499. get: function () {
  12500. return this._collisionGroup;
  12501. },
  12502. set: function (mask) {
  12503. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12504. },
  12505. enumerable: true,
  12506. configurable: true
  12507. });
  12508. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  12509. get: function () {
  12510. return null;
  12511. },
  12512. enumerable: true,
  12513. configurable: true
  12514. });
  12515. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12516. get: function () {
  12517. return this._skeleton;
  12518. },
  12519. set: function (value) {
  12520. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12521. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12522. }
  12523. if (value && value.needInitialSkinMatrix) {
  12524. value._registerMeshWithPoseMatrix(this);
  12525. }
  12526. this._skeleton = value;
  12527. if (!this._skeleton) {
  12528. this._bonesTransformMatrices = null;
  12529. }
  12530. this._markSubMeshesAsAttributesDirty();
  12531. },
  12532. enumerable: true,
  12533. configurable: true
  12534. });
  12535. /**
  12536. * Boolean : true if the mesh has been disposed.
  12537. */
  12538. AbstractMesh.prototype.isDisposed = function () {
  12539. return this._isDisposed;
  12540. };
  12541. /**
  12542. * Returns the string "AbstractMesh"
  12543. */
  12544. AbstractMesh.prototype.getClassName = function () {
  12545. return "AbstractMesh";
  12546. };
  12547. /**
  12548. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12549. */
  12550. AbstractMesh.prototype.toString = function (fullDetails) {
  12551. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12552. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12553. if (this._skeleton) {
  12554. ret += ", skeleton: " + this._skeleton.name;
  12555. }
  12556. if (fullDetails) {
  12557. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12558. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12559. }
  12560. return ret;
  12561. };
  12562. AbstractMesh.prototype._rebuild = function () {
  12563. if (this._occlusionQuery) {
  12564. this._occlusionQuery = null;
  12565. }
  12566. if (this._edgesRenderer) {
  12567. this._edgesRenderer._rebuild();
  12568. }
  12569. if (!this.subMeshes) {
  12570. return;
  12571. }
  12572. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12573. var subMesh = _a[_i];
  12574. subMesh._rebuild();
  12575. }
  12576. };
  12577. AbstractMesh.prototype._resyncLightSources = function () {
  12578. this._lightSources.length = 0;
  12579. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  12580. var light = _a[_i];
  12581. if (!light.isEnabled()) {
  12582. continue;
  12583. }
  12584. if (light.canAffectMesh(this)) {
  12585. this._lightSources.push(light);
  12586. }
  12587. }
  12588. this._markSubMeshesAsLightDirty();
  12589. };
  12590. AbstractMesh.prototype._resyncLighSource = function (light) {
  12591. var isIn = light.isEnabled() && light.canAffectMesh(this);
  12592. var index = this._lightSources.indexOf(light);
  12593. if (index === -1) {
  12594. if (!isIn) {
  12595. return;
  12596. }
  12597. this._lightSources.push(light);
  12598. }
  12599. else {
  12600. if (isIn) {
  12601. return;
  12602. }
  12603. this._lightSources.splice(index, 1);
  12604. }
  12605. this._markSubMeshesAsLightDirty();
  12606. };
  12607. AbstractMesh.prototype._removeLightSource = function (light) {
  12608. var index = this._lightSources.indexOf(light);
  12609. if (index === -1) {
  12610. return;
  12611. }
  12612. this._lightSources.splice(index, 1);
  12613. };
  12614. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  12615. if (!this.subMeshes) {
  12616. return;
  12617. }
  12618. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12619. var subMesh = _a[_i];
  12620. if (subMesh._materialDefines) {
  12621. func(subMesh._materialDefines);
  12622. }
  12623. }
  12624. };
  12625. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  12626. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  12627. };
  12628. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  12629. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  12630. };
  12631. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  12632. if (!this.subMeshes) {
  12633. return;
  12634. }
  12635. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12636. var subMesh = _a[_i];
  12637. var material = subMesh.getMaterial();
  12638. if (material) {
  12639. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  12640. }
  12641. }
  12642. };
  12643. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12644. /**
  12645. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12646. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12647. * Default : (0.0, 0.0, 0.0)
  12648. */
  12649. get: function () {
  12650. return this._rotation;
  12651. },
  12652. set: function (newRotation) {
  12653. this._rotation = newRotation;
  12654. },
  12655. enumerable: true,
  12656. configurable: true
  12657. });
  12658. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12659. /**
  12660. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12661. * Default : (1.0, 1.0, 1.0)
  12662. */
  12663. get: function () {
  12664. return this._scaling;
  12665. },
  12666. set: function (newScaling) {
  12667. this._scaling = newScaling;
  12668. if (this.physicsImpostor) {
  12669. this.physicsImpostor.forceUpdate();
  12670. }
  12671. },
  12672. enumerable: true,
  12673. configurable: true
  12674. });
  12675. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12676. /**
  12677. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12678. * It's null by default.
  12679. * 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)
  12680. */
  12681. get: function () {
  12682. return this._rotationQuaternion;
  12683. },
  12684. set: function (quaternion) {
  12685. this._rotationQuaternion = quaternion;
  12686. //reset the rotation vector.
  12687. if (quaternion && this.rotation.length()) {
  12688. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12689. }
  12690. },
  12691. enumerable: true,
  12692. configurable: true
  12693. });
  12694. // Methods
  12695. /**
  12696. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12697. * Returns the AbstractMesh.
  12698. */
  12699. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12700. this._poseMatrix.copyFrom(matrix);
  12701. return this;
  12702. };
  12703. /**
  12704. * Returns the mesh Pose matrix.
  12705. * Returned object : Matrix
  12706. */
  12707. AbstractMesh.prototype.getPoseMatrix = function () {
  12708. return this._poseMatrix;
  12709. };
  12710. /**
  12711. * Disables the mesh edger rendering mode.
  12712. * Returns the AbstractMesh.
  12713. */
  12714. AbstractMesh.prototype.disableEdgesRendering = function () {
  12715. if (this._edgesRenderer !== undefined) {
  12716. this._edgesRenderer.dispose();
  12717. this._edgesRenderer = undefined;
  12718. }
  12719. return this;
  12720. };
  12721. /**
  12722. * Enables the edge rendering mode on the mesh.
  12723. * This mode makes the mesh edges visible.
  12724. * Returns the AbstractMesh.
  12725. */
  12726. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12727. if (epsilon === void 0) { epsilon = 0.95; }
  12728. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12729. this.disableEdgesRendering();
  12730. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12731. return this;
  12732. };
  12733. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12734. /**
  12735. * Returns true if the mesh is blocked. Used by the class Mesh.
  12736. * Returns the boolean `false` by default.
  12737. */
  12738. get: function () {
  12739. return false;
  12740. },
  12741. enumerable: true,
  12742. configurable: true
  12743. });
  12744. /**
  12745. * Returns the mesh itself by default, used by the class Mesh.
  12746. * Returned type : AbstractMesh
  12747. */
  12748. AbstractMesh.prototype.getLOD = function (camera) {
  12749. return this;
  12750. };
  12751. /**
  12752. * Returns 0 by default, used by the class Mesh.
  12753. * Returns an integer.
  12754. */
  12755. AbstractMesh.prototype.getTotalVertices = function () {
  12756. return 0;
  12757. };
  12758. /**
  12759. * Returns null by default, used by the class Mesh.
  12760. * Returned type : integer array
  12761. */
  12762. AbstractMesh.prototype.getIndices = function () {
  12763. return null;
  12764. };
  12765. /**
  12766. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12767. * Returned type : float array or Float32Array
  12768. */
  12769. AbstractMesh.prototype.getVerticesData = function (kind) {
  12770. return null;
  12771. };
  12772. /**
  12773. * Sets the vertex data of the mesh geometry for the requested `kind`.
  12774. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  12775. * The `data` are either a numeric array either a Float32Array.
  12776. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  12777. * 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).
  12778. * Note that a new underlying VertexBuffer object is created each call.
  12779. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  12780. *
  12781. * Possible `kind` values :
  12782. * - BABYLON.VertexBuffer.PositionKind
  12783. * - BABYLON.VertexBuffer.UVKind
  12784. * - BABYLON.VertexBuffer.UV2Kind
  12785. * - BABYLON.VertexBuffer.UV3Kind
  12786. * - BABYLON.VertexBuffer.UV4Kind
  12787. * - BABYLON.VertexBuffer.UV5Kind
  12788. * - BABYLON.VertexBuffer.UV6Kind
  12789. * - BABYLON.VertexBuffer.ColorKind
  12790. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12791. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12792. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12793. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12794. *
  12795. * Returns the Mesh.
  12796. */
  12797. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  12798. return null;
  12799. };
  12800. /**
  12801. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  12802. * If the mesh has no geometry, it is simply returned as it is.
  12803. * The `data` are either a numeric array either a Float32Array.
  12804. * No new underlying VertexBuffer object is created.
  12805. * 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.
  12806. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  12807. *
  12808. * Possible `kind` values :
  12809. * - BABYLON.VertexBuffer.PositionKind
  12810. * - BABYLON.VertexBuffer.UVKind
  12811. * - BABYLON.VertexBuffer.UV2Kind
  12812. * - BABYLON.VertexBuffer.UV3Kind
  12813. * - BABYLON.VertexBuffer.UV4Kind
  12814. * - BABYLON.VertexBuffer.UV5Kind
  12815. * - BABYLON.VertexBuffer.UV6Kind
  12816. * - BABYLON.VertexBuffer.ColorKind
  12817. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12818. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12819. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12820. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12821. *
  12822. * Returns the Mesh.
  12823. */
  12824. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  12825. return null;
  12826. };
  12827. /**
  12828. * Sets the mesh indices.
  12829. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  12830. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  12831. * This method creates a new index buffer each call.
  12832. * Returns the Mesh.
  12833. */
  12834. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  12835. return null;
  12836. };
  12837. /** Returns false by default, used by the class Mesh.
  12838. * Returns a boolean
  12839. */
  12840. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12841. return false;
  12842. };
  12843. /**
  12844. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12845. * Returns a BoundingInfo
  12846. */
  12847. AbstractMesh.prototype.getBoundingInfo = function () {
  12848. if (this._masterMesh) {
  12849. return this._masterMesh.getBoundingInfo();
  12850. }
  12851. if (!this._boundingInfo) {
  12852. this._updateBoundingInfo();
  12853. }
  12854. return this._boundingInfo;
  12855. };
  12856. /**
  12857. * Sets a mesh new object BoundingInfo.
  12858. * Returns the AbstractMesh.
  12859. */
  12860. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12861. this._boundingInfo = boundingInfo;
  12862. return this;
  12863. };
  12864. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12865. get: function () {
  12866. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12867. },
  12868. enumerable: true,
  12869. configurable: true
  12870. });
  12871. AbstractMesh.prototype._preActivate = function () {
  12872. };
  12873. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12874. };
  12875. AbstractMesh.prototype._activate = function (renderId) {
  12876. this._renderId = renderId;
  12877. };
  12878. /**
  12879. * Returns the last update of the World matrix
  12880. * Returns a Matrix.
  12881. */
  12882. AbstractMesh.prototype.getWorldMatrix = function () {
  12883. if (this._masterMesh) {
  12884. return this._masterMesh.getWorldMatrix();
  12885. }
  12886. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12887. this.computeWorldMatrix();
  12888. }
  12889. return this._worldMatrix;
  12890. };
  12891. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12892. /**
  12893. * Returns directly the last state of the mesh World matrix.
  12894. * A Matrix is returned.
  12895. */
  12896. get: function () {
  12897. return this._worldMatrix;
  12898. },
  12899. enumerable: true,
  12900. configurable: true
  12901. });
  12902. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12903. /**
  12904. * Returns the current mesh absolute position.
  12905. * Retuns a Vector3.
  12906. */
  12907. get: function () {
  12908. return this._absolutePosition;
  12909. },
  12910. enumerable: true,
  12911. configurable: true
  12912. });
  12913. /**
  12914. * Prevents the World matrix to be computed any longer.
  12915. * Returns the AbstractMesh.
  12916. */
  12917. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12918. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12919. this.computeWorldMatrix(true);
  12920. this._isWorldMatrixFrozen = true;
  12921. return this;
  12922. };
  12923. /**
  12924. * Allows back the World matrix computation.
  12925. * Returns the AbstractMesh.
  12926. */
  12927. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12928. this._isWorldMatrixFrozen = false;
  12929. this.computeWorldMatrix(true);
  12930. return this;
  12931. };
  12932. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12933. /**
  12934. * True if the World matrix has been frozen.
  12935. * Returns a boolean.
  12936. */
  12937. get: function () {
  12938. return this._isWorldMatrixFrozen;
  12939. },
  12940. enumerable: true,
  12941. configurable: true
  12942. });
  12943. /**
  12944. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12945. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12946. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12947. * The passed axis is also normalized.
  12948. * Returns the AbstractMesh.
  12949. */
  12950. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12951. axis.normalize();
  12952. if (!this.rotationQuaternion) {
  12953. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12954. this.rotation = BABYLON.Vector3.Zero();
  12955. }
  12956. var rotationQuaternion;
  12957. if (!space || space === BABYLON.Space.LOCAL) {
  12958. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12959. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12960. }
  12961. else {
  12962. if (this.parent) {
  12963. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12964. invertParentWorldMatrix.invert();
  12965. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12966. }
  12967. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12968. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12969. }
  12970. return this;
  12971. };
  12972. /**
  12973. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  12974. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12975. * The passed axis is also normalized.
  12976. * Returns the AbstractMesh.
  12977. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  12978. */
  12979. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  12980. axis.normalize();
  12981. if (!this.rotationQuaternion) {
  12982. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12983. this.rotation.copyFromFloats(0, 0, 0);
  12984. }
  12985. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  12986. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  12987. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  12988. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  12989. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  12990. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  12991. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  12992. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  12993. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12994. return this;
  12995. };
  12996. /**
  12997. * Translates the mesh along the axis vector for the passed distance in the given space.
  12998. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12999. * Returns the AbstractMesh.
  13000. */
  13001. AbstractMesh.prototype.translate = function (axis, distance, space) {
  13002. var displacementVector = axis.scale(distance);
  13003. if (!space || space === BABYLON.Space.LOCAL) {
  13004. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13005. this.setPositionWithLocalVector(tempV3);
  13006. }
  13007. else {
  13008. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13009. }
  13010. return this;
  13011. };
  13012. /**
  13013. * Adds a rotation step to the mesh current rotation.
  13014. * x, y, z are Euler angles expressed in radians.
  13015. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13016. * This means this rotation is made in the mesh local space only.
  13017. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13018. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13019. * ```javascript
  13020. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13021. * ```
  13022. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13023. * 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.
  13024. * Returns the AbstractMesh.
  13025. */
  13026. AbstractMesh.prototype.addRotation = function (x, y, z) {
  13027. var rotationQuaternion;
  13028. if (this.rotationQuaternion) {
  13029. rotationQuaternion = this.rotationQuaternion;
  13030. }
  13031. else {
  13032. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13033. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13034. }
  13035. var accumulation = BABYLON.Tmp.Quaternion[0];
  13036. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13037. rotationQuaternion.multiplyInPlace(accumulation);
  13038. if (!this.rotationQuaternion) {
  13039. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13040. }
  13041. return this;
  13042. };
  13043. /**
  13044. * Retuns the mesh absolute position in the World.
  13045. * Returns a Vector3.
  13046. */
  13047. AbstractMesh.prototype.getAbsolutePosition = function () {
  13048. this.computeWorldMatrix();
  13049. return this._absolutePosition;
  13050. };
  13051. /**
  13052. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13053. * Returns the AbstractMesh.
  13054. */
  13055. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  13056. if (!absolutePosition) {
  13057. return;
  13058. }
  13059. var absolutePositionX;
  13060. var absolutePositionY;
  13061. var absolutePositionZ;
  13062. if (absolutePosition.x === undefined) {
  13063. if (arguments.length < 3) {
  13064. return;
  13065. }
  13066. absolutePositionX = arguments[0];
  13067. absolutePositionY = arguments[1];
  13068. absolutePositionZ = arguments[2];
  13069. }
  13070. else {
  13071. absolutePositionX = absolutePosition.x;
  13072. absolutePositionY = absolutePosition.y;
  13073. absolutePositionZ = absolutePosition.z;
  13074. }
  13075. if (this.parent) {
  13076. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13077. invertParentWorldMatrix.invert();
  13078. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13079. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13080. }
  13081. else {
  13082. this.position.x = absolutePositionX;
  13083. this.position.y = absolutePositionY;
  13084. this.position.z = absolutePositionZ;
  13085. }
  13086. return this;
  13087. };
  13088. // ================================== Point of View Movement =================================
  13089. /**
  13090. * Perform relative position change from the point of view of behind the front of the mesh.
  13091. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13092. * Supports definition of mesh facing forward or backward.
  13093. * @param {number} amountRight
  13094. * @param {number} amountUp
  13095. * @param {number} amountForward
  13096. *
  13097. * Returns the AbstractMesh.
  13098. */
  13099. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  13100. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  13101. return this;
  13102. };
  13103. /**
  13104. * Calculate relative position change from the point of view of behind the front of the mesh.
  13105. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13106. * Supports definition of mesh facing forward or backward.
  13107. * @param {number} amountRight
  13108. * @param {number} amountUp
  13109. * @param {number} amountForward
  13110. *
  13111. * Returns a new Vector3.
  13112. */
  13113. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  13114. var rotMatrix = new BABYLON.Matrix();
  13115. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13116. rotQuaternion.toRotationMatrix(rotMatrix);
  13117. var translationDelta = BABYLON.Vector3.Zero();
  13118. var defForwardMult = this.definedFacingForward ? -1 : 1;
  13119. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  13120. return translationDelta;
  13121. };
  13122. // ================================== Point of View Rotation =================================
  13123. /**
  13124. * Perform relative rotation change from the point of view of behind the front of the mesh.
  13125. * Supports definition of mesh facing forward or backward.
  13126. * @param {number} flipBack
  13127. * @param {number} twirlClockwise
  13128. * @param {number} tiltRight
  13129. *
  13130. * Returns the AbstractMesh.
  13131. */
  13132. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13133. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  13134. return this;
  13135. };
  13136. /**
  13137. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  13138. * Supports definition of mesh facing forward or backward.
  13139. * @param {number} flipBack
  13140. * @param {number} twirlClockwise
  13141. * @param {number} tiltRight
  13142. *
  13143. * Returns a new Vector3.
  13144. */
  13145. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13146. var defForwardMult = this.definedFacingForward ? 1 : -1;
  13147. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  13148. };
  13149. /**
  13150. * Sets a new pivot matrix to the mesh.
  13151. * Returns the AbstractMesh.
  13152. */
  13153. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  13154. this._pivotMatrix = matrix;
  13155. this._cache.pivotMatrixUpdated = true;
  13156. return this;
  13157. };
  13158. /**
  13159. * Returns the mesh pivot matrix.
  13160. * Default : Identity.
  13161. * A Matrix is returned.
  13162. */
  13163. AbstractMesh.prototype.getPivotMatrix = function () {
  13164. return this._pivotMatrix;
  13165. };
  13166. AbstractMesh.prototype._isSynchronized = function () {
  13167. if (this._isDirty) {
  13168. return false;
  13169. }
  13170. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  13171. return false;
  13172. if (this._cache.pivotMatrixUpdated) {
  13173. return false;
  13174. }
  13175. if (this.infiniteDistance) {
  13176. return false;
  13177. }
  13178. if (!this._cache.position.equals(this.position))
  13179. return false;
  13180. if (this.rotationQuaternion) {
  13181. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13182. return false;
  13183. }
  13184. if (!this._cache.rotation.equals(this.rotation))
  13185. return false;
  13186. if (!this._cache.scaling.equals(this.scaling))
  13187. return false;
  13188. return true;
  13189. };
  13190. AbstractMesh.prototype._initCache = function () {
  13191. _super.prototype._initCache.call(this);
  13192. this._cache.localMatrixUpdated = false;
  13193. this._cache.position = BABYLON.Vector3.Zero();
  13194. this._cache.scaling = BABYLON.Vector3.Zero();
  13195. this._cache.rotation = BABYLON.Vector3.Zero();
  13196. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13197. this._cache.billboardMode = -1;
  13198. };
  13199. AbstractMesh.prototype.markAsDirty = function (property) {
  13200. if (property === "rotation") {
  13201. this.rotationQuaternion = null;
  13202. }
  13203. this._currentRenderId = Number.MAX_VALUE;
  13204. this._isDirty = true;
  13205. return this;
  13206. };
  13207. /**
  13208. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  13209. * Returns the AbstractMesh.
  13210. */
  13211. AbstractMesh.prototype._updateBoundingInfo = function () {
  13212. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  13213. this._boundingInfo.update(this.worldMatrixFromCache);
  13214. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13215. return this;
  13216. };
  13217. /**
  13218. * Update a mesh's children BoundingInfo objects only.
  13219. * Returns the AbstractMesh.
  13220. */
  13221. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  13222. if (!this.subMeshes) {
  13223. return;
  13224. }
  13225. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  13226. var subMesh = this.subMeshes[subIndex];
  13227. if (!subMesh.IsGlobal) {
  13228. subMesh.updateBoundingInfo(matrix);
  13229. }
  13230. }
  13231. return this;
  13232. };
  13233. /**
  13234. * Computes the mesh World matrix and returns it.
  13235. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13236. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13237. * If the parameter `force`is set to `true`, the actual computation is done.
  13238. * Returns the mesh World Matrix.
  13239. */
  13240. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  13241. if (this._isWorldMatrixFrozen) {
  13242. return this._worldMatrix;
  13243. }
  13244. if (!force && this.isSynchronized(true)) {
  13245. this._currentRenderId = this.getScene().getRenderId();
  13246. return this._worldMatrix;
  13247. }
  13248. this._cache.position.copyFrom(this.position);
  13249. this._cache.scaling.copyFrom(this.scaling);
  13250. this._cache.pivotMatrixUpdated = false;
  13251. this._cache.billboardMode = this.billboardMode;
  13252. this._currentRenderId = this.getScene().getRenderId();
  13253. this._isDirty = false;
  13254. // Scaling
  13255. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13256. // Rotation
  13257. //rotate, if quaternion is set and rotation was used
  13258. if (this.rotationQuaternion) {
  13259. var len = this.rotation.length();
  13260. if (len) {
  13261. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13262. this.rotation.copyFromFloats(0, 0, 0);
  13263. }
  13264. }
  13265. if (this.rotationQuaternion) {
  13266. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13267. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13268. }
  13269. else {
  13270. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13271. this._cache.rotation.copyFrom(this.rotation);
  13272. }
  13273. // Translation
  13274. if (this.infiniteDistance && !this.parent) {
  13275. var camera = this.getScene().activeCamera;
  13276. if (camera) {
  13277. var cameraWorldMatrix = camera.getWorldMatrix();
  13278. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13279. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13280. }
  13281. }
  13282. else {
  13283. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13284. }
  13285. // Composing transformations
  13286. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13287. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13288. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13289. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  13290. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  13291. // Need to decompose each rotation here
  13292. var currentPosition = BABYLON.Tmp.Vector3[3];
  13293. if (this.parent && this.parent.getWorldMatrix) {
  13294. if (this._meshToBoneReferal) {
  13295. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13296. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13297. }
  13298. else {
  13299. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13300. }
  13301. }
  13302. else {
  13303. currentPosition.copyFrom(this.position);
  13304. }
  13305. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  13306. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13307. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  13308. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13309. }
  13310. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  13311. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13312. }
  13313. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  13314. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13315. }
  13316. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13317. }
  13318. else {
  13319. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  13320. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13321. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13322. }
  13323. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13324. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13325. }
  13326. // Local world
  13327. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13328. // Parent
  13329. if (this.parent && this.parent.getWorldMatrix) {
  13330. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  13331. if (this._meshToBoneReferal) {
  13332. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13333. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13334. }
  13335. else {
  13336. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13337. }
  13338. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13339. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13340. this._worldMatrix.copyFrom(this._localWorld);
  13341. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13342. }
  13343. else {
  13344. if (this._meshToBoneReferal) {
  13345. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13346. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13347. }
  13348. else {
  13349. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13350. }
  13351. }
  13352. this._markSyncedWithParent();
  13353. }
  13354. else {
  13355. this._worldMatrix.copyFrom(this._localWorld);
  13356. }
  13357. // Bounding info
  13358. this._updateBoundingInfo();
  13359. // Absolute position
  13360. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13361. // Callbacks
  13362. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13363. if (!this._poseMatrix) {
  13364. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13365. }
  13366. return this._worldMatrix;
  13367. };
  13368. /**
  13369. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13370. * @param func: callback function to add
  13371. *
  13372. * Returns the AbstractMesh.
  13373. */
  13374. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13375. this.onAfterWorldMatrixUpdateObservable.add(func);
  13376. return this;
  13377. };
  13378. /**
  13379. * Removes a registered callback function.
  13380. * Returns the AbstractMesh.
  13381. */
  13382. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13383. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13384. return this;
  13385. };
  13386. /**
  13387. * Sets the mesh position in its local space.
  13388. * Returns the AbstractMesh.
  13389. */
  13390. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  13391. this.computeWorldMatrix();
  13392. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13393. return this;
  13394. };
  13395. /**
  13396. * Returns the mesh position in the local space from the current World matrix values.
  13397. * Returns a new Vector3.
  13398. */
  13399. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  13400. this.computeWorldMatrix();
  13401. var invLocalWorldMatrix = this._localWorld.clone();
  13402. invLocalWorldMatrix.invert();
  13403. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13404. };
  13405. /**
  13406. * Translates the mesh along the passed Vector3 in its local space.
  13407. * Returns the AbstractMesh.
  13408. */
  13409. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  13410. this.computeWorldMatrix(true);
  13411. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13412. return this;
  13413. };
  13414. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13415. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13416. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13417. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13418. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13419. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13420. /// <returns>Mesh oriented towards targetMesh</returns>
  13421. if (yawCor === void 0) { yawCor = 0; }
  13422. if (pitchCor === void 0) { pitchCor = 0; }
  13423. if (rollCor === void 0) { rollCor = 0; }
  13424. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13425. var dv = AbstractMesh._lookAtVectorCache;
  13426. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13427. targetPoint.subtractToRef(pos, dv);
  13428. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13429. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13430. var pitch = Math.atan2(dv.y, len);
  13431. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13432. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13433. return this;
  13434. };
  13435. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13436. this._meshToBoneReferal = affectedMesh;
  13437. this.parent = bone;
  13438. if (bone.getWorldMatrix().determinant() < 0) {
  13439. this.scalingDeterminant *= -1;
  13440. }
  13441. return this;
  13442. };
  13443. AbstractMesh.prototype.detachFromBone = function () {
  13444. if (this.parent.getWorldMatrix().determinant() < 0) {
  13445. this.scalingDeterminant *= -1;
  13446. }
  13447. this._meshToBoneReferal = null;
  13448. this.parent = null;
  13449. return this;
  13450. };
  13451. /**
  13452. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13453. * A mesh is in the frustum if its bounding box intersects the frustum.
  13454. * Boolean returned.
  13455. */
  13456. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13457. return this._boundingInfo.isInFrustum(frustumPlanes);
  13458. };
  13459. /**
  13460. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13461. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13462. * Boolean returned.
  13463. */
  13464. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13465. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13466. ;
  13467. };
  13468. /**
  13469. * True if the mesh intersects another mesh or a SolidParticle object.
  13470. * 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)
  13471. * Returns a boolean.
  13472. */
  13473. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  13474. if (!this._boundingInfo || !mesh._boundingInfo) {
  13475. return false;
  13476. }
  13477. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  13478. };
  13479. /**
  13480. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13481. * Returns a boolean.
  13482. */
  13483. AbstractMesh.prototype.intersectsPoint = function (point) {
  13484. if (!this._boundingInfo) {
  13485. return false;
  13486. }
  13487. return this._boundingInfo.intersectsPoint(point);
  13488. };
  13489. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13490. return this.physicsImpostor;
  13491. };
  13492. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13493. if (!camera) {
  13494. camera = this.getScene().activeCamera;
  13495. }
  13496. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13497. };
  13498. /**
  13499. * Returns the distance from the mesh to the active camera.
  13500. * Returns a float.
  13501. */
  13502. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13503. if (!camera) {
  13504. camera = this.getScene().activeCamera;
  13505. }
  13506. return this.absolutePosition.subtract(camera.position).length();
  13507. };
  13508. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13509. if (!this.physicsImpostor) {
  13510. return;
  13511. }
  13512. this.physicsImpostor.applyImpulse(force, contactPoint);
  13513. return this;
  13514. };
  13515. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13516. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13517. return;
  13518. }
  13519. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13520. mainPivot: pivot1,
  13521. connectedPivot: pivot2,
  13522. nativeParams: options
  13523. });
  13524. return this;
  13525. };
  13526. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13527. // Collisions
  13528. /**
  13529. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13530. * Default `false`.
  13531. */
  13532. get: function () {
  13533. return this._checkCollisions;
  13534. },
  13535. set: function (collisionEnabled) {
  13536. this._checkCollisions = collisionEnabled;
  13537. if (this.getScene().workerCollisions) {
  13538. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13539. }
  13540. },
  13541. enumerable: true,
  13542. configurable: true
  13543. });
  13544. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  13545. var globalPosition = this.getAbsolutePosition();
  13546. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13547. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13548. if (!this._collider) {
  13549. this._collider = new BABYLON.Collider();
  13550. }
  13551. this._collider.radius = this.ellipsoid;
  13552. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13553. return this;
  13554. };
  13555. // Submeshes octree
  13556. /**
  13557. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13558. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13559. * Returns an Octree of submeshes.
  13560. */
  13561. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13562. if (maxCapacity === void 0) { maxCapacity = 64; }
  13563. if (maxDepth === void 0) { maxDepth = 2; }
  13564. if (!this._submeshesOctree) {
  13565. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13566. }
  13567. this.computeWorldMatrix(true);
  13568. // Update octree
  13569. var bbox = this.getBoundingInfo().boundingBox;
  13570. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13571. return this._submeshesOctree;
  13572. };
  13573. // Collisions
  13574. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13575. this._generatePointsArray();
  13576. // Transformation
  13577. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13578. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13579. subMesh._lastColliderWorldVertices = [];
  13580. subMesh._trianglePlanes = [];
  13581. var start = subMesh.verticesStart;
  13582. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13583. for (var i = start; i < end; i++) {
  13584. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13585. }
  13586. }
  13587. // Collide
  13588. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13589. if (collider.collisionFound) {
  13590. collider.collidedMesh = this;
  13591. }
  13592. return this;
  13593. };
  13594. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13595. var subMeshes;
  13596. var len;
  13597. // Octrees
  13598. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13599. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13600. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13601. len = intersections.length;
  13602. subMeshes = intersections.data;
  13603. }
  13604. else {
  13605. subMeshes = this.subMeshes;
  13606. len = subMeshes.length;
  13607. }
  13608. for (var index = 0; index < len; index++) {
  13609. var subMesh = subMeshes[index];
  13610. // Bounding test
  13611. if (len > 1 && !subMesh._checkCollision(collider))
  13612. continue;
  13613. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13614. }
  13615. return this;
  13616. };
  13617. AbstractMesh.prototype._checkCollision = function (collider) {
  13618. // Bounding box test
  13619. if (!this._boundingInfo._checkCollision(collider))
  13620. return this;
  13621. // Transformation matrix
  13622. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13623. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13624. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13625. return this;
  13626. };
  13627. // Picking
  13628. AbstractMesh.prototype._generatePointsArray = function () {
  13629. return false;
  13630. };
  13631. /**
  13632. * Checks if the passed Ray intersects with the mesh.
  13633. * Returns an object PickingInfo.
  13634. */
  13635. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13636. var pickingInfo = new BABYLON.PickingInfo();
  13637. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13638. return pickingInfo;
  13639. }
  13640. if (!this._generatePointsArray()) {
  13641. return pickingInfo;
  13642. }
  13643. var intersectInfo = null;
  13644. // Octrees
  13645. var subMeshes;
  13646. var len;
  13647. if (this._submeshesOctree && this.useOctreeForPicking) {
  13648. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13649. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13650. len = intersections.length;
  13651. subMeshes = intersections.data;
  13652. }
  13653. else {
  13654. subMeshes = this.subMeshes;
  13655. len = subMeshes.length;
  13656. }
  13657. for (var index = 0; index < len; index++) {
  13658. var subMesh = subMeshes[index];
  13659. // Bounding test
  13660. if (len > 1 && !subMesh.canIntersects(ray))
  13661. continue;
  13662. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13663. if (currentIntersectInfo) {
  13664. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13665. intersectInfo = currentIntersectInfo;
  13666. intersectInfo.subMeshId = index;
  13667. if (fastCheck) {
  13668. break;
  13669. }
  13670. }
  13671. }
  13672. }
  13673. if (intersectInfo) {
  13674. // Get picked point
  13675. var world = this.getWorldMatrix();
  13676. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13677. var direction = ray.direction.clone();
  13678. direction = direction.scale(intersectInfo.distance);
  13679. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13680. var pickedPoint = worldOrigin.add(worldDirection);
  13681. // Return result
  13682. pickingInfo.hit = true;
  13683. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13684. pickingInfo.pickedPoint = pickedPoint;
  13685. pickingInfo.pickedMesh = this;
  13686. pickingInfo.bu = intersectInfo.bu;
  13687. pickingInfo.bv = intersectInfo.bv;
  13688. pickingInfo.faceId = intersectInfo.faceId;
  13689. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13690. return pickingInfo;
  13691. }
  13692. return pickingInfo;
  13693. };
  13694. /**
  13695. * Clones the mesh, used by the class Mesh.
  13696. * Just returns `null` for an AbstractMesh.
  13697. */
  13698. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13699. return null;
  13700. };
  13701. /**
  13702. * Disposes all the mesh submeshes.
  13703. * Returns the AbstractMesh.
  13704. */
  13705. AbstractMesh.prototype.releaseSubMeshes = function () {
  13706. if (this.subMeshes) {
  13707. while (this.subMeshes.length) {
  13708. this.subMeshes[0].dispose();
  13709. }
  13710. }
  13711. else {
  13712. this.subMeshes = new Array();
  13713. }
  13714. return this;
  13715. };
  13716. /**
  13717. * Disposes the AbstractMesh.
  13718. * Some internal references are kept for further use.
  13719. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13720. * Returns nothing.
  13721. */
  13722. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13723. var _this = this;
  13724. var index;
  13725. // Action manager
  13726. if (this.actionManager) {
  13727. this.actionManager.dispose();
  13728. this.actionManager = null;
  13729. }
  13730. // Skeleton
  13731. this.skeleton = null;
  13732. // Animations
  13733. this.getScene().stopAnimation(this);
  13734. // Physics
  13735. if (this.physicsImpostor) {
  13736. this.physicsImpostor.dispose();
  13737. }
  13738. // Intersections in progress
  13739. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13740. var other = this._intersectionsInProgress[index];
  13741. var pos = other._intersectionsInProgress.indexOf(this);
  13742. other._intersectionsInProgress.splice(pos, 1);
  13743. }
  13744. this._intersectionsInProgress = [];
  13745. // Lights
  13746. var lights = this.getScene().lights;
  13747. lights.forEach(function (light) {
  13748. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13749. if (meshIndex !== -1) {
  13750. light.includedOnlyMeshes.splice(meshIndex, 1);
  13751. }
  13752. meshIndex = light.excludedMeshes.indexOf(_this);
  13753. if (meshIndex !== -1) {
  13754. light.excludedMeshes.splice(meshIndex, 1);
  13755. }
  13756. // Shadow generators
  13757. var generator = light.getShadowGenerator();
  13758. if (generator) {
  13759. var shadowMap = generator.getShadowMap();
  13760. meshIndex = shadowMap.renderList.indexOf(_this);
  13761. if (meshIndex !== -1) {
  13762. shadowMap.renderList.splice(meshIndex, 1);
  13763. }
  13764. }
  13765. });
  13766. // Edges
  13767. if (this._edgesRenderer) {
  13768. this._edgesRenderer.dispose();
  13769. this._edgesRenderer = null;
  13770. }
  13771. // SubMeshes
  13772. if (this.getClassName() !== "InstancedMesh") {
  13773. this.releaseSubMeshes();
  13774. }
  13775. // Octree
  13776. var sceneOctree = this.getScene().selectionOctree;
  13777. if (sceneOctree) {
  13778. var index = sceneOctree.dynamicContent.indexOf(this);
  13779. if (index !== -1) {
  13780. sceneOctree.dynamicContent.splice(index, 1);
  13781. }
  13782. }
  13783. // Query
  13784. var engine = this.getScene().getEngine();
  13785. if (this._occlusionQuery) {
  13786. this._isOcclusionQueryInProgress = false;
  13787. engine.deleteQuery(this._occlusionQuery);
  13788. this._occlusionQuery = null;
  13789. }
  13790. // Engine
  13791. engine.wipeCaches();
  13792. // Remove from scene
  13793. this.getScene().removeMesh(this);
  13794. if (!doNotRecurse) {
  13795. // Particles
  13796. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13797. if (this.getScene().particleSystems[index].emitter === this) {
  13798. this.getScene().particleSystems[index].dispose();
  13799. index--;
  13800. }
  13801. }
  13802. // Children
  13803. var objects = this.getDescendants(true);
  13804. for (index = 0; index < objects.length; index++) {
  13805. objects[index].dispose();
  13806. }
  13807. }
  13808. else {
  13809. var childMeshes = this.getChildMeshes(true);
  13810. for (index = 0; index < childMeshes.length; index++) {
  13811. var child = childMeshes[index];
  13812. child.parent = null;
  13813. child.computeWorldMatrix(true);
  13814. }
  13815. }
  13816. // facet data
  13817. if (this._facetDataEnabled) {
  13818. this.disableFacetData();
  13819. }
  13820. this.onAfterWorldMatrixUpdateObservable.clear();
  13821. this.onCollideObservable.clear();
  13822. this.onCollisionPositionChangeObservable.clear();
  13823. this._isDisposed = true;
  13824. _super.prototype.dispose.call(this);
  13825. };
  13826. /**
  13827. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13828. * This Vector3 is expressed in the World space.
  13829. */
  13830. AbstractMesh.prototype.getDirection = function (localAxis) {
  13831. var result = BABYLON.Vector3.Zero();
  13832. this.getDirectionToRef(localAxis, result);
  13833. return result;
  13834. };
  13835. /**
  13836. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13837. * localAxis is expressed in the mesh local space.
  13838. * result is computed in the Wordl space from the mesh World matrix.
  13839. * Returns the AbstractMesh.
  13840. */
  13841. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13842. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13843. return this;
  13844. };
  13845. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13846. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13847. if (this.getScene().getRenderId() == 0) {
  13848. this.computeWorldMatrix(true);
  13849. }
  13850. var wm = this.getWorldMatrix();
  13851. if (space == BABYLON.Space.WORLD) {
  13852. var tmat = BABYLON.Tmp.Matrix[0];
  13853. wm.invertToRef(tmat);
  13854. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13855. }
  13856. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13857. this._pivotMatrix.m[12] = -point.x;
  13858. this._pivotMatrix.m[13] = -point.y;
  13859. this._pivotMatrix.m[14] = -point.z;
  13860. this._cache.pivotMatrixUpdated = true;
  13861. return this;
  13862. };
  13863. /**
  13864. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13865. */
  13866. AbstractMesh.prototype.getPivotPoint = function () {
  13867. var point = BABYLON.Vector3.Zero();
  13868. this.getPivotPointToRef(point);
  13869. return point;
  13870. };
  13871. /**
  13872. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13873. * Returns the AbstractMesh.
  13874. */
  13875. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13876. result.x = -this._pivotMatrix.m[12];
  13877. result.y = -this._pivotMatrix.m[13];
  13878. result.z = -this._pivotMatrix.m[14];
  13879. return this;
  13880. };
  13881. /**
  13882. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13883. */
  13884. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13885. var point = BABYLON.Vector3.Zero();
  13886. this.getAbsolutePivotPointToRef(point);
  13887. return point;
  13888. };
  13889. /**
  13890. * Defines the passed mesh as the parent of the current mesh.
  13891. * Returns the AbstractMesh.
  13892. */
  13893. AbstractMesh.prototype.setParent = function (mesh) {
  13894. var child = this;
  13895. var parent = mesh;
  13896. if (mesh == null) {
  13897. var rotation = BABYLON.Tmp.Quaternion[0];
  13898. var position = BABYLON.Tmp.Vector3[0];
  13899. var scale = BABYLON.Tmp.Vector3[1];
  13900. child.getWorldMatrix().decompose(scale, rotation, position);
  13901. if (child.rotationQuaternion) {
  13902. child.rotationQuaternion.copyFrom(rotation);
  13903. }
  13904. else {
  13905. rotation.toEulerAnglesToRef(child.rotation);
  13906. }
  13907. child.position.x = position.x;
  13908. child.position.y = position.y;
  13909. child.position.z = position.z;
  13910. }
  13911. else {
  13912. var position = BABYLON.Tmp.Vector3[0];
  13913. var m1 = BABYLON.Tmp.Matrix[0];
  13914. parent.getWorldMatrix().invertToRef(m1);
  13915. BABYLON.Vector3.TransformCoordinatesToRef(child.position, m1, position);
  13916. child.position.copyFrom(position);
  13917. }
  13918. child.parent = parent;
  13919. return this;
  13920. };
  13921. /**
  13922. * Adds the passed mesh as a child to the current mesh.
  13923. * Returns the AbstractMesh.
  13924. */
  13925. AbstractMesh.prototype.addChild = function (mesh) {
  13926. mesh.setParent(this);
  13927. return this;
  13928. };
  13929. /**
  13930. * Removes the passed mesh from the current mesh children list.
  13931. * Returns the AbstractMesh.
  13932. */
  13933. AbstractMesh.prototype.removeChild = function (mesh) {
  13934. mesh.setParent(null);
  13935. return this;
  13936. };
  13937. /**
  13938. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13939. * Returns the AbstractMesh.
  13940. */
  13941. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13942. result.x = this._pivotMatrix.m[12];
  13943. result.y = this._pivotMatrix.m[13];
  13944. result.z = this._pivotMatrix.m[14];
  13945. this.getPivotPointToRef(result);
  13946. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13947. return this;
  13948. };
  13949. // Facet data
  13950. /**
  13951. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13952. * Returns the AbstractMesh.
  13953. */
  13954. AbstractMesh.prototype._initFacetData = function () {
  13955. if (!this._facetNormals) {
  13956. this._facetNormals = new Array();
  13957. }
  13958. if (!this._facetPositions) {
  13959. this._facetPositions = new Array();
  13960. }
  13961. if (!this._facetPartitioning) {
  13962. this._facetPartitioning = new Array();
  13963. }
  13964. this._facetNb = this.getIndices().length / 3;
  13965. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13966. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13967. for (var f = 0; f < this._facetNb; f++) {
  13968. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13969. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13970. }
  13971. this._facetDataEnabled = true;
  13972. return this;
  13973. };
  13974. /**
  13975. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13976. * This method can be called within the render loop.
  13977. * 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.
  13978. * Returns the AbstractMesh.
  13979. */
  13980. AbstractMesh.prototype.updateFacetData = function () {
  13981. if (!this._facetDataEnabled) {
  13982. this._initFacetData();
  13983. }
  13984. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13985. var indices = this.getIndices();
  13986. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13987. var bInfo = this.getBoundingInfo();
  13988. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13989. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13990. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13991. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13992. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13993. this._subDiv.max = this._partitioningSubdivisions;
  13994. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13995. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13996. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13997. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13998. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13999. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  14000. // set the parameters for ComputeNormals()
  14001. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  14002. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  14003. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  14004. this._facetParameters.bInfo = bInfo;
  14005. this._facetParameters.bbSize = this._bbSize;
  14006. this._facetParameters.subDiv = this._subDiv;
  14007. this._facetParameters.ratio = this.partitioningBBoxRatio;
  14008. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  14009. return this;
  14010. };
  14011. /**
  14012. * Returns the facetLocalNormals array.
  14013. * The normals are expressed in the mesh local space.
  14014. */
  14015. AbstractMesh.prototype.getFacetLocalNormals = function () {
  14016. if (!this._facetNormals) {
  14017. this.updateFacetData();
  14018. }
  14019. return this._facetNormals;
  14020. };
  14021. /**
  14022. * Returns the facetLocalPositions array.
  14023. * The facet positions are expressed in the mesh local space.
  14024. */
  14025. AbstractMesh.prototype.getFacetLocalPositions = function () {
  14026. if (!this._facetPositions) {
  14027. this.updateFacetData();
  14028. }
  14029. return this._facetPositions;
  14030. };
  14031. /**
  14032. * Returns the facetLocalPartioning array.
  14033. */
  14034. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  14035. if (!this._facetPartitioning) {
  14036. this.updateFacetData();
  14037. }
  14038. return this._facetPartitioning;
  14039. };
  14040. /**
  14041. * Returns the i-th facet position in the world system.
  14042. * This method allocates a new Vector3 per call.
  14043. */
  14044. AbstractMesh.prototype.getFacetPosition = function (i) {
  14045. var pos = BABYLON.Vector3.Zero();
  14046. this.getFacetPositionToRef(i, pos);
  14047. return pos;
  14048. };
  14049. /**
  14050. * Sets the reference Vector3 with the i-th facet position in the world system.
  14051. * Returns the AbstractMesh.
  14052. */
  14053. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  14054. var localPos = (this.getFacetLocalPositions())[i];
  14055. var world = this.getWorldMatrix();
  14056. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  14057. return this;
  14058. };
  14059. /**
  14060. * Returns the i-th facet normal in the world system.
  14061. * This method allocates a new Vector3 per call.
  14062. */
  14063. AbstractMesh.prototype.getFacetNormal = function (i) {
  14064. var norm = BABYLON.Vector3.Zero();
  14065. this.getFacetNormalToRef(i, norm);
  14066. return norm;
  14067. };
  14068. /**
  14069. * Sets the reference Vector3 with the i-th facet normal in the world system.
  14070. * Returns the AbstractMesh.
  14071. */
  14072. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  14073. var localNorm = (this.getFacetLocalNormals())[i];
  14074. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  14075. return this;
  14076. };
  14077. /**
  14078. * 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).
  14079. */
  14080. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  14081. var bInfo = this.getBoundingInfo();
  14082. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  14083. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  14084. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  14085. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  14086. return null;
  14087. }
  14088. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  14089. };
  14090. /**
  14091. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  14092. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  14093. * 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.
  14094. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14095. * 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.
  14096. */
  14097. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  14098. if (checkFace === void 0) { checkFace = false; }
  14099. if (facing === void 0) { facing = true; }
  14100. var world = this.getWorldMatrix();
  14101. var invMat = BABYLON.Tmp.Matrix[5];
  14102. world.invertToRef(invMat);
  14103. var invVect = BABYLON.Tmp.Vector3[8];
  14104. var closest = null;
  14105. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  14106. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  14107. if (projected) {
  14108. // tranform the local computed projected vector to world coordinates
  14109. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  14110. }
  14111. return closest;
  14112. };
  14113. /**
  14114. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  14115. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  14116. * 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.
  14117. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14118. * 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.
  14119. */
  14120. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  14121. if (checkFace === void 0) { checkFace = false; }
  14122. if (facing === void 0) { facing = true; }
  14123. var closest = null;
  14124. var tmpx = 0.0;
  14125. var tmpy = 0.0;
  14126. var tmpz = 0.0;
  14127. var d = 0.0; // tmp dot facet normal * facet position
  14128. var t0 = 0.0;
  14129. var projx = 0.0;
  14130. var projy = 0.0;
  14131. var projz = 0.0;
  14132. // Get all the facets in the same partitioning block than (x, y, z)
  14133. var facetPositions = this.getFacetLocalPositions();
  14134. var facetNormals = this.getFacetLocalNormals();
  14135. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  14136. if (!facetsInBlock) {
  14137. return null;
  14138. }
  14139. // Get the closest facet to (x, y, z)
  14140. var shortest = Number.MAX_VALUE; // init distance vars
  14141. var tmpDistance = shortest;
  14142. var fib; // current facet in the block
  14143. var norm; // current facet normal
  14144. var p0; // current facet barycenter position
  14145. // loop on all the facets in the current partitioning block
  14146. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  14147. fib = facetsInBlock[idx];
  14148. norm = facetNormals[fib];
  14149. p0 = facetPositions[fib];
  14150. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  14151. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  14152. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  14153. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  14154. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  14155. projx = x + norm.x * t0;
  14156. projy = y + norm.y * t0;
  14157. projz = z + norm.z * t0;
  14158. tmpx = projx - x;
  14159. tmpy = projy - y;
  14160. tmpz = projz - z;
  14161. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  14162. if (tmpDistance < shortest) {
  14163. shortest = tmpDistance;
  14164. closest = fib;
  14165. if (projected) {
  14166. projected.x = projx;
  14167. projected.y = projy;
  14168. projected.z = projz;
  14169. }
  14170. }
  14171. }
  14172. }
  14173. return closest;
  14174. };
  14175. /**
  14176. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  14177. */
  14178. AbstractMesh.prototype.getFacetDataParameters = function () {
  14179. return this._facetParameters;
  14180. };
  14181. /**
  14182. * Disables the feature FacetData and frees the related memory.
  14183. * Returns the AbstractMesh.
  14184. */
  14185. AbstractMesh.prototype.disableFacetData = function () {
  14186. if (this._facetDataEnabled) {
  14187. this._facetDataEnabled = false;
  14188. this._facetPositions = null;
  14189. this._facetNormals = null;
  14190. this._facetPartitioning = null;
  14191. this._facetParameters = null;
  14192. }
  14193. return this;
  14194. };
  14195. /**
  14196. * Creates new normals data for the mesh.
  14197. * @param updatable.
  14198. */
  14199. AbstractMesh.prototype.createNormals = function (updatable) {
  14200. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14201. var indices = this.getIndices();
  14202. var normals;
  14203. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14204. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14205. }
  14206. else {
  14207. normals = [];
  14208. }
  14209. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  14210. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  14211. };
  14212. AbstractMesh.prototype.checkOcclusionQuery = function () {
  14213. var engine = this.getEngine();
  14214. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  14215. this._isOccluded = false;
  14216. return;
  14217. }
  14218. if (this.isOcclusionQueryInProgress) {
  14219. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  14220. if (isOcclusionQueryAvailable) {
  14221. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  14222. this._isOcclusionQueryInProgress = false;
  14223. this._occlusionInternalRetryCounter = 0;
  14224. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  14225. }
  14226. else {
  14227. this._occlusionInternalRetryCounter++;
  14228. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  14229. this._isOcclusionQueryInProgress = false;
  14230. this._occlusionInternalRetryCounter = 0;
  14231. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  14232. // if strict continue the last state of the object.
  14233. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  14234. }
  14235. else {
  14236. return;
  14237. }
  14238. }
  14239. }
  14240. var scene = this.getScene();
  14241. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  14242. if (!this._occlusionQuery) {
  14243. this._occlusionQuery = engine.createQuery();
  14244. }
  14245. engine.beginQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  14246. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  14247. engine.endQuery(this.occlusionQueryAlgorithmType);
  14248. this._isOcclusionQueryInProgress = true;
  14249. };
  14250. // Statics
  14251. AbstractMesh._BILLBOARDMODE_NONE = 0;
  14252. AbstractMesh._BILLBOARDMODE_X = 1;
  14253. AbstractMesh._BILLBOARDMODE_Y = 2;
  14254. AbstractMesh._BILLBOARDMODE_Z = 4;
  14255. AbstractMesh._BILLBOARDMODE_ALL = 7;
  14256. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  14257. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  14258. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  14259. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  14260. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  14261. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  14262. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14263. return AbstractMesh;
  14264. }(BABYLON.Node));
  14265. BABYLON.AbstractMesh = AbstractMesh;
  14266. })(BABYLON || (BABYLON = {}));
  14267. //# sourceMappingURL=babylon.abstractMesh.js.map
  14268. var BABYLON;
  14269. (function (BABYLON) {
  14270. var Light = (function (_super) {
  14271. __extends(Light, _super);
  14272. /**
  14273. * Creates a Light object in the scene.
  14274. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14275. */
  14276. function Light(name, scene) {
  14277. var _this = _super.call(this, name, scene) || this;
  14278. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  14279. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  14280. _this.intensity = 1.0;
  14281. _this.range = Number.MAX_VALUE;
  14282. /**
  14283. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  14284. * of light.
  14285. */
  14286. _this._photometricScale = 1.0;
  14287. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  14288. _this._radius = 0.00001;
  14289. _this.renderPriority = 0;
  14290. /**
  14291. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  14292. * the current shadow generator.
  14293. */
  14294. _this.shadowEnabled = true;
  14295. _this._excludeWithLayerMask = 0;
  14296. _this._includeOnlyWithLayerMask = 0;
  14297. _this._lightmapMode = 0;
  14298. _this._excludedMeshesIds = new Array();
  14299. _this._includedOnlyMeshesIds = new Array();
  14300. _this.getScene().addLight(_this);
  14301. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  14302. _this._buildUniformLayout();
  14303. _this.includedOnlyMeshes = new Array();
  14304. _this.excludedMeshes = new Array();
  14305. _this._resyncMeshes();
  14306. return _this;
  14307. }
  14308. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  14309. /**
  14310. * If every light affecting the material is in this lightmapMode,
  14311. * material.lightmapTexture adds or multiplies
  14312. * (depends on material.useLightmapAsShadowmap)
  14313. * after every other light calculations.
  14314. */
  14315. get: function () {
  14316. return Light._LIGHTMAP_DEFAULT;
  14317. },
  14318. enumerable: true,
  14319. configurable: true
  14320. });
  14321. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  14322. /**
  14323. * material.lightmapTexture as only diffuse lighting from this light
  14324. * adds pnly specular lighting from this light
  14325. * adds dynamic shadows
  14326. */
  14327. get: function () {
  14328. return Light._LIGHTMAP_SPECULAR;
  14329. },
  14330. enumerable: true,
  14331. configurable: true
  14332. });
  14333. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  14334. /**
  14335. * material.lightmapTexture as only lighting
  14336. * no light calculation from this light
  14337. * only adds dynamic shadows from this light
  14338. */
  14339. get: function () {
  14340. return Light._LIGHTMAP_SHADOWSONLY;
  14341. },
  14342. enumerable: true,
  14343. configurable: true
  14344. });
  14345. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  14346. /**
  14347. * Each light type uses the default quantity according to its type:
  14348. * point/spot lights use luminous intensity
  14349. * directional lights use illuminance
  14350. */
  14351. get: function () {
  14352. return Light._INTENSITYMODE_AUTOMATIC;
  14353. },
  14354. enumerable: true,
  14355. configurable: true
  14356. });
  14357. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  14358. /**
  14359. * lumen (lm)
  14360. */
  14361. get: function () {
  14362. return Light._INTENSITYMODE_LUMINOUSPOWER;
  14363. },
  14364. enumerable: true,
  14365. configurable: true
  14366. });
  14367. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  14368. /**
  14369. * candela (lm/sr)
  14370. */
  14371. get: function () {
  14372. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  14373. },
  14374. enumerable: true,
  14375. configurable: true
  14376. });
  14377. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  14378. /**
  14379. * lux (lm/m^2)
  14380. */
  14381. get: function () {
  14382. return Light._INTENSITYMODE_ILLUMINANCE;
  14383. },
  14384. enumerable: true,
  14385. configurable: true
  14386. });
  14387. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  14388. /**
  14389. * nit (cd/m^2)
  14390. */
  14391. get: function () {
  14392. return Light._INTENSITYMODE_LUMINANCE;
  14393. },
  14394. enumerable: true,
  14395. configurable: true
  14396. });
  14397. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  14398. /**
  14399. * Light type const id of the point light.
  14400. */
  14401. get: function () {
  14402. return Light._LIGHTTYPEID_POINTLIGHT;
  14403. },
  14404. enumerable: true,
  14405. configurable: true
  14406. });
  14407. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  14408. /**
  14409. * Light type const id of the directional light.
  14410. */
  14411. get: function () {
  14412. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  14413. },
  14414. enumerable: true,
  14415. configurable: true
  14416. });
  14417. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  14418. /**
  14419. * Light type const id of the spot light.
  14420. */
  14421. get: function () {
  14422. return Light._LIGHTTYPEID_SPOTLIGHT;
  14423. },
  14424. enumerable: true,
  14425. configurable: true
  14426. });
  14427. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  14428. /**
  14429. * Light type const id of the hemispheric light.
  14430. */
  14431. get: function () {
  14432. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  14433. },
  14434. enumerable: true,
  14435. configurable: true
  14436. });
  14437. Object.defineProperty(Light.prototype, "intensityMode", {
  14438. /**
  14439. * Gets the photometric scale used to interpret the intensity.
  14440. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14441. */
  14442. get: function () {
  14443. return this._intensityMode;
  14444. },
  14445. /**
  14446. * Sets the photometric scale used to interpret the intensity.
  14447. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14448. */
  14449. set: function (value) {
  14450. this._intensityMode = value;
  14451. this._computePhotometricScale();
  14452. },
  14453. enumerable: true,
  14454. configurable: true
  14455. });
  14456. ;
  14457. ;
  14458. Object.defineProperty(Light.prototype, "radius", {
  14459. /**
  14460. * Gets the light radius used by PBR Materials to simulate soft area lights.
  14461. */
  14462. get: function () {
  14463. return this._radius;
  14464. },
  14465. /**
  14466. * sets the light radius used by PBR Materials to simulate soft area lights.
  14467. */
  14468. set: function (value) {
  14469. this._radius = value;
  14470. this._computePhotometricScale();
  14471. },
  14472. enumerable: true,
  14473. configurable: true
  14474. });
  14475. ;
  14476. ;
  14477. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  14478. get: function () {
  14479. return this._includedOnlyMeshes;
  14480. },
  14481. set: function (value) {
  14482. this._includedOnlyMeshes = value;
  14483. this._hookArrayForIncludedOnly(value);
  14484. },
  14485. enumerable: true,
  14486. configurable: true
  14487. });
  14488. Object.defineProperty(Light.prototype, "excludedMeshes", {
  14489. get: function () {
  14490. return this._excludedMeshes;
  14491. },
  14492. set: function (value) {
  14493. this._excludedMeshes = value;
  14494. this._hookArrayForExcluded(value);
  14495. },
  14496. enumerable: true,
  14497. configurable: true
  14498. });
  14499. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  14500. get: function () {
  14501. return this._excludeWithLayerMask;
  14502. },
  14503. set: function (value) {
  14504. this._excludeWithLayerMask = value;
  14505. this._resyncMeshes();
  14506. },
  14507. enumerable: true,
  14508. configurable: true
  14509. });
  14510. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  14511. get: function () {
  14512. return this._includeOnlyWithLayerMask;
  14513. },
  14514. set: function (value) {
  14515. this._includeOnlyWithLayerMask = value;
  14516. this._resyncMeshes();
  14517. },
  14518. enumerable: true,
  14519. configurable: true
  14520. });
  14521. Object.defineProperty(Light.prototype, "lightmapMode", {
  14522. get: function () {
  14523. return this._lightmapMode;
  14524. },
  14525. set: function (value) {
  14526. if (this._lightmapMode === value) {
  14527. return;
  14528. }
  14529. this._lightmapMode = value;
  14530. this._markMeshesAsLightDirty();
  14531. },
  14532. enumerable: true,
  14533. configurable: true
  14534. });
  14535. Light.prototype._buildUniformLayout = function () {
  14536. // Overridden
  14537. };
  14538. /**
  14539. * Returns the string "Light".
  14540. */
  14541. Light.prototype.getClassName = function () {
  14542. return "Light";
  14543. };
  14544. /**
  14545. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14546. */
  14547. Light.prototype.toString = function (fullDetails) {
  14548. var ret = "Name: " + this.name;
  14549. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  14550. if (this.animations) {
  14551. for (var i = 0; i < this.animations.length; i++) {
  14552. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14553. }
  14554. }
  14555. if (fullDetails) {
  14556. }
  14557. return ret;
  14558. };
  14559. /**
  14560. * Set the enabled state of this node.
  14561. * @param {boolean} value - the new enabled state
  14562. * @see isEnabled
  14563. */
  14564. Light.prototype.setEnabled = function (value) {
  14565. _super.prototype.setEnabled.call(this, value);
  14566. this._resyncMeshes();
  14567. };
  14568. /**
  14569. * Returns the Light associated shadow generator.
  14570. */
  14571. Light.prototype.getShadowGenerator = function () {
  14572. return this._shadowGenerator;
  14573. };
  14574. /**
  14575. * Returns a Vector3, the absolute light position in the World.
  14576. */
  14577. Light.prototype.getAbsolutePosition = function () {
  14578. return BABYLON.Vector3.Zero();
  14579. };
  14580. Light.prototype.transferToEffect = function (effect, lightIndex) {
  14581. };
  14582. Light.prototype._getWorldMatrix = function () {
  14583. return BABYLON.Matrix.Identity();
  14584. };
  14585. /**
  14586. * Boolean : True if the light will affect the passed mesh.
  14587. */
  14588. Light.prototype.canAffectMesh = function (mesh) {
  14589. if (!mesh) {
  14590. return true;
  14591. }
  14592. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  14593. return false;
  14594. }
  14595. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  14596. return false;
  14597. }
  14598. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  14599. return false;
  14600. }
  14601. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  14602. return false;
  14603. }
  14604. return true;
  14605. };
  14606. /**
  14607. * Returns the light World matrix.
  14608. */
  14609. Light.prototype.getWorldMatrix = function () {
  14610. this._currentRenderId = this.getScene().getRenderId();
  14611. var worldMatrix = this._getWorldMatrix();
  14612. if (this.parent && this.parent.getWorldMatrix) {
  14613. if (!this._parentedWorldMatrix) {
  14614. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  14615. }
  14616. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  14617. this._markSyncedWithParent();
  14618. return this._parentedWorldMatrix;
  14619. }
  14620. return worldMatrix;
  14621. };
  14622. /**
  14623. * Sort function to order lights for rendering.
  14624. * @param a First Light object to compare to second.
  14625. * @param b Second Light object to compare first.
  14626. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  14627. */
  14628. Light.compareLightsPriority = function (a, b) {
  14629. //shadow-casting lights have priority over non-shadow-casting lights
  14630. //the renderPrioirty is a secondary sort criterion
  14631. if (a.shadowEnabled !== b.shadowEnabled) {
  14632. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  14633. }
  14634. return b.renderPriority - a.renderPriority;
  14635. };
  14636. /**
  14637. * Disposes the light.
  14638. */
  14639. Light.prototype.dispose = function () {
  14640. if (this._shadowGenerator) {
  14641. this._shadowGenerator.dispose();
  14642. this._shadowGenerator = null;
  14643. }
  14644. // Animations
  14645. this.getScene().stopAnimation(this);
  14646. // Remove from meshes
  14647. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14648. var mesh = _a[_i];
  14649. mesh._removeLightSource(this);
  14650. }
  14651. this._uniformBuffer.dispose();
  14652. // Remove from scene
  14653. this.getScene().removeLight(this);
  14654. _super.prototype.dispose.call(this);
  14655. };
  14656. /**
  14657. * Returns the light type ID (integer).
  14658. */
  14659. Light.prototype.getTypeID = function () {
  14660. return 0;
  14661. };
  14662. /**
  14663. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  14664. */
  14665. Light.prototype.getScaledIntensity = function () {
  14666. return this._photometricScale * this.intensity;
  14667. };
  14668. /**
  14669. * Returns a new Light object, named "name", from the current one.
  14670. */
  14671. Light.prototype.clone = function (name) {
  14672. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  14673. };
  14674. /**
  14675. * Serializes the current light into a Serialization object.
  14676. * Returns the serialized object.
  14677. */
  14678. Light.prototype.serialize = function () {
  14679. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14680. // Type
  14681. serializationObject.type = this.getTypeID();
  14682. // Parent
  14683. if (this.parent) {
  14684. serializationObject.parentId = this.parent.id;
  14685. }
  14686. // Inclusion / exclusions
  14687. if (this.excludedMeshes.length > 0) {
  14688. serializationObject.excludedMeshesIds = [];
  14689. this.excludedMeshes.forEach(function (mesh) {
  14690. serializationObject.excludedMeshesIds.push(mesh.id);
  14691. });
  14692. }
  14693. if (this.includedOnlyMeshes.length > 0) {
  14694. serializationObject.includedOnlyMeshesIds = [];
  14695. this.includedOnlyMeshes.forEach(function (mesh) {
  14696. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  14697. });
  14698. }
  14699. // Animations
  14700. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14701. serializationObject.ranges = this.serializeAnimationRanges();
  14702. return serializationObject;
  14703. };
  14704. /**
  14705. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  14706. * This new light is named "name" and added to the passed scene.
  14707. */
  14708. Light.GetConstructorFromName = function (type, name, scene) {
  14709. switch (type) {
  14710. case 0:
  14711. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  14712. case 1:
  14713. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  14714. case 2:
  14715. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14716. case 3:
  14717. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14718. }
  14719. };
  14720. /**
  14721. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14722. */
  14723. Light.Parse = function (parsedLight, scene) {
  14724. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14725. // Inclusion / exclusions
  14726. if (parsedLight.excludedMeshesIds) {
  14727. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14728. }
  14729. if (parsedLight.includedOnlyMeshesIds) {
  14730. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14731. }
  14732. // Parent
  14733. if (parsedLight.parentId) {
  14734. light._waitingParentId = parsedLight.parentId;
  14735. }
  14736. // Animations
  14737. if (parsedLight.animations) {
  14738. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14739. var parsedAnimation = parsedLight.animations[animationIndex];
  14740. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14741. }
  14742. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14743. }
  14744. if (parsedLight.autoAnimate) {
  14745. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14746. }
  14747. return light;
  14748. };
  14749. Light.prototype._hookArrayForExcluded = function (array) {
  14750. var _this = this;
  14751. var oldPush = array.push;
  14752. array.push = function () {
  14753. var items = [];
  14754. for (var _i = 0; _i < arguments.length; _i++) {
  14755. items[_i] = arguments[_i];
  14756. }
  14757. var result = oldPush.apply(array, items);
  14758. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  14759. var item = items_1[_a];
  14760. item._resyncLighSource(_this);
  14761. }
  14762. return result;
  14763. };
  14764. var oldSplice = array.splice;
  14765. array.splice = function (index, deleteCount) {
  14766. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14767. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  14768. var item = deleted_1[_i];
  14769. item._resyncLighSource(_this);
  14770. }
  14771. return deleted;
  14772. };
  14773. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  14774. var item = array_1[_i];
  14775. item._resyncLighSource(this);
  14776. }
  14777. };
  14778. Light.prototype._hookArrayForIncludedOnly = function (array) {
  14779. var _this = this;
  14780. var oldPush = array.push;
  14781. array.push = function () {
  14782. var items = [];
  14783. for (var _i = 0; _i < arguments.length; _i++) {
  14784. items[_i] = arguments[_i];
  14785. }
  14786. var result = oldPush.apply(array, items);
  14787. _this._resyncMeshes();
  14788. return result;
  14789. };
  14790. var oldSplice = array.splice;
  14791. array.splice = function (index, deleteCount) {
  14792. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14793. _this._resyncMeshes();
  14794. return deleted;
  14795. };
  14796. this._resyncMeshes();
  14797. };
  14798. Light.prototype._resyncMeshes = function () {
  14799. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14800. var mesh = _a[_i];
  14801. mesh._resyncLighSource(this);
  14802. }
  14803. };
  14804. Light.prototype._markMeshesAsLightDirty = function () {
  14805. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14806. var mesh = _a[_i];
  14807. if (mesh._lightSources.indexOf(this) !== -1) {
  14808. mesh._markSubMeshesAsLightDirty();
  14809. }
  14810. }
  14811. };
  14812. /**
  14813. * Recomputes the cached photometric scale if needed.
  14814. */
  14815. Light.prototype._computePhotometricScale = function () {
  14816. this._photometricScale = this._getPhotometricScale();
  14817. this.getScene().resetCachedMaterial();
  14818. };
  14819. /**
  14820. * Returns the Photometric Scale according to the light type and intensity mode.
  14821. */
  14822. Light.prototype._getPhotometricScale = function () {
  14823. var photometricScale = 0.0;
  14824. var lightTypeID = this.getTypeID();
  14825. //get photometric mode
  14826. var photometricMode = this.intensityMode;
  14827. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  14828. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  14829. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  14830. }
  14831. else {
  14832. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  14833. }
  14834. }
  14835. //compute photometric scale
  14836. switch (lightTypeID) {
  14837. case Light.LIGHTTYPEID_POINTLIGHT:
  14838. case Light.LIGHTTYPEID_SPOTLIGHT:
  14839. switch (photometricMode) {
  14840. case Light.INTENSITYMODE_LUMINOUSPOWER:
  14841. photometricScale = 1.0 / (4.0 * Math.PI);
  14842. break;
  14843. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  14844. photometricScale = 1.0;
  14845. break;
  14846. case Light.INTENSITYMODE_LUMINANCE:
  14847. photometricScale = this.radius * this.radius;
  14848. break;
  14849. }
  14850. break;
  14851. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  14852. switch (photometricMode) {
  14853. case Light.INTENSITYMODE_ILLUMINANCE:
  14854. photometricScale = 1.0;
  14855. break;
  14856. case Light.INTENSITYMODE_LUMINANCE:
  14857. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  14858. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  14859. var apexAngleRadians = this.radius;
  14860. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  14861. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  14862. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  14863. photometricScale = solidAngle;
  14864. break;
  14865. }
  14866. break;
  14867. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  14868. // No fall off in hemisperic light.
  14869. photometricScale = 1.0;
  14870. break;
  14871. }
  14872. return photometricScale;
  14873. };
  14874. Light.prototype._reorderLightsInScene = function () {
  14875. var scene = this.getScene();
  14876. if (this.renderPriority != 0) {
  14877. scene.requireLightSorting = true;
  14878. }
  14879. this.getScene().sortLightsByPriority();
  14880. };
  14881. //lightmapMode Consts
  14882. Light._LIGHTMAP_DEFAULT = 0;
  14883. Light._LIGHTMAP_SPECULAR = 1;
  14884. Light._LIGHTMAP_SHADOWSONLY = 2;
  14885. // Intensity Mode Consts
  14886. Light._INTENSITYMODE_AUTOMATIC = 0;
  14887. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  14888. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  14889. Light._INTENSITYMODE_ILLUMINANCE = 3;
  14890. Light._INTENSITYMODE_LUMINANCE = 4;
  14891. // Light types ids const.
  14892. Light._LIGHTTYPEID_POINTLIGHT = 0;
  14893. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  14894. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  14895. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  14896. __decorate([
  14897. BABYLON.serializeAsColor3()
  14898. ], Light.prototype, "diffuse", void 0);
  14899. __decorate([
  14900. BABYLON.serializeAsColor3()
  14901. ], Light.prototype, "specular", void 0);
  14902. __decorate([
  14903. BABYLON.serialize()
  14904. ], Light.prototype, "intensity", void 0);
  14905. __decorate([
  14906. BABYLON.serialize()
  14907. ], Light.prototype, "range", void 0);
  14908. __decorate([
  14909. BABYLON.serialize()
  14910. ], Light.prototype, "intensityMode", null);
  14911. __decorate([
  14912. BABYLON.serialize()
  14913. ], Light.prototype, "radius", null);
  14914. __decorate([
  14915. BABYLON.serialize()
  14916. ], Light.prototype, "_renderPriority", void 0);
  14917. __decorate([
  14918. BABYLON.expandToProperty("_reorderLightsInScene")
  14919. ], Light.prototype, "renderPriority", void 0);
  14920. __decorate([
  14921. BABYLON.serialize()
  14922. ], Light.prototype, "shadowEnabled", void 0);
  14923. __decorate([
  14924. BABYLON.serialize("excludeWithLayerMask")
  14925. ], Light.prototype, "_excludeWithLayerMask", void 0);
  14926. __decorate([
  14927. BABYLON.serialize("includeOnlyWithLayerMask")
  14928. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  14929. __decorate([
  14930. BABYLON.serialize("lightmapMode")
  14931. ], Light.prototype, "_lightmapMode", void 0);
  14932. return Light;
  14933. }(BABYLON.Node));
  14934. BABYLON.Light = Light;
  14935. })(BABYLON || (BABYLON = {}));
  14936. //# sourceMappingURL=babylon.light.js.map
  14937. var BABYLON;
  14938. (function (BABYLON) {
  14939. var Camera = (function (_super) {
  14940. __extends(Camera, _super);
  14941. function Camera(name, position, scene) {
  14942. var _this = _super.call(this, name, scene) || this;
  14943. _this.upVector = BABYLON.Vector3.Up();
  14944. _this.orthoLeft = null;
  14945. _this.orthoRight = null;
  14946. _this.orthoBottom = null;
  14947. _this.orthoTop = null;
  14948. _this.fov = 0.8;
  14949. _this.minZ = 1;
  14950. _this.maxZ = 10000.0;
  14951. _this.inertia = 0.9;
  14952. _this.mode = Camera.PERSPECTIVE_CAMERA;
  14953. _this.isIntermediate = false;
  14954. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  14955. _this.layerMask = 0x0FFFFFFF;
  14956. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  14957. // Camera rig members
  14958. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  14959. _this._rigCameras = new Array();
  14960. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  14961. _this.customRenderTargets = new Array();
  14962. // Observables
  14963. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  14964. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  14965. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  14966. _this.onRestoreStateObservable = new BABYLON.Observable();
  14967. // Cache
  14968. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  14969. _this._projectionMatrix = new BABYLON.Matrix();
  14970. _this._doNotComputeProjectionMatrix = false;
  14971. _this._postProcesses = new Array();
  14972. _this._transformMatrix = BABYLON.Matrix.Zero();
  14973. _this._activeMeshes = new BABYLON.SmartArray(256);
  14974. _this._globalPosition = BABYLON.Vector3.Zero();
  14975. _this._refreshFrustumPlanes = true;
  14976. _this.getScene().addCamera(_this);
  14977. if (!_this.getScene().activeCamera) {
  14978. _this.getScene().activeCamera = _this;
  14979. }
  14980. _this.position = position;
  14981. return _this;
  14982. }
  14983. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  14984. get: function () {
  14985. return Camera._PERSPECTIVE_CAMERA;
  14986. },
  14987. enumerable: true,
  14988. configurable: true
  14989. });
  14990. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  14991. get: function () {
  14992. return Camera._ORTHOGRAPHIC_CAMERA;
  14993. },
  14994. enumerable: true,
  14995. configurable: true
  14996. });
  14997. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  14998. get: function () {
  14999. return Camera._FOVMODE_VERTICAL_FIXED;
  15000. },
  15001. enumerable: true,
  15002. configurable: true
  15003. });
  15004. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15005. get: function () {
  15006. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15007. },
  15008. enumerable: true,
  15009. configurable: true
  15010. });
  15011. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15012. get: function () {
  15013. return Camera._RIG_MODE_NONE;
  15014. },
  15015. enumerable: true,
  15016. configurable: true
  15017. });
  15018. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15019. get: function () {
  15020. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15021. },
  15022. enumerable: true,
  15023. configurable: true
  15024. });
  15025. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15026. get: function () {
  15027. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15028. },
  15029. enumerable: true,
  15030. configurable: true
  15031. });
  15032. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15033. get: function () {
  15034. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15035. },
  15036. enumerable: true,
  15037. configurable: true
  15038. });
  15039. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15040. get: function () {
  15041. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15042. },
  15043. enumerable: true,
  15044. configurable: true
  15045. });
  15046. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15047. get: function () {
  15048. return Camera._RIG_MODE_VR;
  15049. },
  15050. enumerable: true,
  15051. configurable: true
  15052. });
  15053. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15054. get: function () {
  15055. return Camera._RIG_MODE_WEBVR;
  15056. },
  15057. enumerable: true,
  15058. configurable: true
  15059. });
  15060. /**
  15061. * Store current camera state (fov, position, etc..)
  15062. */
  15063. Camera.prototype.storeState = function () {
  15064. this._stateStored = true;
  15065. this._storedFov = this.fov;
  15066. return this;
  15067. };
  15068. /**
  15069. * Restores the camera state values if it has been stored. You must call storeState() first
  15070. */
  15071. Camera.prototype._restoreStateValues = function () {
  15072. if (!this._stateStored) {
  15073. return false;
  15074. }
  15075. this.fov = this._storedFov;
  15076. return true;
  15077. };
  15078. /**
  15079. * Restored camera state. You must call storeState() first
  15080. */
  15081. Camera.prototype.restoreState = function () {
  15082. if (this._restoreStateValues()) {
  15083. this.onRestoreStateObservable.notifyObservers(this);
  15084. return true;
  15085. }
  15086. return false;
  15087. };
  15088. Camera.prototype.getClassName = function () {
  15089. return "Camera";
  15090. };
  15091. /**
  15092. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15093. */
  15094. Camera.prototype.toString = function (fullDetails) {
  15095. var ret = "Name: " + this.name;
  15096. ret += ", type: " + this.getClassName();
  15097. if (this.animations) {
  15098. for (var i = 0; i < this.animations.length; i++) {
  15099. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15100. }
  15101. }
  15102. if (fullDetails) {
  15103. }
  15104. return ret;
  15105. };
  15106. Object.defineProperty(Camera.prototype, "globalPosition", {
  15107. get: function () {
  15108. return this._globalPosition;
  15109. },
  15110. enumerable: true,
  15111. configurable: true
  15112. });
  15113. Camera.prototype.getActiveMeshes = function () {
  15114. return this._activeMeshes;
  15115. };
  15116. Camera.prototype.isActiveMesh = function (mesh) {
  15117. return (this._activeMeshes.indexOf(mesh) !== -1);
  15118. };
  15119. //Cache
  15120. Camera.prototype._initCache = function () {
  15121. _super.prototype._initCache.call(this);
  15122. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15123. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15124. this._cache.mode = undefined;
  15125. this._cache.minZ = undefined;
  15126. this._cache.maxZ = undefined;
  15127. this._cache.fov = undefined;
  15128. this._cache.fovMode = undefined;
  15129. this._cache.aspectRatio = undefined;
  15130. this._cache.orthoLeft = undefined;
  15131. this._cache.orthoRight = undefined;
  15132. this._cache.orthoBottom = undefined;
  15133. this._cache.orthoTop = undefined;
  15134. this._cache.renderWidth = undefined;
  15135. this._cache.renderHeight = undefined;
  15136. };
  15137. Camera.prototype._updateCache = function (ignoreParentClass) {
  15138. if (!ignoreParentClass) {
  15139. _super.prototype._updateCache.call(this);
  15140. }
  15141. var engine = this.getEngine();
  15142. this._cache.position.copyFrom(this.position);
  15143. this._cache.upVector.copyFrom(this.upVector);
  15144. this._cache.mode = this.mode;
  15145. this._cache.minZ = this.minZ;
  15146. this._cache.maxZ = this.maxZ;
  15147. this._cache.fov = this.fov;
  15148. this._cache.fovMode = this.fovMode;
  15149. this._cache.aspectRatio = engine.getAspectRatio(this);
  15150. this._cache.orthoLeft = this.orthoLeft;
  15151. this._cache.orthoRight = this.orthoRight;
  15152. this._cache.orthoBottom = this.orthoBottom;
  15153. this._cache.orthoTop = this.orthoTop;
  15154. this._cache.renderWidth = engine.getRenderWidth();
  15155. this._cache.renderHeight = engine.getRenderHeight();
  15156. };
  15157. Camera.prototype._updateFromScene = function () {
  15158. this.updateCache();
  15159. this.update();
  15160. };
  15161. // Synchronized
  15162. Camera.prototype._isSynchronized = function () {
  15163. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15164. };
  15165. Camera.prototype._isSynchronizedViewMatrix = function () {
  15166. if (!_super.prototype._isSynchronized.call(this))
  15167. return false;
  15168. return this._cache.position.equals(this.position)
  15169. && this._cache.upVector.equals(this.upVector)
  15170. && this.isSynchronizedWithParent();
  15171. };
  15172. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15173. var check = this._cache.mode === this.mode
  15174. && this._cache.minZ === this.minZ
  15175. && this._cache.maxZ === this.maxZ;
  15176. if (!check) {
  15177. return false;
  15178. }
  15179. var engine = this.getEngine();
  15180. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15181. check = this._cache.fov === this.fov
  15182. && this._cache.fovMode === this.fovMode
  15183. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15184. }
  15185. else {
  15186. check = this._cache.orthoLeft === this.orthoLeft
  15187. && this._cache.orthoRight === this.orthoRight
  15188. && this._cache.orthoBottom === this.orthoBottom
  15189. && this._cache.orthoTop === this.orthoTop
  15190. && this._cache.renderWidth === engine.getRenderWidth()
  15191. && this._cache.renderHeight === engine.getRenderHeight();
  15192. }
  15193. return check;
  15194. };
  15195. // Controls
  15196. Camera.prototype.attachControl = function (element, noPreventDefault) {
  15197. };
  15198. Camera.prototype.detachControl = function (element) {
  15199. };
  15200. Camera.prototype.update = function () {
  15201. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15202. this._updateRigCameras();
  15203. }
  15204. this._checkInputs();
  15205. };
  15206. Camera.prototype._checkInputs = function () {
  15207. this.onAfterCheckInputsObservable.notifyObservers(this);
  15208. };
  15209. Object.defineProperty(Camera.prototype, "rigCameras", {
  15210. get: function () {
  15211. return this._rigCameras;
  15212. },
  15213. enumerable: true,
  15214. configurable: true
  15215. });
  15216. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  15217. get: function () {
  15218. return this._rigPostProcess;
  15219. },
  15220. enumerable: true,
  15221. configurable: true
  15222. });
  15223. Camera.prototype._cascadePostProcessesToRigCams = function () {
  15224. // invalidate framebuffer
  15225. if (this._postProcesses.length > 0) {
  15226. this._postProcesses[0].markTextureDirty();
  15227. }
  15228. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  15229. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  15230. var cam = this._rigCameras[i];
  15231. var rigPostProcess = cam._rigPostProcess;
  15232. // for VR rig, there does not have to be a post process
  15233. if (rigPostProcess) {
  15234. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  15235. if (isPass) {
  15236. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  15237. cam.isIntermediate = this._postProcesses.length === 0;
  15238. }
  15239. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  15240. rigPostProcess.markTextureDirty();
  15241. }
  15242. else {
  15243. cam._postProcesses = this._postProcesses.slice(0);
  15244. }
  15245. }
  15246. };
  15247. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15248. if (insertAt === void 0) { insertAt = null; }
  15249. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15250. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15251. return 0;
  15252. }
  15253. if (insertAt == null || insertAt < 0) {
  15254. this._postProcesses.push(postProcess);
  15255. }
  15256. else {
  15257. this._postProcesses.splice(insertAt, 0, postProcess);
  15258. }
  15259. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15260. return this._postProcesses.indexOf(postProcess);
  15261. };
  15262. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15263. if (atIndices === void 0) { atIndices = null; }
  15264. var result = [];
  15265. var i;
  15266. var index;
  15267. if (!atIndices) {
  15268. var idx = this._postProcesses.indexOf(postProcess);
  15269. if (idx !== -1) {
  15270. this._postProcesses.splice(idx, 1);
  15271. }
  15272. }
  15273. else {
  15274. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  15275. // iterate descending, so can just splice as we go
  15276. for (i = atIndices.length - 1; i >= 0; i--) {
  15277. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15278. result.push(i);
  15279. continue;
  15280. }
  15281. index = atIndices[i];
  15282. this._postProcesses.splice(index, 1);
  15283. }
  15284. }
  15285. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15286. return result;
  15287. };
  15288. Camera.prototype.getWorldMatrix = function () {
  15289. if (!this._worldMatrix) {
  15290. this._worldMatrix = BABYLON.Matrix.Identity();
  15291. }
  15292. var viewMatrix = this.getViewMatrix();
  15293. viewMatrix.invertToRef(this._worldMatrix);
  15294. return this._worldMatrix;
  15295. };
  15296. Camera.prototype._getViewMatrix = function () {
  15297. return BABYLON.Matrix.Identity();
  15298. };
  15299. Camera.prototype.getViewMatrix = function (force) {
  15300. if (!force && this._isSynchronizedViewMatrix()) {
  15301. return this._computedViewMatrix;
  15302. }
  15303. this._computedViewMatrix = this._getViewMatrix();
  15304. this._currentRenderId = this.getScene().getRenderId();
  15305. this._refreshFrustumPlanes = true;
  15306. if (!this.parent || !this.parent.getWorldMatrix) {
  15307. this._globalPosition.copyFrom(this.position);
  15308. }
  15309. else {
  15310. if (!this._worldMatrix) {
  15311. this._worldMatrix = BABYLON.Matrix.Identity();
  15312. }
  15313. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15314. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15315. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15316. this._computedViewMatrix.invert();
  15317. this._markSyncedWithParent();
  15318. }
  15319. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15320. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15321. }
  15322. this.onViewMatrixChangedObservable.notifyObservers(this);
  15323. return this._computedViewMatrix;
  15324. };
  15325. Camera.prototype.freezeProjectionMatrix = function (projection) {
  15326. this._doNotComputeProjectionMatrix = true;
  15327. if (projection !== undefined) {
  15328. this._projectionMatrix = projection;
  15329. }
  15330. };
  15331. ;
  15332. Camera.prototype.unfreezeProjectionMatrix = function () {
  15333. this._doNotComputeProjectionMatrix = false;
  15334. };
  15335. ;
  15336. Camera.prototype.getProjectionMatrix = function (force) {
  15337. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  15338. return this._projectionMatrix;
  15339. }
  15340. this._refreshFrustumPlanes = true;
  15341. var engine = this.getEngine();
  15342. var scene = this.getScene();
  15343. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15344. if (this.minZ <= 0) {
  15345. this.minZ = 0.1;
  15346. }
  15347. if (scene.useRightHandedSystem) {
  15348. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15349. }
  15350. else {
  15351. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15352. }
  15353. }
  15354. else {
  15355. var halfWidth = engine.getRenderWidth() / 2.0;
  15356. var halfHeight = engine.getRenderHeight() / 2.0;
  15357. if (scene.useRightHandedSystem) {
  15358. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15359. }
  15360. else {
  15361. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15362. }
  15363. }
  15364. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  15365. return this._projectionMatrix;
  15366. };
  15367. Camera.prototype.getTranformationMatrix = function () {
  15368. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15369. return this._transformMatrix;
  15370. };
  15371. Camera.prototype.updateFrustumPlanes = function () {
  15372. if (!this._refreshFrustumPlanes) {
  15373. return;
  15374. }
  15375. this.getTranformationMatrix();
  15376. if (!this._frustumPlanes) {
  15377. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15378. }
  15379. else {
  15380. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15381. }
  15382. this._refreshFrustumPlanes = false;
  15383. };
  15384. Camera.prototype.isInFrustum = function (target) {
  15385. this.updateFrustumPlanes();
  15386. return target.isInFrustum(this._frustumPlanes);
  15387. };
  15388. Camera.prototype.isCompletelyInFrustum = function (target) {
  15389. this.updateFrustumPlanes();
  15390. return target.isCompletelyInFrustum(this._frustumPlanes);
  15391. };
  15392. Camera.prototype.getForwardRay = function (length, transform, origin) {
  15393. if (length === void 0) { length = 100; }
  15394. if (!transform) {
  15395. transform = this.getWorldMatrix();
  15396. }
  15397. if (!origin) {
  15398. origin = this.position;
  15399. }
  15400. var forward = new BABYLON.Vector3(0, 0, 1);
  15401. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  15402. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  15403. return new BABYLON.Ray(origin, direction, length);
  15404. };
  15405. Camera.prototype.dispose = function () {
  15406. // Observables
  15407. this.onViewMatrixChangedObservable.clear();
  15408. this.onProjectionMatrixChangedObservable.clear();
  15409. this.onAfterCheckInputsObservable.clear();
  15410. this.onRestoreStateObservable.clear();
  15411. // Inputs
  15412. if (this.inputs) {
  15413. this.inputs.clear();
  15414. }
  15415. // Animations
  15416. this.getScene().stopAnimation(this);
  15417. // Remove from scene
  15418. this.getScene().removeCamera(this);
  15419. while (this._rigCameras.length > 0) {
  15420. this._rigCameras.pop().dispose();
  15421. }
  15422. // Postprocesses
  15423. var i = this._postProcesses.length;
  15424. while (--i >= 0) {
  15425. this._postProcesses[i].dispose(this);
  15426. }
  15427. // Render targets
  15428. var i = this.customRenderTargets.length;
  15429. while (--i >= 0) {
  15430. this.customRenderTargets[i].dispose();
  15431. }
  15432. this.customRenderTargets = [];
  15433. // Active Meshes
  15434. this._activeMeshes.dispose();
  15435. _super.prototype.dispose.call(this);
  15436. };
  15437. Object.defineProperty(Camera.prototype, "leftCamera", {
  15438. // ---- Camera rigs section ----
  15439. get: function () {
  15440. if (this._rigCameras.length < 1) {
  15441. return undefined;
  15442. }
  15443. return this._rigCameras[0];
  15444. },
  15445. enumerable: true,
  15446. configurable: true
  15447. });
  15448. Object.defineProperty(Camera.prototype, "rightCamera", {
  15449. get: function () {
  15450. if (this._rigCameras.length < 2) {
  15451. return undefined;
  15452. }
  15453. return this._rigCameras[1];
  15454. },
  15455. enumerable: true,
  15456. configurable: true
  15457. });
  15458. Camera.prototype.getLeftTarget = function () {
  15459. if (this._rigCameras.length < 1) {
  15460. return undefined;
  15461. }
  15462. return this._rigCameras[0].getTarget();
  15463. };
  15464. Camera.prototype.getRightTarget = function () {
  15465. if (this._rigCameras.length < 2) {
  15466. return undefined;
  15467. }
  15468. return this._rigCameras[1].getTarget();
  15469. };
  15470. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  15471. while (this._rigCameras.length > 0) {
  15472. this._rigCameras.pop().dispose();
  15473. }
  15474. this.cameraRigMode = mode;
  15475. this._cameraRigParams = {};
  15476. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  15477. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  15478. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  15479. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  15480. // create the rig cameras, unless none
  15481. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15482. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  15483. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  15484. }
  15485. switch (this.cameraRigMode) {
  15486. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15487. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15488. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  15489. break;
  15490. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15491. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15492. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15493. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15494. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15495. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  15496. break;
  15497. case Camera.RIG_MODE_VR:
  15498. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  15499. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  15500. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15501. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15502. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  15503. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  15504. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  15505. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  15506. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15507. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15508. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  15509. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  15510. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  15511. if (metrics.compensateDistortion) {
  15512. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  15513. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  15514. }
  15515. break;
  15516. case Camera.RIG_MODE_WEBVR:
  15517. if (rigParams.vrDisplay) {
  15518. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  15519. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  15520. //Left eye
  15521. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15522. this._rigCameras[0].setCameraRigParameter("left", true);
  15523. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  15524. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  15525. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  15526. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15527. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15528. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15529. this._rigCameras[0].parent = this;
  15530. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  15531. //Right eye
  15532. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15533. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  15534. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  15535. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  15536. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15537. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15538. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15539. this._rigCameras[1].parent = this;
  15540. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  15541. }
  15542. break;
  15543. }
  15544. this._cascadePostProcessesToRigCams();
  15545. this.
  15546. update();
  15547. };
  15548. Camera.prototype._getVRProjectionMatrix = function () {
  15549. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  15550. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  15551. return this._projectionMatrix;
  15552. };
  15553. Camera.prototype._updateCameraRotationMatrix = function () {
  15554. //Here for WebVR
  15555. };
  15556. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  15557. //Here for WebVR
  15558. };
  15559. /**
  15560. * This function MUST be overwritten by the different WebVR cameras available.
  15561. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15562. */
  15563. Camera.prototype._getWebVRProjectionMatrix = function () {
  15564. return BABYLON.Matrix.Identity();
  15565. };
  15566. /**
  15567. * This function MUST be overwritten by the different WebVR cameras available.
  15568. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15569. */
  15570. Camera.prototype._getWebVRViewMatrix = function () {
  15571. return BABYLON.Matrix.Identity();
  15572. };
  15573. Camera.prototype.setCameraRigParameter = function (name, value) {
  15574. if (!this._cameraRigParams) {
  15575. this._cameraRigParams = {};
  15576. }
  15577. this._cameraRigParams[name] = value;
  15578. //provisionnally:
  15579. if (name === "interaxialDistance") {
  15580. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  15581. }
  15582. };
  15583. /**
  15584. * needs to be overridden by children so sub has required properties to be copied
  15585. */
  15586. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  15587. return null;
  15588. };
  15589. /**
  15590. * May need to be overridden by children
  15591. */
  15592. Camera.prototype._updateRigCameras = function () {
  15593. for (var i = 0; i < this._rigCameras.length; i++) {
  15594. this._rigCameras[i].minZ = this.minZ;
  15595. this._rigCameras[i].maxZ = this.maxZ;
  15596. this._rigCameras[i].fov = this.fov;
  15597. }
  15598. // only update viewport when ANAGLYPH
  15599. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  15600. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  15601. }
  15602. };
  15603. Camera.prototype._setupInputs = function () {
  15604. };
  15605. Camera.prototype.serialize = function () {
  15606. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15607. // Type
  15608. serializationObject.type = this.getClassName();
  15609. // Parent
  15610. if (this.parent) {
  15611. serializationObject.parentId = this.parent.id;
  15612. }
  15613. if (this.inputs) {
  15614. this.inputs.serialize(serializationObject);
  15615. }
  15616. // Animations
  15617. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15618. serializationObject.ranges = this.serializeAnimationRanges();
  15619. return serializationObject;
  15620. };
  15621. Camera.prototype.clone = function (name) {
  15622. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  15623. };
  15624. Camera.prototype.getDirection = function (localAxis) {
  15625. var result = BABYLON.Vector3.Zero();
  15626. this.getDirectionToRef(localAxis, result);
  15627. return result;
  15628. };
  15629. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  15630. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15631. };
  15632. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  15633. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  15634. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  15635. switch (type) {
  15636. case "ArcRotateCamera":
  15637. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  15638. case "DeviceOrientationCamera":
  15639. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  15640. case "FollowCamera":
  15641. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  15642. case "ArcFollowCamera":
  15643. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  15644. case "GamepadCamera":
  15645. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15646. case "TouchCamera":
  15647. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  15648. case "VirtualJoysticksCamera":
  15649. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  15650. case "WebVRFreeCamera":
  15651. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15652. case "WebVRGamepadCamera":
  15653. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15654. case "VRDeviceOrientationFreeCamera":
  15655. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15656. case "VRDeviceOrientationGamepadCamera":
  15657. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15658. case "AnaglyphArcRotateCamera":
  15659. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15660. case "AnaglyphFreeCamera":
  15661. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15662. case "AnaglyphGamepadCamera":
  15663. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15664. case "AnaglyphUniversalCamera":
  15665. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15666. case "StereoscopicArcRotateCamera":
  15667. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15668. case "StereoscopicFreeCamera":
  15669. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15670. case "StereoscopicGamepadCamera":
  15671. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15672. case "StereoscopicUniversalCamera":
  15673. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15674. case "FreeCamera":// Forcing Universal here
  15675. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15676. default:// Universal Camera is the default value
  15677. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15678. }
  15679. };
  15680. Camera.Parse = function (parsedCamera, scene) {
  15681. var type = parsedCamera.type;
  15682. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  15683. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  15684. // Parent
  15685. if (parsedCamera.parentId) {
  15686. camera._waitingParentId = parsedCamera.parentId;
  15687. }
  15688. //If camera has an input manager, let it parse inputs settings
  15689. if (camera.inputs) {
  15690. camera.inputs.parse(parsedCamera);
  15691. camera._setupInputs();
  15692. }
  15693. if (camera.setPosition) {
  15694. camera.position.copyFromFloats(0, 0, 0);
  15695. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  15696. }
  15697. // Target
  15698. if (parsedCamera.target) {
  15699. if (camera.setTarget) {
  15700. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15701. }
  15702. }
  15703. // Apply 3d rig, when found
  15704. if (parsedCamera.cameraRigMode) {
  15705. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  15706. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  15707. }
  15708. // Animations
  15709. if (parsedCamera.animations) {
  15710. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15711. var parsedAnimation = parsedCamera.animations[animationIndex];
  15712. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15713. }
  15714. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  15715. }
  15716. if (parsedCamera.autoAnimate) {
  15717. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  15718. }
  15719. return camera;
  15720. };
  15721. // Statics
  15722. Camera._PERSPECTIVE_CAMERA = 0;
  15723. Camera._ORTHOGRAPHIC_CAMERA = 1;
  15724. Camera._FOVMODE_VERTICAL_FIXED = 0;
  15725. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  15726. Camera._RIG_MODE_NONE = 0;
  15727. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  15728. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  15729. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  15730. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  15731. Camera._RIG_MODE_VR = 20;
  15732. Camera._RIG_MODE_WEBVR = 21;
  15733. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  15734. __decorate([
  15735. BABYLON.serializeAsVector3()
  15736. ], Camera.prototype, "position", void 0);
  15737. __decorate([
  15738. BABYLON.serializeAsVector3()
  15739. ], Camera.prototype, "upVector", void 0);
  15740. __decorate([
  15741. BABYLON.serialize()
  15742. ], Camera.prototype, "orthoLeft", void 0);
  15743. __decorate([
  15744. BABYLON.serialize()
  15745. ], Camera.prototype, "orthoRight", void 0);
  15746. __decorate([
  15747. BABYLON.serialize()
  15748. ], Camera.prototype, "orthoBottom", void 0);
  15749. __decorate([
  15750. BABYLON.serialize()
  15751. ], Camera.prototype, "orthoTop", void 0);
  15752. __decorate([
  15753. BABYLON.serialize()
  15754. ], Camera.prototype, "fov", void 0);
  15755. __decorate([
  15756. BABYLON.serialize()
  15757. ], Camera.prototype, "minZ", void 0);
  15758. __decorate([
  15759. BABYLON.serialize()
  15760. ], Camera.prototype, "maxZ", void 0);
  15761. __decorate([
  15762. BABYLON.serialize()
  15763. ], Camera.prototype, "inertia", void 0);
  15764. __decorate([
  15765. BABYLON.serialize()
  15766. ], Camera.prototype, "mode", void 0);
  15767. __decorate([
  15768. BABYLON.serialize()
  15769. ], Camera.prototype, "layerMask", void 0);
  15770. __decorate([
  15771. BABYLON.serialize()
  15772. ], Camera.prototype, "fovMode", void 0);
  15773. __decorate([
  15774. BABYLON.serialize()
  15775. ], Camera.prototype, "cameraRigMode", void 0);
  15776. __decorate([
  15777. BABYLON.serialize()
  15778. ], Camera.prototype, "interaxialDistance", void 0);
  15779. __decorate([
  15780. BABYLON.serialize()
  15781. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  15782. return Camera;
  15783. }(BABYLON.Node));
  15784. BABYLON.Camera = Camera;
  15785. })(BABYLON || (BABYLON = {}));
  15786. //# sourceMappingURL=babylon.camera.js.map
  15787. var BABYLON;
  15788. (function (BABYLON) {
  15789. var RenderingManager = (function () {
  15790. function RenderingManager(scene) {
  15791. this._renderingGroups = new Array();
  15792. this._autoClearDepthStencil = {};
  15793. this._customOpaqueSortCompareFn = {};
  15794. this._customAlphaTestSortCompareFn = {};
  15795. this._customTransparentSortCompareFn = {};
  15796. this._renderinGroupInfo = null;
  15797. this._scene = scene;
  15798. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15799. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  15800. }
  15801. }
  15802. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  15803. if (depth === void 0) { depth = true; }
  15804. if (stencil === void 0) { stencil = true; }
  15805. if (this._depthStencilBufferAlreadyCleaned) {
  15806. return;
  15807. }
  15808. this._scene.getEngine().clear(null, false, depth, stencil);
  15809. this._depthStencilBufferAlreadyCleaned = true;
  15810. };
  15811. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15812. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  15813. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  15814. var info = null;
  15815. if (observable) {
  15816. if (!this._renderinGroupInfo) {
  15817. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  15818. }
  15819. info = this._renderinGroupInfo;
  15820. info.scene = this._scene;
  15821. info.camera = this._scene.activeCamera;
  15822. }
  15823. // Dispatch sprites
  15824. if (renderSprites) {
  15825. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  15826. var manager = this._scene.spriteManagers[index];
  15827. this.dispatchSprites(manager);
  15828. }
  15829. }
  15830. // Render
  15831. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15832. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15833. var renderingGroup = this._renderingGroups[index];
  15834. if (!renderingGroup && !observable)
  15835. continue;
  15836. this._currentIndex = index;
  15837. var renderingGroupMask = 0;
  15838. // Fire PRECLEAR stage
  15839. if (observable) {
  15840. renderingGroupMask = Math.pow(2, index);
  15841. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15842. info.renderingGroupId = index;
  15843. observable.notifyObservers(info, renderingGroupMask);
  15844. }
  15845. // Clear depth/stencil if needed
  15846. if (RenderingManager.AUTOCLEAR) {
  15847. var autoClear = this._autoClearDepthStencil[index];
  15848. if (autoClear && autoClear.autoClear) {
  15849. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  15850. }
  15851. }
  15852. if (observable) {
  15853. // Fire PREOPAQUE stage
  15854. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  15855. observable.notifyObservers(info, renderingGroupMask);
  15856. // Fire PRETRANSPARENT stage
  15857. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  15858. observable.notifyObservers(info, renderingGroupMask);
  15859. }
  15860. if (renderingGroup)
  15861. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  15862. // Fire POSTTRANSPARENT stage
  15863. if (observable) {
  15864. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15865. observable.notifyObservers(info, renderingGroupMask);
  15866. }
  15867. }
  15868. };
  15869. RenderingManager.prototype.reset = function () {
  15870. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15871. var renderingGroup = this._renderingGroups[index];
  15872. if (renderingGroup) {
  15873. renderingGroup.prepare();
  15874. }
  15875. }
  15876. };
  15877. RenderingManager.prototype.dispose = function () {
  15878. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15879. var renderingGroup = this._renderingGroups[index];
  15880. if (renderingGroup) {
  15881. renderingGroup.dispose();
  15882. }
  15883. }
  15884. this._renderingGroups.length = 0;
  15885. };
  15886. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  15887. if (!this._renderingGroups[renderingGroupId]) {
  15888. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15889. }
  15890. };
  15891. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  15892. var renderingGroupId = spriteManager.renderingGroupId || 0;
  15893. this._prepareRenderingGroup(renderingGroupId);
  15894. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  15895. };
  15896. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  15897. var renderingGroupId = particleSystem.renderingGroupId || 0;
  15898. this._prepareRenderingGroup(renderingGroupId);
  15899. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  15900. };
  15901. RenderingManager.prototype.dispatch = function (subMesh) {
  15902. var mesh = subMesh.getMesh();
  15903. var renderingGroupId = mesh.renderingGroupId || 0;
  15904. this._prepareRenderingGroup(renderingGroupId);
  15905. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15906. };
  15907. /**
  15908. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15909. * This allowed control for front to back rendering or reversly depending of the special needs.
  15910. *
  15911. * @param renderingGroupId The rendering group id corresponding to its index
  15912. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15913. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15914. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15915. */
  15916. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15917. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15918. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15919. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15920. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15921. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15922. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15923. if (this._renderingGroups[renderingGroupId]) {
  15924. var group = this._renderingGroups[renderingGroupId];
  15925. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15926. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15927. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15928. }
  15929. };
  15930. /**
  15931. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15932. *
  15933. * @param renderingGroupId The rendering group id corresponding to its index
  15934. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15935. * @param depth Automatically clears depth between groups if true and autoClear is true.
  15936. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  15937. */
  15938. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  15939. if (depth === void 0) { depth = true; }
  15940. if (stencil === void 0) { stencil = true; }
  15941. this._autoClearDepthStencil[renderingGroupId] = {
  15942. autoClear: autoClearDepthStencil,
  15943. depth: depth,
  15944. stencil: stencil
  15945. };
  15946. };
  15947. /**
  15948. * The max id used for rendering groups (not included)
  15949. */
  15950. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15951. /**
  15952. * The min id used for rendering groups (included)
  15953. */
  15954. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15955. /**
  15956. * Used to globally prevent autoclearing scenes.
  15957. */
  15958. RenderingManager.AUTOCLEAR = true;
  15959. return RenderingManager;
  15960. }());
  15961. BABYLON.RenderingManager = RenderingManager;
  15962. })(BABYLON || (BABYLON = {}));
  15963. //# sourceMappingURL=babylon.renderingManager.js.map
  15964. var BABYLON;
  15965. (function (BABYLON) {
  15966. var RenderingGroup = (function () {
  15967. /**
  15968. * Creates a new rendering group.
  15969. * @param index The rendering group index
  15970. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15971. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15972. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15973. */
  15974. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15975. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15976. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15977. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15978. this.index = index;
  15979. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15980. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15981. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15982. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  15983. this._particleSystems = new BABYLON.SmartArray(256);
  15984. this._spriteManagers = new BABYLON.SmartArray(256);
  15985. this._edgesRenderers = new BABYLON.SmartArray(16);
  15986. this._scene = scene;
  15987. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15988. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15989. this.transparentSortCompareFn = transparentSortCompareFn;
  15990. }
  15991. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15992. /**
  15993. * Set the opaque sort comparison function.
  15994. * If null the sub meshes will be render in the order they were created
  15995. */
  15996. set: function (value) {
  15997. this._opaqueSortCompareFn = value;
  15998. if (value) {
  15999. this._renderOpaque = this.renderOpaqueSorted;
  16000. }
  16001. else {
  16002. this._renderOpaque = RenderingGroup.renderUnsorted;
  16003. }
  16004. },
  16005. enumerable: true,
  16006. configurable: true
  16007. });
  16008. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16009. /**
  16010. * Set the alpha test sort comparison function.
  16011. * If null the sub meshes will be render in the order they were created
  16012. */
  16013. set: function (value) {
  16014. this._alphaTestSortCompareFn = value;
  16015. if (value) {
  16016. this._renderAlphaTest = this.renderAlphaTestSorted;
  16017. }
  16018. else {
  16019. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16020. }
  16021. },
  16022. enumerable: true,
  16023. configurable: true
  16024. });
  16025. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16026. /**
  16027. * Set the transparent sort comparison function.
  16028. * If null the sub meshes will be render in the order they were created
  16029. */
  16030. set: function (value) {
  16031. if (value) {
  16032. this._transparentSortCompareFn = value;
  16033. }
  16034. else {
  16035. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16036. }
  16037. this._renderTransparent = this.renderTransparentSorted;
  16038. },
  16039. enumerable: true,
  16040. configurable: true
  16041. });
  16042. /**
  16043. * Render all the sub meshes contained in the group.
  16044. * @param customRenderFunction Used to override the default render behaviour of the group.
  16045. * @returns true if rendered some submeshes.
  16046. */
  16047. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16048. if (customRenderFunction) {
  16049. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  16050. return;
  16051. }
  16052. var engine = this._scene.getEngine();
  16053. // Depth only
  16054. if (this._depthOnlySubMeshes.length !== 0) {
  16055. engine.setAlphaTesting(true);
  16056. engine.setColorWrite(false);
  16057. this._renderAlphaTest(this._depthOnlySubMeshes);
  16058. engine.setAlphaTesting(false);
  16059. engine.setColorWrite(true);
  16060. }
  16061. // Opaque
  16062. if (this._opaqueSubMeshes.length !== 0) {
  16063. this._renderOpaque(this._opaqueSubMeshes);
  16064. }
  16065. // Alpha test
  16066. if (this._alphaTestSubMeshes.length !== 0) {
  16067. engine.setAlphaTesting(true);
  16068. this._renderAlphaTest(this._alphaTestSubMeshes);
  16069. engine.setAlphaTesting(false);
  16070. }
  16071. var stencilState = engine.getStencilBuffer();
  16072. engine.setStencilBuffer(false);
  16073. // Sprites
  16074. if (renderSprites) {
  16075. this._renderSprites();
  16076. }
  16077. // Particles
  16078. if (renderParticles) {
  16079. this._renderParticles(activeMeshes);
  16080. }
  16081. if (this.onBeforeTransparentRendering) {
  16082. this.onBeforeTransparentRendering();
  16083. }
  16084. // Transparent
  16085. if (this._transparentSubMeshes.length !== 0) {
  16086. this._renderTransparent(this._transparentSubMeshes);
  16087. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16088. }
  16089. // Set back stencil to false in case it changes before the edge renderer.
  16090. engine.setStencilBuffer(false);
  16091. // Edges
  16092. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16093. this._edgesRenderers.data[edgesRendererIndex].render();
  16094. }
  16095. // Restore Stencil state.
  16096. engine.setStencilBuffer(stencilState);
  16097. };
  16098. /**
  16099. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16100. * @param subMeshes The submeshes to render
  16101. */
  16102. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16103. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16104. };
  16105. /**
  16106. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16107. * @param subMeshes The submeshes to render
  16108. */
  16109. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16110. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16111. };
  16112. /**
  16113. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16114. * @param subMeshes The submeshes to render
  16115. */
  16116. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16117. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  16118. };
  16119. /**
  16120. * Renders the submeshes in a specified order.
  16121. * @param subMeshes The submeshes to sort before render
  16122. * @param sortCompareFn The comparison function use to sort
  16123. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16124. * @param transparent Specifies to activate blending if true
  16125. */
  16126. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  16127. var subIndex = 0;
  16128. var subMesh;
  16129. for (; subIndex < subMeshes.length; subIndex++) {
  16130. subMesh = subMeshes.data[subIndex];
  16131. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16132. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16133. }
  16134. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16135. sortedArray.sort(sortCompareFn);
  16136. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16137. subMesh = sortedArray[subIndex];
  16138. if (transparent) {
  16139. var material = subMesh.getMaterial();
  16140. if (material.needDepthPrePass) {
  16141. var engine = material.getScene().getEngine();
  16142. engine.setColorWrite(false);
  16143. engine.setAlphaTesting(true);
  16144. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16145. subMesh.render(false);
  16146. engine.setAlphaTesting(false);
  16147. engine.setColorWrite(true);
  16148. }
  16149. }
  16150. subMesh.render(transparent);
  16151. }
  16152. };
  16153. /**
  16154. * Renders the submeshes in the order they were dispatched (no sort applied).
  16155. * @param subMeshes The submeshes to render
  16156. */
  16157. RenderingGroup.renderUnsorted = function (subMeshes) {
  16158. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16159. var submesh = subMeshes.data[subIndex];
  16160. submesh.render(false);
  16161. }
  16162. };
  16163. /**
  16164. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16165. * are rendered back to front if in the same alpha index.
  16166. *
  16167. * @param a The first submesh
  16168. * @param b The second submesh
  16169. * @returns The result of the comparison
  16170. */
  16171. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16172. // Alpha index first
  16173. if (a._alphaIndex > b._alphaIndex) {
  16174. return 1;
  16175. }
  16176. if (a._alphaIndex < b._alphaIndex) {
  16177. return -1;
  16178. }
  16179. // Then distance to camera
  16180. return RenderingGroup.backToFrontSortCompare(a, b);
  16181. };
  16182. /**
  16183. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16184. * are rendered back to front.
  16185. *
  16186. * @param a The first submesh
  16187. * @param b The second submesh
  16188. * @returns The result of the comparison
  16189. */
  16190. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16191. // Then distance to camera
  16192. if (a._distanceToCamera < b._distanceToCamera) {
  16193. return 1;
  16194. }
  16195. if (a._distanceToCamera > b._distanceToCamera) {
  16196. return -1;
  16197. }
  16198. return 0;
  16199. };
  16200. /**
  16201. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16202. * are rendered front to back (prevent overdraw).
  16203. *
  16204. * @param a The first submesh
  16205. * @param b The second submesh
  16206. * @returns The result of the comparison
  16207. */
  16208. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16209. // Then distance to camera
  16210. if (a._distanceToCamera < b._distanceToCamera) {
  16211. return -1;
  16212. }
  16213. if (a._distanceToCamera > b._distanceToCamera) {
  16214. return 1;
  16215. }
  16216. return 0;
  16217. };
  16218. /**
  16219. * Resets the different lists of submeshes to prepare a new frame.
  16220. */
  16221. RenderingGroup.prototype.prepare = function () {
  16222. this._opaqueSubMeshes.reset();
  16223. this._transparentSubMeshes.reset();
  16224. this._alphaTestSubMeshes.reset();
  16225. this._depthOnlySubMeshes.reset();
  16226. this._particleSystems.reset();
  16227. this._spriteManagers.reset();
  16228. this._edgesRenderers.reset();
  16229. };
  16230. RenderingGroup.prototype.dispose = function () {
  16231. this._opaqueSubMeshes.dispose();
  16232. this._transparentSubMeshes.dispose();
  16233. this._alphaTestSubMeshes.dispose();
  16234. this._depthOnlySubMeshes.dispose();
  16235. this._particleSystems.dispose();
  16236. this._spriteManagers.dispose();
  16237. this._edgesRenderers.dispose();
  16238. };
  16239. /**
  16240. * Inserts the submesh in its correct queue depending on its material.
  16241. * @param subMesh The submesh to dispatch
  16242. */
  16243. RenderingGroup.prototype.dispatch = function (subMesh) {
  16244. var material = subMesh.getMaterial();
  16245. var mesh = subMesh.getMesh();
  16246. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16247. this._transparentSubMeshes.push(subMesh);
  16248. }
  16249. else if (material.needAlphaTesting()) {
  16250. if (material.needDepthPrePass) {
  16251. this._depthOnlySubMeshes.push(subMesh);
  16252. }
  16253. this._alphaTestSubMeshes.push(subMesh);
  16254. }
  16255. else {
  16256. if (material.needDepthPrePass) {
  16257. this._depthOnlySubMeshes.push(subMesh);
  16258. }
  16259. this._opaqueSubMeshes.push(subMesh); // Opaque
  16260. }
  16261. if (mesh._edgesRenderer) {
  16262. this._edgesRenderers.push(mesh._edgesRenderer);
  16263. }
  16264. };
  16265. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  16266. this._spriteManagers.push(spriteManager);
  16267. };
  16268. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  16269. this._particleSystems.push(particleSystem);
  16270. };
  16271. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  16272. if (this._particleSystems.length === 0) {
  16273. return;
  16274. }
  16275. // Particles
  16276. var activeCamera = this._scene.activeCamera;
  16277. this._scene._particlesDuration.beginMonitoring();
  16278. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  16279. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16280. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16281. continue;
  16282. }
  16283. var emitter = particleSystem.emitter;
  16284. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  16285. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16286. }
  16287. }
  16288. this._scene._particlesDuration.endMonitoring(false);
  16289. };
  16290. RenderingGroup.prototype._renderSprites = function () {
  16291. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  16292. return;
  16293. }
  16294. // Sprites
  16295. var activeCamera = this._scene.activeCamera;
  16296. this._scene._spritesDuration.beginMonitoring();
  16297. for (var id = 0; id < this._spriteManagers.length; id++) {
  16298. var spriteManager = this._spriteManagers.data[id];
  16299. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16300. spriteManager.render();
  16301. }
  16302. }
  16303. this._scene._spritesDuration.endMonitoring(false);
  16304. };
  16305. return RenderingGroup;
  16306. }());
  16307. BABYLON.RenderingGroup = RenderingGroup;
  16308. })(BABYLON || (BABYLON = {}));
  16309. //# sourceMappingURL=babylon.renderingGroup.js.map
  16310. var BABYLON;
  16311. (function (BABYLON) {
  16312. var ClickInfo = (function () {
  16313. function ClickInfo() {
  16314. this._singleClick = false;
  16315. this._doubleClick = false;
  16316. this._hasSwiped = false;
  16317. this._ignore = false;
  16318. }
  16319. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  16320. get: function () {
  16321. return this._singleClick;
  16322. },
  16323. set: function (b) {
  16324. this._singleClick = b;
  16325. },
  16326. enumerable: true,
  16327. configurable: true
  16328. });
  16329. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  16330. get: function () {
  16331. return this._doubleClick;
  16332. },
  16333. set: function (b) {
  16334. this._doubleClick = b;
  16335. },
  16336. enumerable: true,
  16337. configurable: true
  16338. });
  16339. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  16340. get: function () {
  16341. return this._hasSwiped;
  16342. },
  16343. set: function (b) {
  16344. this._hasSwiped = b;
  16345. },
  16346. enumerable: true,
  16347. configurable: true
  16348. });
  16349. Object.defineProperty(ClickInfo.prototype, "ignore", {
  16350. get: function () {
  16351. return this._ignore;
  16352. },
  16353. set: function (b) {
  16354. this._ignore = b;
  16355. },
  16356. enumerable: true,
  16357. configurable: true
  16358. });
  16359. return ClickInfo;
  16360. }());
  16361. /**
  16362. * This class is used by the onRenderingGroupObservable
  16363. */
  16364. var RenderingGroupInfo = (function () {
  16365. function RenderingGroupInfo() {
  16366. }
  16367. /**
  16368. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16369. * This stage will be fired no matter what
  16370. */
  16371. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16372. /**
  16373. * Called before opaque object are rendered.
  16374. * This stage will be fired only if there's 3D Opaque content to render
  16375. */
  16376. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16377. /**
  16378. * Called after the opaque objects are rendered and before the transparent ones
  16379. * This stage will be fired only if there's 3D transparent content to render
  16380. */
  16381. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16382. /**
  16383. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16384. * This stage will be fired no matter what
  16385. */
  16386. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16387. return RenderingGroupInfo;
  16388. }());
  16389. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16390. /**
  16391. * Represents a scene to be rendered by the engine.
  16392. * @see http://doc.babylonjs.com/page.php?p=21911
  16393. */
  16394. var Scene = (function () {
  16395. /**
  16396. * @constructor
  16397. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16398. */
  16399. function Scene(engine) {
  16400. // Members
  16401. this.autoClear = true;
  16402. this.autoClearDepthAndStencil = true;
  16403. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  16404. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16405. this.forceWireframe = false;
  16406. this._forcePointsCloud = false;
  16407. this.forceShowBoundingBoxes = false;
  16408. this.animationsEnabled = true;
  16409. this.constantlyUpdateMeshUnderPointer = false;
  16410. this.hoverCursor = "pointer";
  16411. this.defaultCursor = "";
  16412. // Metadata
  16413. this.metadata = null;
  16414. /**
  16415. * An event triggered when the scene is disposed.
  16416. * @type {BABYLON.Observable}
  16417. */
  16418. this.onDisposeObservable = new BABYLON.Observable();
  16419. /**
  16420. * An event triggered before rendering the scene
  16421. * @type {BABYLON.Observable}
  16422. */
  16423. this.onBeforeRenderObservable = new BABYLON.Observable();
  16424. /**
  16425. * An event triggered after rendering the scene
  16426. * @type {BABYLON.Observable}
  16427. */
  16428. this.onAfterRenderObservable = new BABYLON.Observable();
  16429. /**
  16430. * An event triggered when the scene is ready
  16431. * @type {BABYLON.Observable}
  16432. */
  16433. this.onReadyObservable = new BABYLON.Observable();
  16434. /**
  16435. * An event triggered before rendering a camera
  16436. * @type {BABYLON.Observable}
  16437. */
  16438. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16439. /**
  16440. * An event triggered after rendering a camera
  16441. * @type {BABYLON.Observable}
  16442. */
  16443. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16444. /**
  16445. * An event triggered when a camera is created
  16446. * @type {BABYLON.Observable}
  16447. */
  16448. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16449. /**
  16450. * An event triggered when a camera is removed
  16451. * @type {BABYLON.Observable}
  16452. */
  16453. this.onCameraRemovedObservable = new BABYLON.Observable();
  16454. /**
  16455. * An event triggered when a light is created
  16456. * @type {BABYLON.Observable}
  16457. */
  16458. this.onNewLightAddedObservable = new BABYLON.Observable();
  16459. /**
  16460. * An event triggered when a light is removed
  16461. * @type {BABYLON.Observable}
  16462. */
  16463. this.onLightRemovedObservable = new BABYLON.Observable();
  16464. /**
  16465. * An event triggered when a geometry is created
  16466. * @type {BABYLON.Observable}
  16467. */
  16468. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16469. /**
  16470. * An event triggered when a geometry is removed
  16471. * @type {BABYLON.Observable}
  16472. */
  16473. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16474. /**
  16475. * An event triggered when a mesh is created
  16476. * @type {BABYLON.Observable}
  16477. */
  16478. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16479. /**
  16480. * An event triggered when a mesh is removed
  16481. * @type {BABYLON.Observable}
  16482. */
  16483. this.onMeshRemovedObservable = new BABYLON.Observable();
  16484. /**
  16485. * An event triggered before calculating deterministic simulation step
  16486. * @type {BABYLON.Observable}
  16487. */
  16488. this.onBeforeStepObservable = new BABYLON.Observable();
  16489. /**
  16490. * An event triggered after calculating deterministic simulation step
  16491. * @type {BABYLON.Observable}
  16492. */
  16493. this.onAfterStepObservable = new BABYLON.Observable();
  16494. /**
  16495. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16496. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16497. * 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)
  16498. */
  16499. this.onRenderingGroupObservable = new BABYLON.Observable();
  16500. // Animations
  16501. this.animations = [];
  16502. /**
  16503. * 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).
  16504. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  16505. */
  16506. this.onPrePointerObservable = new BABYLON.Observable();
  16507. /**
  16508. * Observable event triggered each time an input event is received from the rendering canvas
  16509. */
  16510. this.onPointerObservable = new BABYLON.Observable();
  16511. this._meshPickProceed = false;
  16512. this._previousHasSwiped = false;
  16513. this._currentPickResult = null;
  16514. this._previousPickResult = null;
  16515. this._isButtonPressed = false;
  16516. this._doubleClickOccured = false;
  16517. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  16518. this.cameraToUseForPointers = null;
  16519. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16520. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  16521. this._startingPointerTime = 0;
  16522. this._previousStartingPointerTime = 0;
  16523. // Deterministic lockstep
  16524. this._timeAccumulator = 0;
  16525. this._currentStepId = 0;
  16526. this._currentInternalStep = 0;
  16527. // Keyboard
  16528. /**
  16529. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  16530. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  16531. */
  16532. this.onPreKeyboardObservable = new BABYLON.Observable();
  16533. /**
  16534. * Observable event triggered each time an keyboard event is received from the hosting window
  16535. */
  16536. this.onKeyboardObservable = new BABYLON.Observable();
  16537. // Coordinate system
  16538. /**
  16539. * use right-handed coordinate system on this scene.
  16540. * @type {boolean}
  16541. */
  16542. this._useRightHandedSystem = false;
  16543. // Fog
  16544. this._fogEnabled = true;
  16545. this._fogMode = Scene.FOGMODE_NONE;
  16546. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16547. this.fogDensity = 0.1;
  16548. this.fogStart = 0;
  16549. this.fogEnd = 1000.0;
  16550. // Lights
  16551. /**
  16552. * is shadow enabled on this scene.
  16553. * @type {boolean}
  16554. */
  16555. this._shadowsEnabled = true;
  16556. /**
  16557. * is light enabled on this scene.
  16558. * @type {boolean}
  16559. */
  16560. this._lightsEnabled = true;
  16561. /**
  16562. * All of the lights added to this scene.
  16563. * @see BABYLON.Light
  16564. * @type {BABYLON.Light[]}
  16565. */
  16566. this.lights = new Array();
  16567. // Cameras
  16568. /** All of the cameras added to this scene. */
  16569. this.cameras = new Array();
  16570. /** All of the active cameras added to this scene. */
  16571. this.activeCameras = new Array();
  16572. // Meshes
  16573. /**
  16574. * All of the (abstract) meshes added to this scene.
  16575. * @see BABYLON.AbstractMesh
  16576. * @type {BABYLON.AbstractMesh[]}
  16577. */
  16578. this.meshes = new Array();
  16579. // Geometries
  16580. this._geometries = new Array();
  16581. this.materials = new Array();
  16582. this.multiMaterials = new Array();
  16583. // Textures
  16584. this._texturesEnabled = true;
  16585. this.textures = new Array();
  16586. // Particles
  16587. this.particlesEnabled = true;
  16588. this.particleSystems = new Array();
  16589. // Sprites
  16590. this.spritesEnabled = true;
  16591. this.spriteManagers = new Array();
  16592. // Layers
  16593. this.layers = new Array();
  16594. this.highlightLayers = new Array();
  16595. // Skeletons
  16596. this._skeletonsEnabled = true;
  16597. this.skeletons = new Array();
  16598. // Morph targets
  16599. this.morphTargetManagers = new Array();
  16600. // Lens flares
  16601. this.lensFlaresEnabled = true;
  16602. this.lensFlareSystems = new Array();
  16603. // Collisions
  16604. this.collisionsEnabled = true;
  16605. /** Defines the gravity applied to this scene */
  16606. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16607. // Postprocesses
  16608. this.postProcesses = new Array();
  16609. this.postProcessesEnabled = true;
  16610. // Customs render targets
  16611. this.renderTargetsEnabled = true;
  16612. this.dumpNextRenderTargets = false;
  16613. this.customRenderTargets = new Array();
  16614. // Imported meshes
  16615. this.importedMeshesFiles = new Array();
  16616. // Probes
  16617. this.probesEnabled = true;
  16618. this.reflectionProbes = new Array();
  16619. this._actionManagers = new Array();
  16620. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16621. // Procedural textures
  16622. this.proceduralTexturesEnabled = true;
  16623. this._proceduralTextures = new Array();
  16624. this.soundTracks = new Array();
  16625. this._audioEnabled = true;
  16626. this._headphone = false;
  16627. // Performance counters
  16628. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16629. this._totalLightsCounter = new BABYLON.PerfCounter();
  16630. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16631. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16632. this._totalVertices = new BABYLON.PerfCounter();
  16633. this._activeIndices = new BABYLON.PerfCounter();
  16634. this._activeParticles = new BABYLON.PerfCounter();
  16635. this._interFrameDuration = new BABYLON.PerfCounter();
  16636. this._lastFrameDuration = new BABYLON.PerfCounter();
  16637. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16638. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16639. this._particlesDuration = new BABYLON.PerfCounter();
  16640. this._renderDuration = new BABYLON.PerfCounter();
  16641. this._spritesDuration = new BABYLON.PerfCounter();
  16642. this._activeBones = new BABYLON.PerfCounter();
  16643. this._animationTime = 0;
  16644. this.animationTimeScale = 1;
  16645. this._renderId = 0;
  16646. this._executeWhenReadyTimeoutId = -1;
  16647. this._intermediateRendering = false;
  16648. this._viewUpdateFlag = -1;
  16649. this._projectionUpdateFlag = -1;
  16650. this._toBeDisposed = new BABYLON.SmartArray(256);
  16651. this._pendingData = []; //ANY
  16652. this._activeMeshes = new BABYLON.SmartArray(256);
  16653. this._processedMaterials = new BABYLON.SmartArray(256);
  16654. this._renderTargets = new BABYLON.SmartArray(256);
  16655. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16656. this._activeSkeletons = new BABYLON.SmartArray(32);
  16657. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16658. this._activeAnimatables = new Array();
  16659. this._transformMatrix = BABYLON.Matrix.Zero();
  16660. this.requireLightSorting = false;
  16661. this._uniqueIdCounter = 0;
  16662. this._activeMeshesFrozen = false;
  16663. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  16664. this._engine.scenes.push(this);
  16665. this._uid = null;
  16666. this._renderingManager = new BABYLON.RenderingManager(this);
  16667. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16668. if (BABYLON.OutlineRenderer) {
  16669. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16670. }
  16671. this.attachControl();
  16672. if (BABYLON.SoundTrack) {
  16673. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16674. }
  16675. //simplification queue
  16676. if (BABYLON.SimplificationQueue) {
  16677. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16678. }
  16679. //collision coordinator initialization. For now legacy per default.
  16680. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16681. // Uniform Buffer
  16682. this._createUbo();
  16683. // Default Image processing definition.
  16684. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  16685. }
  16686. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16687. /** The fog is deactivated */
  16688. get: function () {
  16689. return Scene._FOGMODE_NONE;
  16690. },
  16691. enumerable: true,
  16692. configurable: true
  16693. });
  16694. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16695. /** The fog density is following an exponential function */
  16696. get: function () {
  16697. return Scene._FOGMODE_EXP;
  16698. },
  16699. enumerable: true,
  16700. configurable: true
  16701. });
  16702. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16703. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  16704. get: function () {
  16705. return Scene._FOGMODE_EXP2;
  16706. },
  16707. enumerable: true,
  16708. configurable: true
  16709. });
  16710. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16711. /** The fog density is following a linear function. */
  16712. get: function () {
  16713. return Scene._FOGMODE_LINEAR;
  16714. },
  16715. enumerable: true,
  16716. configurable: true
  16717. });
  16718. Object.defineProperty(Scene.prototype, "environmentTexture", {
  16719. /**
  16720. * Texture used in all pbr material as the reflection texture.
  16721. * As in the majority of the scene they are the same (exception for multi room and so on),
  16722. * this is easier to reference from here than from all the materials.
  16723. */
  16724. get: function () {
  16725. return this._environmentTexture;
  16726. },
  16727. /**
  16728. * Texture used in all pbr material as the reflection texture.
  16729. * As in the majority of the scene they are the same (exception for multi room and so on),
  16730. * this is easier to set here than in all the materials.
  16731. */
  16732. set: function (value) {
  16733. this._environmentTexture = value;
  16734. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16735. },
  16736. enumerable: true,
  16737. configurable: true
  16738. });
  16739. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  16740. /**
  16741. * Default image processing configuration used either in the rendering
  16742. * Forward main pass or through the imageProcessingPostProcess if present.
  16743. * As in the majority of the scene they are the same (exception for multi camera),
  16744. * this is easier to reference from here than from all the materials and post process.
  16745. *
  16746. * No setter as we it is a shared configuration, you can set the values instead.
  16747. */
  16748. get: function () {
  16749. return this._imageProcessingConfiguration;
  16750. },
  16751. enumerable: true,
  16752. configurable: true
  16753. });
  16754. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  16755. get: function () {
  16756. return this._forcePointsCloud;
  16757. },
  16758. set: function (value) {
  16759. if (this._forcePointsCloud === value) {
  16760. return;
  16761. }
  16762. this._forcePointsCloud = value;
  16763. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16764. },
  16765. enumerable: true,
  16766. configurable: true
  16767. });
  16768. Object.defineProperty(Scene.prototype, "onDispose", {
  16769. /** A function to be executed when this scene is disposed. */
  16770. set: function (callback) {
  16771. if (this._onDisposeObserver) {
  16772. this.onDisposeObservable.remove(this._onDisposeObserver);
  16773. }
  16774. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16775. },
  16776. enumerable: true,
  16777. configurable: true
  16778. });
  16779. Object.defineProperty(Scene.prototype, "beforeRender", {
  16780. /** A function to be executed before rendering this scene */
  16781. set: function (callback) {
  16782. if (this._onBeforeRenderObserver) {
  16783. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16784. }
  16785. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16786. },
  16787. enumerable: true,
  16788. configurable: true
  16789. });
  16790. Object.defineProperty(Scene.prototype, "afterRender", {
  16791. /** A function to be executed after rendering this scene */
  16792. set: function (callback) {
  16793. if (this._onAfterRenderObserver) {
  16794. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16795. }
  16796. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16797. },
  16798. enumerable: true,
  16799. configurable: true
  16800. });
  16801. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16802. set: function (callback) {
  16803. if (this._onBeforeCameraRenderObserver) {
  16804. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16805. }
  16806. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16807. },
  16808. enumerable: true,
  16809. configurable: true
  16810. });
  16811. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16812. set: function (callback) {
  16813. if (this._onAfterCameraRenderObserver) {
  16814. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16815. }
  16816. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16817. },
  16818. enumerable: true,
  16819. configurable: true
  16820. });
  16821. Object.defineProperty(Scene.prototype, "gamepadManager", {
  16822. get: function () {
  16823. if (!this._gamepadManager) {
  16824. this._gamepadManager = new BABYLON.GamepadManager();
  16825. }
  16826. return this._gamepadManager;
  16827. },
  16828. enumerable: true,
  16829. configurable: true
  16830. });
  16831. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16832. get: function () {
  16833. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16834. },
  16835. enumerable: true,
  16836. configurable: true
  16837. });
  16838. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  16839. get: function () {
  16840. return this._useRightHandedSystem;
  16841. },
  16842. set: function (value) {
  16843. if (this._useRightHandedSystem === value) {
  16844. return;
  16845. }
  16846. this._useRightHandedSystem = value;
  16847. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16848. },
  16849. enumerable: true,
  16850. configurable: true
  16851. });
  16852. Scene.prototype.setStepId = function (newStepId) {
  16853. this._currentStepId = newStepId;
  16854. };
  16855. ;
  16856. Scene.prototype.getStepId = function () {
  16857. return this._currentStepId;
  16858. };
  16859. ;
  16860. Scene.prototype.getInternalStep = function () {
  16861. return this._currentInternalStep;
  16862. };
  16863. ;
  16864. Object.defineProperty(Scene.prototype, "fogEnabled", {
  16865. get: function () {
  16866. return this._fogEnabled;
  16867. },
  16868. /**
  16869. * is fog enabled on this scene.
  16870. */
  16871. set: function (value) {
  16872. if (this._fogEnabled === value) {
  16873. return;
  16874. }
  16875. this._fogEnabled = value;
  16876. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16877. },
  16878. enumerable: true,
  16879. configurable: true
  16880. });
  16881. Object.defineProperty(Scene.prototype, "fogMode", {
  16882. get: function () {
  16883. return this._fogMode;
  16884. },
  16885. set: function (value) {
  16886. if (this._fogMode === value) {
  16887. return;
  16888. }
  16889. this._fogMode = value;
  16890. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16891. },
  16892. enumerable: true,
  16893. configurable: true
  16894. });
  16895. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  16896. get: function () {
  16897. return this._shadowsEnabled;
  16898. },
  16899. set: function (value) {
  16900. if (this._shadowsEnabled === value) {
  16901. return;
  16902. }
  16903. this._shadowsEnabled = value;
  16904. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16905. },
  16906. enumerable: true,
  16907. configurable: true
  16908. });
  16909. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  16910. get: function () {
  16911. return this._lightsEnabled;
  16912. },
  16913. set: function (value) {
  16914. if (this._lightsEnabled === value) {
  16915. return;
  16916. }
  16917. this._lightsEnabled = value;
  16918. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16919. },
  16920. enumerable: true,
  16921. configurable: true
  16922. });
  16923. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16924. /** The default material used on meshes when no material is affected */
  16925. get: function () {
  16926. if (!this._defaultMaterial) {
  16927. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16928. }
  16929. return this._defaultMaterial;
  16930. },
  16931. /** The default material used on meshes when no material is affected */
  16932. set: function (value) {
  16933. this._defaultMaterial = value;
  16934. },
  16935. enumerable: true,
  16936. configurable: true
  16937. });
  16938. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  16939. get: function () {
  16940. return this._texturesEnabled;
  16941. },
  16942. set: function (value) {
  16943. if (this._texturesEnabled === value) {
  16944. return;
  16945. }
  16946. this._texturesEnabled = value;
  16947. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16948. },
  16949. enumerable: true,
  16950. configurable: true
  16951. });
  16952. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  16953. get: function () {
  16954. return this._skeletonsEnabled;
  16955. },
  16956. set: function (value) {
  16957. if (this._skeletonsEnabled === value) {
  16958. return;
  16959. }
  16960. this._skeletonsEnabled = value;
  16961. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  16962. },
  16963. enumerable: true,
  16964. configurable: true
  16965. });
  16966. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  16967. get: function () {
  16968. if (!this._postProcessRenderPipelineManager) {
  16969. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16970. }
  16971. return this._postProcessRenderPipelineManager;
  16972. },
  16973. enumerable: true,
  16974. configurable: true
  16975. });
  16976. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  16977. get: function () {
  16978. return this._frustumPlanes;
  16979. },
  16980. enumerable: true,
  16981. configurable: true
  16982. });
  16983. Object.defineProperty(Scene.prototype, "debugLayer", {
  16984. // Properties
  16985. get: function () {
  16986. if (!this._debugLayer) {
  16987. this._debugLayer = new BABYLON.DebugLayer(this);
  16988. }
  16989. return this._debugLayer;
  16990. },
  16991. enumerable: true,
  16992. configurable: true
  16993. });
  16994. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16995. get: function () {
  16996. return this._workerCollisions;
  16997. },
  16998. set: function (enabled) {
  16999. if (!BABYLON.CollisionCoordinatorLegacy) {
  17000. return;
  17001. }
  17002. enabled = (enabled && !!Worker);
  17003. this._workerCollisions = enabled;
  17004. if (this.collisionCoordinator) {
  17005. this.collisionCoordinator.destroy();
  17006. }
  17007. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  17008. this.collisionCoordinator.init(this);
  17009. },
  17010. enumerable: true,
  17011. configurable: true
  17012. });
  17013. Object.defineProperty(Scene.prototype, "selectionOctree", {
  17014. get: function () {
  17015. return this._selectionOctree;
  17016. },
  17017. enumerable: true,
  17018. configurable: true
  17019. });
  17020. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  17021. /**
  17022. * The mesh that is currently under the pointer.
  17023. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  17024. */
  17025. get: function () {
  17026. return this._pointerOverMesh;
  17027. },
  17028. enumerable: true,
  17029. configurable: true
  17030. });
  17031. Object.defineProperty(Scene.prototype, "pointerX", {
  17032. /**
  17033. * Current on-screen X position of the pointer
  17034. * @return {number} X position of the pointer
  17035. */
  17036. get: function () {
  17037. return this._pointerX;
  17038. },
  17039. enumerable: true,
  17040. configurable: true
  17041. });
  17042. Object.defineProperty(Scene.prototype, "pointerY", {
  17043. /**
  17044. * Current on-screen Y position of the pointer
  17045. * @return {number} Y position of the pointer
  17046. */
  17047. get: function () {
  17048. return this._pointerY;
  17049. },
  17050. enumerable: true,
  17051. configurable: true
  17052. });
  17053. Scene.prototype.getCachedMaterial = function () {
  17054. return this._cachedMaterial;
  17055. };
  17056. Scene.prototype.getCachedEffect = function () {
  17057. return this._cachedEffect;
  17058. };
  17059. Scene.prototype.getCachedVisibility = function () {
  17060. return this._cachedVisibility;
  17061. };
  17062. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  17063. if (visibility === void 0) { visibility = 1; }
  17064. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  17065. };
  17066. Scene.prototype.getBoundingBoxRenderer = function () {
  17067. if (!this._boundingBoxRenderer) {
  17068. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  17069. }
  17070. return this._boundingBoxRenderer;
  17071. };
  17072. Scene.prototype.getOutlineRenderer = function () {
  17073. return this._outlineRenderer;
  17074. };
  17075. Scene.prototype.getEngine = function () {
  17076. return this._engine;
  17077. };
  17078. Scene.prototype.getTotalVertices = function () {
  17079. return this._totalVertices.current;
  17080. };
  17081. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17082. get: function () {
  17083. return this._totalVertices;
  17084. },
  17085. enumerable: true,
  17086. configurable: true
  17087. });
  17088. Scene.prototype.getActiveIndices = function () {
  17089. return this._activeIndices.current;
  17090. };
  17091. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17092. get: function () {
  17093. return this._activeIndices;
  17094. },
  17095. enumerable: true,
  17096. configurable: true
  17097. });
  17098. Scene.prototype.getActiveParticles = function () {
  17099. return this._activeParticles.current;
  17100. };
  17101. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17102. get: function () {
  17103. return this._activeParticles;
  17104. },
  17105. enumerable: true,
  17106. configurable: true
  17107. });
  17108. Scene.prototype.getActiveBones = function () {
  17109. return this._activeBones.current;
  17110. };
  17111. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17112. get: function () {
  17113. return this._activeBones;
  17114. },
  17115. enumerable: true,
  17116. configurable: true
  17117. });
  17118. // Stats
  17119. Scene.prototype.getInterFramePerfCounter = function () {
  17120. return this._interFrameDuration.current;
  17121. };
  17122. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  17123. get: function () {
  17124. return this._interFrameDuration;
  17125. },
  17126. enumerable: true,
  17127. configurable: true
  17128. });
  17129. Scene.prototype.getLastFrameDuration = function () {
  17130. return this._lastFrameDuration.current;
  17131. };
  17132. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  17133. get: function () {
  17134. return this._lastFrameDuration;
  17135. },
  17136. enumerable: true,
  17137. configurable: true
  17138. });
  17139. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  17140. return this._evaluateActiveMeshesDuration.current;
  17141. };
  17142. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  17143. get: function () {
  17144. return this._evaluateActiveMeshesDuration;
  17145. },
  17146. enumerable: true,
  17147. configurable: true
  17148. });
  17149. Scene.prototype.getActiveMeshes = function () {
  17150. return this._activeMeshes;
  17151. };
  17152. Scene.prototype.getRenderTargetsDuration = function () {
  17153. return this._renderTargetsDuration.current;
  17154. };
  17155. Scene.prototype.getRenderDuration = function () {
  17156. return this._renderDuration.current;
  17157. };
  17158. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  17159. get: function () {
  17160. return this._renderDuration;
  17161. },
  17162. enumerable: true,
  17163. configurable: true
  17164. });
  17165. Scene.prototype.getParticlesDuration = function () {
  17166. return this._particlesDuration.current;
  17167. };
  17168. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17169. get: function () {
  17170. return this._particlesDuration;
  17171. },
  17172. enumerable: true,
  17173. configurable: true
  17174. });
  17175. Scene.prototype.getSpritesDuration = function () {
  17176. return this._spritesDuration.current;
  17177. };
  17178. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17179. get: function () {
  17180. return this._spritesDuration;
  17181. },
  17182. enumerable: true,
  17183. configurable: true
  17184. });
  17185. Scene.prototype.getAnimationRatio = function () {
  17186. return this._animationRatio;
  17187. };
  17188. Scene.prototype.getRenderId = function () {
  17189. return this._renderId;
  17190. };
  17191. Scene.prototype.incrementRenderId = function () {
  17192. this._renderId++;
  17193. };
  17194. Scene.prototype._updatePointerPosition = function (evt) {
  17195. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17196. this._pointerX = evt.clientX - canvasRect.left;
  17197. this._pointerY = evt.clientY - canvasRect.top;
  17198. this._unTranslatedPointerX = this._pointerX;
  17199. this._unTranslatedPointerY = this._pointerY;
  17200. };
  17201. Scene.prototype._createUbo = function () {
  17202. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  17203. this._sceneUbo.addUniform("viewProjection", 16);
  17204. this._sceneUbo.addUniform("view", 16);
  17205. };
  17206. // Pointers handling
  17207. /**
  17208. * Use this method to simulate a pointer move on a mesh
  17209. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17210. */
  17211. Scene.prototype.simulatePointerMove = function (pickResult) {
  17212. var evt = new PointerEvent("pointermove");
  17213. return this._processPointerMove(pickResult, evt);
  17214. };
  17215. Scene.prototype._processPointerMove = function (pickResult, evt) {
  17216. var canvas = this._engine.getRenderingCanvas();
  17217. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17218. this.setPointerOverSprite(null);
  17219. this.setPointerOverMesh(pickResult.pickedMesh);
  17220. if (this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17221. if (this._pointerOverMesh.actionManager.hoverCursor) {
  17222. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  17223. }
  17224. else {
  17225. canvas.style.cursor = this.hoverCursor;
  17226. }
  17227. }
  17228. else {
  17229. canvas.style.cursor = this.defaultCursor;
  17230. }
  17231. }
  17232. else {
  17233. this.setPointerOverMesh(null);
  17234. // Sprites
  17235. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers);
  17236. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17237. this.setPointerOverSprite(pickResult.pickedSprite);
  17238. if (this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  17239. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  17240. }
  17241. else {
  17242. canvas.style.cursor = this.hoverCursor;
  17243. }
  17244. }
  17245. else {
  17246. this.setPointerOverSprite(null);
  17247. // Restore pointer
  17248. canvas.style.cursor = this.defaultCursor;
  17249. }
  17250. }
  17251. if (this.onPointerMove) {
  17252. this.onPointerMove(evt, pickResult);
  17253. }
  17254. if (this.onPointerObservable.hasObservers()) {
  17255. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17256. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17257. this.onPointerObservable.notifyObservers(pi, type);
  17258. }
  17259. return this;
  17260. };
  17261. /**
  17262. * Use this method to simulate a pointer down on a mesh
  17263. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17264. */
  17265. Scene.prototype.simulatePointerDown = function (pickResult) {
  17266. var evt = new PointerEvent("pointerdown");
  17267. return this._processPointerDown(pickResult, evt);
  17268. };
  17269. Scene.prototype._processPointerDown = function (pickResult, evt) {
  17270. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17271. this._pickedDownMesh = pickResult.pickedMesh;
  17272. var actionManager = pickResult.pickedMesh.actionManager;
  17273. if (actionManager) {
  17274. if (actionManager.hasPickTriggers) {
  17275. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17276. switch (evt.button) {
  17277. case 0:
  17278. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17279. break;
  17280. case 1:
  17281. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17282. break;
  17283. case 2:
  17284. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17285. break;
  17286. }
  17287. }
  17288. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17289. window.setTimeout((function () {
  17290. var _this = this;
  17291. 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);
  17292. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17293. if (this._isButtonPressed &&
  17294. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  17295. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  17296. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  17297. this._startingPointerTime = 0;
  17298. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17299. }
  17300. }
  17301. }).bind(this), Scene.LongPressDelay);
  17302. }
  17303. }
  17304. }
  17305. if (this.onPointerDown) {
  17306. this.onPointerDown(evt, pickResult);
  17307. }
  17308. if (this.onPointerObservable.hasObservers()) {
  17309. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  17310. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17311. this.onPointerObservable.notifyObservers(pi, type);
  17312. }
  17313. return this;
  17314. };
  17315. /**
  17316. * Use this method to simulate a pointer up on a mesh
  17317. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17318. */
  17319. Scene.prototype.simulatePointerUp = function (pickResult) {
  17320. var evt = new PointerEvent("pointerup");
  17321. var clickInfo = new ClickInfo();
  17322. clickInfo.singleClick = true;
  17323. return this._processPointerUp(pickResult, evt, clickInfo);
  17324. };
  17325. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  17326. if (pickResult && pickResult && pickResult.pickedMesh) {
  17327. this._pickedUpMesh = pickResult.pickedMesh;
  17328. if (this._pickedDownMesh === this._pickedUpMesh) {
  17329. if (this.onPointerPick) {
  17330. this.onPointerPick(evt, pickResult);
  17331. }
  17332. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  17333. var type = BABYLON.PointerEventTypes.POINTERPICK;
  17334. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17335. this.onPointerObservable.notifyObservers(pi, type);
  17336. }
  17337. }
  17338. if (pickResult.pickedMesh.actionManager) {
  17339. if (clickInfo.ignore) {
  17340. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17341. }
  17342. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  17343. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17344. }
  17345. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17346. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17347. }
  17348. }
  17349. }
  17350. if (this._pickedDownMesh &&
  17351. this._pickedDownMesh.actionManager &&
  17352. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  17353. this._pickedDownMesh !== this._pickedUpMesh) {
  17354. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  17355. }
  17356. if (this.onPointerUp) {
  17357. this.onPointerUp(evt, pickResult);
  17358. }
  17359. if (this.onPointerObservable.hasObservers()) {
  17360. if (!clickInfo.ignore) {
  17361. if (!clickInfo.hasSwiped) {
  17362. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  17363. var type = BABYLON.PointerEventTypes.POINTERTAP;
  17364. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17365. this.onPointerObservable.notifyObservers(pi, type);
  17366. }
  17367. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  17368. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  17369. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17370. this.onPointerObservable.notifyObservers(pi, type);
  17371. }
  17372. }
  17373. }
  17374. else {
  17375. var type = BABYLON.PointerEventTypes.POINTERUP;
  17376. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17377. this.onPointerObservable.notifyObservers(pi, type);
  17378. }
  17379. }
  17380. return this;
  17381. };
  17382. /**
  17383. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17384. * @param attachUp defines if you want to attach events to pointerup
  17385. * @param attachDown defines if you want to attach events to pointerdown
  17386. * @param attachMove defines if you want to attach events to pointermove
  17387. */
  17388. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17389. var _this = this;
  17390. if (attachUp === void 0) { attachUp = true; }
  17391. if (attachDown === void 0) { attachDown = true; }
  17392. if (attachMove === void 0) { attachMove = true; }
  17393. this._initActionManager = function (act, clickInfo) {
  17394. if (!_this._meshPickProceed) {
  17395. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17396. _this._currentPickResult = pickResult;
  17397. if (pickResult) {
  17398. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  17399. }
  17400. _this._meshPickProceed = true;
  17401. }
  17402. return act;
  17403. };
  17404. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  17405. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  17406. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  17407. btn !== _this._previousButtonPressed) {
  17408. _this._doubleClickOccured = false;
  17409. clickInfo.singleClick = true;
  17410. clickInfo.ignore = false;
  17411. cb(clickInfo, _this._currentPickResult);
  17412. }
  17413. };
  17414. this._initClickEvent = function (obs1, obs2, evt, cb) {
  17415. var clickInfo = new ClickInfo();
  17416. _this._currentPickResult = null;
  17417. var act;
  17418. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  17419. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  17420. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17421. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  17422. act = _this._initActionManager(act, clickInfo);
  17423. if (act)
  17424. checkPicking = act.hasPickTriggers;
  17425. }
  17426. if (checkPicking) {
  17427. var btn = evt.button;
  17428. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  17429. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  17430. if (!clickInfo.hasSwiped) {
  17431. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  17432. if (!checkSingleClickImmediately) {
  17433. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  17434. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17435. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17436. act = _this._initActionManager(act, clickInfo);
  17437. if (act)
  17438. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17439. }
  17440. }
  17441. if (checkSingleClickImmediately) {
  17442. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  17443. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  17444. btn !== _this._previousButtonPressed) {
  17445. clickInfo.singleClick = true;
  17446. cb(clickInfo, _this._currentPickResult);
  17447. }
  17448. }
  17449. else {
  17450. // wait that no double click has been raised during the double click delay
  17451. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17452. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  17453. }
  17454. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  17455. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17456. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17457. act = _this._initActionManager(act, clickInfo);
  17458. if (act)
  17459. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17460. }
  17461. if (checkDoubleClick) {
  17462. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  17463. if (btn === _this._previousButtonPressed &&
  17464. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  17465. !_this._doubleClickOccured) {
  17466. // pointer has not moved for 2 clicks, it's a double click
  17467. if (!clickInfo.hasSwiped &&
  17468. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  17469. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  17470. _this._previousStartingPointerTime = 0;
  17471. _this._doubleClickOccured = true;
  17472. clickInfo.doubleClick = true;
  17473. clickInfo.ignore = false;
  17474. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  17475. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17476. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17477. cb(clickInfo, _this._currentPickResult);
  17478. }
  17479. else {
  17480. _this._doubleClickOccured = false;
  17481. _this._previousStartingPointerTime = _this._startingPointerTime;
  17482. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17483. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17484. _this._previousButtonPressed = btn;
  17485. _this._previousHasSwiped = clickInfo.hasSwiped;
  17486. if (Scene.ExclusiveDoubleClickMode) {
  17487. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  17488. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17489. }
  17490. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17491. cb(clickInfo, _this._previousPickResult);
  17492. }
  17493. else {
  17494. cb(clickInfo, _this._currentPickResult);
  17495. }
  17496. }
  17497. }
  17498. else {
  17499. _this._doubleClickOccured = false;
  17500. _this._previousStartingPointerTime = _this._startingPointerTime;
  17501. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17502. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17503. _this._previousButtonPressed = btn;
  17504. _this._previousHasSwiped = clickInfo.hasSwiped;
  17505. }
  17506. }
  17507. }
  17508. }
  17509. clickInfo.ignore = true;
  17510. cb(clickInfo, _this._currentPickResult);
  17511. };
  17512. this._spritePredicate = function (sprite) {
  17513. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17514. };
  17515. this._onPointerMove = function (evt) {
  17516. _this._updatePointerPosition(evt);
  17517. // PreObservable support
  17518. if (_this.onPrePointerObservable.hasObservers()) {
  17519. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17520. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17521. _this.onPrePointerObservable.notifyObservers(pi, type);
  17522. if (pi.skipOnPointerObservable) {
  17523. return;
  17524. }
  17525. }
  17526. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17527. return;
  17528. }
  17529. if (!_this.pointerMovePredicate) {
  17530. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  17531. }
  17532. // Meshes
  17533. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17534. _this._processPointerMove(pickResult, evt);
  17535. };
  17536. this._onPointerDown = function (evt) {
  17537. _this._isButtonPressed = true;
  17538. _this._pickedDownMesh = null;
  17539. _this._meshPickProceed = false;
  17540. _this._updatePointerPosition(evt);
  17541. // PreObservable support
  17542. if (_this.onPrePointerObservable.hasObservers()) {
  17543. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  17544. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17545. _this.onPrePointerObservable.notifyObservers(pi, type);
  17546. if (pi.skipOnPointerObservable) {
  17547. return;
  17548. }
  17549. }
  17550. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17551. return;
  17552. }
  17553. _this._startingPointerPosition.x = _this._pointerX;
  17554. _this._startingPointerPosition.y = _this._pointerY;
  17555. _this._startingPointerTime = new Date().getTime();
  17556. if (!_this.pointerDownPredicate) {
  17557. _this.pointerDownPredicate = function (mesh) {
  17558. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17559. };
  17560. }
  17561. // Meshes
  17562. _this._pickedDownMesh = null;
  17563. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17564. _this._processPointerDown(pickResult, evt);
  17565. // Sprites
  17566. _this._pickedDownSprite = null;
  17567. if (_this.spriteManagers.length > 0) {
  17568. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers);
  17569. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17570. if (pickResult.pickedSprite.actionManager) {
  17571. _this._pickedDownSprite = pickResult.pickedSprite;
  17572. switch (evt.button) {
  17573. case 0:
  17574. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17575. break;
  17576. case 1:
  17577. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17578. break;
  17579. case 2:
  17580. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17581. break;
  17582. }
  17583. if (pickResult.pickedSprite.actionManager) {
  17584. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17585. }
  17586. }
  17587. }
  17588. }
  17589. };
  17590. this._onPointerUp = function (evt) {
  17591. _this._isButtonPressed = false;
  17592. _this._pickedUpMesh = null;
  17593. _this._meshPickProceed = false;
  17594. _this._updatePointerPosition(evt);
  17595. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  17596. // PreObservable support
  17597. if (this.onPrePointerObservable.hasObservers()) {
  17598. if (!clickInfo.ignore) {
  17599. if (!clickInfo.hasSwiped) {
  17600. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  17601. var type = BABYLON.PointerEventTypes.POINTERTAP;
  17602. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17603. this.onPrePointerObservable.notifyObservers(pi, type);
  17604. if (pi.skipOnPointerObservable) {
  17605. return;
  17606. }
  17607. }
  17608. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  17609. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  17610. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17611. this.onPrePointerObservable.notifyObservers(pi, type);
  17612. if (pi.skipOnPointerObservable) {
  17613. return;
  17614. }
  17615. }
  17616. }
  17617. }
  17618. else {
  17619. var type = BABYLON.PointerEventTypes.POINTERUP;
  17620. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17621. this.onPrePointerObservable.notifyObservers(pi, type);
  17622. if (pi.skipOnPointerObservable) {
  17623. return;
  17624. }
  17625. }
  17626. }
  17627. if (!this.cameraToUseForPointers && !this.activeCamera) {
  17628. return;
  17629. }
  17630. if (!this.pointerUpPredicate) {
  17631. this.pointerUpPredicate = function (mesh) {
  17632. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17633. };
  17634. }
  17635. // Meshes
  17636. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  17637. this._initActionManager(null, clickInfo);
  17638. }
  17639. if (!pickResult) {
  17640. pickResult = this._currentPickResult;
  17641. }
  17642. this._processPointerUp(pickResult, evt, clickInfo);
  17643. // Sprites
  17644. if (this.spriteManagers.length > 0) {
  17645. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers);
  17646. if (pickResult.hit && pickResult.pickedSprite) {
  17647. if (pickResult.pickedSprite.actionManager) {
  17648. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17649. if (pickResult.pickedSprite.actionManager) {
  17650. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  17651. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17652. }
  17653. }
  17654. }
  17655. }
  17656. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  17657. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  17658. }
  17659. }
  17660. this._previousPickResult = this._currentPickResult;
  17661. }).bind(_this));
  17662. };
  17663. this._onKeyDown = function (evt) {
  17664. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  17665. if (_this.onPreKeyboardObservable.hasObservers()) {
  17666. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  17667. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  17668. if (pi.skipOnPointerObservable) {
  17669. return;
  17670. }
  17671. }
  17672. if (_this.onKeyboardObservable.hasObservers()) {
  17673. var pi = new BABYLON.KeyboardInfo(type, evt);
  17674. _this.onKeyboardObservable.notifyObservers(pi, type);
  17675. }
  17676. if (_this.actionManager) {
  17677. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17678. }
  17679. };
  17680. this._onKeyUp = function (evt) {
  17681. var type = BABYLON.KeyboardEventTypes.KEYUP;
  17682. if (_this.onPreKeyboardObservable.hasObservers()) {
  17683. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  17684. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  17685. if (pi.skipOnPointerObservable) {
  17686. return;
  17687. }
  17688. }
  17689. if (_this.onKeyboardObservable.hasObservers()) {
  17690. var pi = new BABYLON.KeyboardInfo(type, evt);
  17691. _this.onKeyboardObservable.notifyObservers(pi, type);
  17692. }
  17693. if (_this.actionManager) {
  17694. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17695. }
  17696. };
  17697. var engine = this.getEngine();
  17698. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  17699. canvas.addEventListener("keydown", _this._onKeyDown, false);
  17700. canvas.addEventListener("keyup", _this._onKeyUp, false);
  17701. });
  17702. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  17703. canvas.removeEventListener("keydown", _this._onKeyDown);
  17704. canvas.removeEventListener("keyup", _this._onKeyUp);
  17705. });
  17706. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17707. var canvas = this._engine.getRenderingCanvas();
  17708. if (attachMove) {
  17709. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17710. // Wheel
  17711. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17712. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17713. }
  17714. if (attachDown) {
  17715. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17716. }
  17717. if (attachUp) {
  17718. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17719. }
  17720. canvas.tabIndex = 1;
  17721. };
  17722. Scene.prototype.detachControl = function () {
  17723. var engine = this.getEngine();
  17724. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17725. var canvas = engine.getRenderingCanvas();
  17726. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17727. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17728. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17729. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  17730. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  17731. // Wheel
  17732. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17733. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17734. // Keyboard
  17735. canvas.removeEventListener("keydown", this._onKeyDown);
  17736. canvas.removeEventListener("keyup", this._onKeyUp);
  17737. // Observables
  17738. this.onKeyboardObservable.clear();
  17739. this.onPreKeyboardObservable.clear();
  17740. this.onPointerObservable.clear();
  17741. this.onPrePointerObservable.clear();
  17742. };
  17743. // Ready
  17744. Scene.prototype.isReady = function () {
  17745. if (this._pendingData.length > 0) {
  17746. return false;
  17747. }
  17748. var index;
  17749. // Geometries
  17750. for (index = 0; index < this._geometries.length; index++) {
  17751. var geometry = this._geometries[index];
  17752. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17753. return false;
  17754. }
  17755. }
  17756. // Meshes
  17757. for (index = 0; index < this.meshes.length; index++) {
  17758. var mesh = this.meshes[index];
  17759. if (!mesh.isEnabled()) {
  17760. continue;
  17761. }
  17762. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  17763. continue;
  17764. }
  17765. if (!mesh.isReady()) {
  17766. return false;
  17767. }
  17768. var mat = mesh.material;
  17769. if (mat) {
  17770. if (!mat.isReady(mesh)) {
  17771. return false;
  17772. }
  17773. }
  17774. }
  17775. return true;
  17776. };
  17777. Scene.prototype.resetCachedMaterial = function () {
  17778. this._cachedMaterial = null;
  17779. this._cachedEffect = null;
  17780. this._cachedVisibility = null;
  17781. };
  17782. Scene.prototype.registerBeforeRender = function (func) {
  17783. this.onBeforeRenderObservable.add(func);
  17784. };
  17785. Scene.prototype.unregisterBeforeRender = function (func) {
  17786. this.onBeforeRenderObservable.removeCallback(func);
  17787. };
  17788. Scene.prototype.registerAfterRender = function (func) {
  17789. this.onAfterRenderObservable.add(func);
  17790. };
  17791. Scene.prototype.unregisterAfterRender = function (func) {
  17792. this.onAfterRenderObservable.removeCallback(func);
  17793. };
  17794. Scene.prototype._addPendingData = function (data) {
  17795. this._pendingData.push(data);
  17796. };
  17797. Scene.prototype._removePendingData = function (data) {
  17798. var index = this._pendingData.indexOf(data);
  17799. if (index !== -1) {
  17800. this._pendingData.splice(index, 1);
  17801. }
  17802. };
  17803. Scene.prototype.getWaitingItemsCount = function () {
  17804. return this._pendingData.length;
  17805. };
  17806. /**
  17807. * Registers a function to be executed when the scene is ready.
  17808. * @param {Function} func - the function to be executed.
  17809. */
  17810. Scene.prototype.executeWhenReady = function (func) {
  17811. var _this = this;
  17812. this.onReadyObservable.add(func);
  17813. if (this._executeWhenReadyTimeoutId !== -1) {
  17814. return;
  17815. }
  17816. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17817. _this._checkIsReady();
  17818. }, 150);
  17819. };
  17820. Scene.prototype._checkIsReady = function () {
  17821. var _this = this;
  17822. if (this.isReady()) {
  17823. this.onReadyObservable.notifyObservers(this);
  17824. this.onReadyObservable.clear();
  17825. this._executeWhenReadyTimeoutId = -1;
  17826. return;
  17827. }
  17828. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17829. _this._checkIsReady();
  17830. }, 150);
  17831. };
  17832. // Animations
  17833. /**
  17834. * Will start the animation sequence of a given target
  17835. * @param target - the target
  17836. * @param {number} from - from which frame should animation start
  17837. * @param {number} to - till which frame should animation run.
  17838. * @param {boolean} [loop] - should the animation loop
  17839. * @param {number} [speedRatio] - the speed in which to run the animation
  17840. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17841. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17842. * Returns {BABYLON.Animatable} the animatable object created for this animation
  17843. * See BABYLON.Animatable
  17844. */
  17845. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17846. if (speedRatio === void 0) { speedRatio = 1.0; }
  17847. if (from > to && speedRatio > 0) {
  17848. speedRatio *= -1;
  17849. }
  17850. this.stopAnimation(target);
  17851. if (!animatable) {
  17852. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17853. }
  17854. // Local animations
  17855. if (target.animations) {
  17856. animatable.appendAnimations(target, target.animations);
  17857. }
  17858. // Children animations
  17859. if (target.getAnimatables) {
  17860. var animatables = target.getAnimatables();
  17861. for (var index = 0; index < animatables.length; index++) {
  17862. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17863. }
  17864. }
  17865. animatable.reset();
  17866. return animatable;
  17867. };
  17868. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17869. if (speedRatio === undefined) {
  17870. speedRatio = 1.0;
  17871. }
  17872. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17873. return animatable;
  17874. };
  17875. Scene.prototype.getAnimatableByTarget = function (target) {
  17876. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17877. if (this._activeAnimatables[index].target === target) {
  17878. return this._activeAnimatables[index];
  17879. }
  17880. }
  17881. return null;
  17882. };
  17883. Object.defineProperty(Scene.prototype, "Animatables", {
  17884. get: function () {
  17885. return this._activeAnimatables;
  17886. },
  17887. enumerable: true,
  17888. configurable: true
  17889. });
  17890. /**
  17891. * Will stop the animation of the given target
  17892. * @param target - the target
  17893. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17894. * @see beginAnimation
  17895. */
  17896. Scene.prototype.stopAnimation = function (target, animationName) {
  17897. var animatable = this.getAnimatableByTarget(target);
  17898. if (animatable) {
  17899. animatable.stop(animationName);
  17900. }
  17901. };
  17902. Scene.prototype._animate = function () {
  17903. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17904. return;
  17905. }
  17906. // Getting time
  17907. var now = BABYLON.Tools.Now;
  17908. if (!this._animationTimeLast) {
  17909. if (this._pendingData.length > 0) {
  17910. return;
  17911. }
  17912. this._animationTimeLast = now;
  17913. }
  17914. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  17915. this._animationTime += deltaTime;
  17916. this._animationTimeLast = now;
  17917. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17918. this._activeAnimatables[index]._animate(this._animationTime);
  17919. }
  17920. };
  17921. // Matrix
  17922. Scene.prototype.getViewMatrix = function () {
  17923. return this._viewMatrix;
  17924. };
  17925. Scene.prototype.getProjectionMatrix = function () {
  17926. return this._projectionMatrix;
  17927. };
  17928. Scene.prototype.getTransformMatrix = function () {
  17929. return this._transformMatrix;
  17930. };
  17931. Scene.prototype.setTransformMatrix = function (view, projection) {
  17932. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  17933. return;
  17934. }
  17935. this._viewUpdateFlag = view.updateFlag;
  17936. this._projectionUpdateFlag = projection.updateFlag;
  17937. this._viewMatrix = view;
  17938. this._projectionMatrix = projection;
  17939. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17940. // Update frustum
  17941. if (!this._frustumPlanes) {
  17942. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17943. }
  17944. else {
  17945. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17946. }
  17947. if (this._sceneUbo.useUbo) {
  17948. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  17949. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  17950. this._sceneUbo.update();
  17951. }
  17952. };
  17953. Scene.prototype.getSceneUniformBuffer = function () {
  17954. return this._sceneUbo;
  17955. };
  17956. // Methods
  17957. Scene.prototype.getUniqueId = function () {
  17958. var result = this._uniqueIdCounter;
  17959. this._uniqueIdCounter++;
  17960. return result;
  17961. };
  17962. Scene.prototype.addMesh = function (newMesh) {
  17963. newMesh.uniqueId = this.getUniqueId();
  17964. var position = this.meshes.push(newMesh);
  17965. //notify the collision coordinator
  17966. if (this.collisionCoordinator) {
  17967. this.collisionCoordinator.onMeshAdded(newMesh);
  17968. }
  17969. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17970. };
  17971. Scene.prototype.removeMesh = function (toRemove) {
  17972. var index = this.meshes.indexOf(toRemove);
  17973. if (index !== -1) {
  17974. // Remove from the scene if mesh found
  17975. this.meshes.splice(index, 1);
  17976. }
  17977. //notify the collision coordinator
  17978. if (this.collisionCoordinator) {
  17979. this.collisionCoordinator.onMeshRemoved(toRemove);
  17980. }
  17981. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17982. return index;
  17983. };
  17984. Scene.prototype.removeSkeleton = function (toRemove) {
  17985. var index = this.skeletons.indexOf(toRemove);
  17986. if (index !== -1) {
  17987. // Remove from the scene if found
  17988. this.skeletons.splice(index, 1);
  17989. }
  17990. return index;
  17991. };
  17992. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  17993. var index = this.morphTargetManagers.indexOf(toRemove);
  17994. if (index !== -1) {
  17995. // Remove from the scene if found
  17996. this.morphTargetManagers.splice(index, 1);
  17997. }
  17998. return index;
  17999. };
  18000. Scene.prototype.removeLight = function (toRemove) {
  18001. var index = this.lights.indexOf(toRemove);
  18002. if (index !== -1) {
  18003. // Remove from the scene if mesh found
  18004. this.lights.splice(index, 1);
  18005. this.sortLightsByPriority();
  18006. }
  18007. this.onLightRemovedObservable.notifyObservers(toRemove);
  18008. return index;
  18009. };
  18010. Scene.prototype.removeCamera = function (toRemove) {
  18011. var index = this.cameras.indexOf(toRemove);
  18012. if (index !== -1) {
  18013. // Remove from the scene if mesh found
  18014. this.cameras.splice(index, 1);
  18015. }
  18016. // Remove from activeCameras
  18017. var index2 = this.activeCameras.indexOf(toRemove);
  18018. if (index2 !== -1) {
  18019. // Remove from the scene if mesh found
  18020. this.activeCameras.splice(index2, 1);
  18021. }
  18022. // Reset the activeCamera
  18023. if (this.activeCamera === toRemove) {
  18024. if (this.cameras.length > 0) {
  18025. this.activeCamera = this.cameras[0];
  18026. }
  18027. else {
  18028. this.activeCamera = null;
  18029. }
  18030. }
  18031. this.onCameraRemovedObservable.notifyObservers(toRemove);
  18032. return index;
  18033. };
  18034. Scene.prototype.addLight = function (newLight) {
  18035. newLight.uniqueId = this.getUniqueId();
  18036. this.lights.push(newLight);
  18037. this.sortLightsByPriority();
  18038. this.onNewLightAddedObservable.notifyObservers(newLight);
  18039. };
  18040. Scene.prototype.sortLightsByPriority = function () {
  18041. if (this.requireLightSorting) {
  18042. this.lights.sort(BABYLON.Light.compareLightsPriority);
  18043. }
  18044. };
  18045. Scene.prototype.addCamera = function (newCamera) {
  18046. newCamera.uniqueId = this.getUniqueId();
  18047. var position = this.cameras.push(newCamera);
  18048. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  18049. };
  18050. /**
  18051. * Switch active camera
  18052. * @param {Camera} newCamera - new active camera
  18053. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  18054. */
  18055. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  18056. if (attachControl === void 0) { attachControl = true; }
  18057. var canvas = this._engine.getRenderingCanvas();
  18058. this.activeCamera.detachControl(canvas);
  18059. this.activeCamera = newCamera;
  18060. if (attachControl) {
  18061. newCamera.attachControl(canvas);
  18062. }
  18063. };
  18064. /**
  18065. * sets the active camera of the scene using its ID
  18066. * @param {string} id - the camera's ID
  18067. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18068. * @see activeCamera
  18069. */
  18070. Scene.prototype.setActiveCameraByID = function (id) {
  18071. var camera = this.getCameraByID(id);
  18072. if (camera) {
  18073. this.activeCamera = camera;
  18074. return camera;
  18075. }
  18076. return null;
  18077. };
  18078. /**
  18079. * sets the active camera of the scene using its name
  18080. * @param {string} name - the camera's name
  18081. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18082. * @see activeCamera
  18083. */
  18084. Scene.prototype.setActiveCameraByName = function (name) {
  18085. var camera = this.getCameraByName(name);
  18086. if (camera) {
  18087. this.activeCamera = camera;
  18088. return camera;
  18089. }
  18090. return null;
  18091. };
  18092. /**
  18093. * get a material using its id
  18094. * @param {string} the material's ID
  18095. * @return {BABYLON.Material|null} the material or null if none found.
  18096. */
  18097. Scene.prototype.getMaterialByID = function (id) {
  18098. for (var index = 0; index < this.materials.length; index++) {
  18099. if (this.materials[index].id === id) {
  18100. return this.materials[index];
  18101. }
  18102. }
  18103. return null;
  18104. };
  18105. /**
  18106. * get a material using its name
  18107. * @param {string} the material's name
  18108. * @return {BABYLON.Material|null} the material or null if none found.
  18109. */
  18110. Scene.prototype.getMaterialByName = function (name) {
  18111. for (var index = 0; index < this.materials.length; index++) {
  18112. if (this.materials[index].name === name) {
  18113. return this.materials[index];
  18114. }
  18115. }
  18116. return null;
  18117. };
  18118. Scene.prototype.getLensFlareSystemByName = function (name) {
  18119. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18120. if (this.lensFlareSystems[index].name === name) {
  18121. return this.lensFlareSystems[index];
  18122. }
  18123. }
  18124. return null;
  18125. };
  18126. Scene.prototype.getLensFlareSystemByID = function (id) {
  18127. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18128. if (this.lensFlareSystems[index].id === id) {
  18129. return this.lensFlareSystems[index];
  18130. }
  18131. }
  18132. return null;
  18133. };
  18134. Scene.prototype.getCameraByID = function (id) {
  18135. for (var index = 0; index < this.cameras.length; index++) {
  18136. if (this.cameras[index].id === id) {
  18137. return this.cameras[index];
  18138. }
  18139. }
  18140. return null;
  18141. };
  18142. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  18143. for (var index = 0; index < this.cameras.length; index++) {
  18144. if (this.cameras[index].uniqueId === uniqueId) {
  18145. return this.cameras[index];
  18146. }
  18147. }
  18148. return null;
  18149. };
  18150. /**
  18151. * get a camera using its name
  18152. * @param {string} the camera's name
  18153. * @return {BABYLON.Camera|null} the camera or null if none found.
  18154. */
  18155. Scene.prototype.getCameraByName = function (name) {
  18156. for (var index = 0; index < this.cameras.length; index++) {
  18157. if (this.cameras[index].name === name) {
  18158. return this.cameras[index];
  18159. }
  18160. }
  18161. return null;
  18162. };
  18163. /**
  18164. * get a bone using its id
  18165. * @param {string} the bone's id
  18166. * @return {BABYLON.Bone|null} the bone or null if not found
  18167. */
  18168. Scene.prototype.getBoneByID = function (id) {
  18169. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18170. var skeleton = this.skeletons[skeletonIndex];
  18171. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18172. if (skeleton.bones[boneIndex].id === id) {
  18173. return skeleton.bones[boneIndex];
  18174. }
  18175. }
  18176. }
  18177. return null;
  18178. };
  18179. /**
  18180. * get a bone using its id
  18181. * @param {string} the bone's name
  18182. * @return {BABYLON.Bone|null} the bone or null if not found
  18183. */
  18184. Scene.prototype.getBoneByName = function (name) {
  18185. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18186. var skeleton = this.skeletons[skeletonIndex];
  18187. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18188. if (skeleton.bones[boneIndex].name === name) {
  18189. return skeleton.bones[boneIndex];
  18190. }
  18191. }
  18192. }
  18193. return null;
  18194. };
  18195. /**
  18196. * get a light node using its name
  18197. * @param {string} the light's name
  18198. * @return {BABYLON.Light|null} the light or null if none found.
  18199. */
  18200. Scene.prototype.getLightByName = function (name) {
  18201. for (var index = 0; index < this.lights.length; index++) {
  18202. if (this.lights[index].name === name) {
  18203. return this.lights[index];
  18204. }
  18205. }
  18206. return null;
  18207. };
  18208. /**
  18209. * get a light node using its ID
  18210. * @param {string} the light's id
  18211. * @return {BABYLON.Light|null} the light or null if none found.
  18212. */
  18213. Scene.prototype.getLightByID = function (id) {
  18214. for (var index = 0; index < this.lights.length; index++) {
  18215. if (this.lights[index].id === id) {
  18216. return this.lights[index];
  18217. }
  18218. }
  18219. return null;
  18220. };
  18221. /**
  18222. * get a light node using its scene-generated unique ID
  18223. * @param {number} the light's unique id
  18224. * @return {BABYLON.Light|null} the light or null if none found.
  18225. */
  18226. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  18227. for (var index = 0; index < this.lights.length; index++) {
  18228. if (this.lights[index].uniqueId === uniqueId) {
  18229. return this.lights[index];
  18230. }
  18231. }
  18232. return null;
  18233. };
  18234. /**
  18235. * get a particle system by id
  18236. * @param id {number} the particle system id
  18237. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  18238. */
  18239. Scene.prototype.getParticleSystemByID = function (id) {
  18240. for (var index = 0; index < this.particleSystems.length; index++) {
  18241. if (this.particleSystems[index].id === id) {
  18242. return this.particleSystems[index];
  18243. }
  18244. }
  18245. return null;
  18246. };
  18247. /**
  18248. * get a geometry using its ID
  18249. * @param {string} the geometry's id
  18250. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  18251. */
  18252. Scene.prototype.getGeometryByID = function (id) {
  18253. for (var index = 0; index < this._geometries.length; index++) {
  18254. if (this._geometries[index].id === id) {
  18255. return this._geometries[index];
  18256. }
  18257. }
  18258. return null;
  18259. };
  18260. /**
  18261. * add a new geometry to this scene.
  18262. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  18263. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  18264. * @return {boolean} was the geometry added or not
  18265. */
  18266. Scene.prototype.pushGeometry = function (geometry, force) {
  18267. if (!force && this.getGeometryByID(geometry.id)) {
  18268. return false;
  18269. }
  18270. this._geometries.push(geometry);
  18271. //notify the collision coordinator
  18272. if (this.collisionCoordinator) {
  18273. this.collisionCoordinator.onGeometryAdded(geometry);
  18274. }
  18275. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  18276. return true;
  18277. };
  18278. /**
  18279. * Removes an existing geometry
  18280. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  18281. * @return {boolean} was the geometry removed or not
  18282. */
  18283. Scene.prototype.removeGeometry = function (geometry) {
  18284. var index = this._geometries.indexOf(geometry);
  18285. if (index > -1) {
  18286. this._geometries.splice(index, 1);
  18287. //notify the collision coordinator
  18288. if (this.collisionCoordinator) {
  18289. this.collisionCoordinator.onGeometryDeleted(geometry);
  18290. }
  18291. this.onGeometryRemovedObservable.notifyObservers(geometry);
  18292. return true;
  18293. }
  18294. return false;
  18295. };
  18296. Scene.prototype.getGeometries = function () {
  18297. return this._geometries;
  18298. };
  18299. /**
  18300. * Get the first added mesh found of a given ID
  18301. * @param {string} id - the id to search for
  18302. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18303. */
  18304. Scene.prototype.getMeshByID = function (id) {
  18305. for (var index = 0; index < this.meshes.length; index++) {
  18306. if (this.meshes[index].id === id) {
  18307. return this.meshes[index];
  18308. }
  18309. }
  18310. return null;
  18311. };
  18312. Scene.prototype.getMeshesByID = function (id) {
  18313. return this.meshes.filter(function (m) {
  18314. return m.id === id;
  18315. });
  18316. };
  18317. /**
  18318. * Get a mesh with its auto-generated unique id
  18319. * @param {number} uniqueId - the unique id to search for
  18320. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18321. */
  18322. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  18323. for (var index = 0; index < this.meshes.length; index++) {
  18324. if (this.meshes[index].uniqueId === uniqueId) {
  18325. return this.meshes[index];
  18326. }
  18327. }
  18328. return null;
  18329. };
  18330. /**
  18331. * Get a the last added mesh found of a given ID
  18332. * @param {string} id - the id to search for
  18333. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18334. */
  18335. Scene.prototype.getLastMeshByID = function (id) {
  18336. for (var index = this.meshes.length - 1; index >= 0; index--) {
  18337. if (this.meshes[index].id === id) {
  18338. return this.meshes[index];
  18339. }
  18340. }
  18341. return null;
  18342. };
  18343. /**
  18344. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  18345. * @param {string} id - the id to search for
  18346. * @return {BABYLON.Node|null} the node found or null if not found at all.
  18347. */
  18348. Scene.prototype.getLastEntryByID = function (id) {
  18349. var index;
  18350. for (index = this.meshes.length - 1; index >= 0; index--) {
  18351. if (this.meshes[index].id === id) {
  18352. return this.meshes[index];
  18353. }
  18354. }
  18355. for (index = this.cameras.length - 1; index >= 0; index--) {
  18356. if (this.cameras[index].id === id) {
  18357. return this.cameras[index];
  18358. }
  18359. }
  18360. for (index = this.lights.length - 1; index >= 0; index--) {
  18361. if (this.lights[index].id === id) {
  18362. return this.lights[index];
  18363. }
  18364. }
  18365. return null;
  18366. };
  18367. Scene.prototype.getNodeByID = function (id) {
  18368. var mesh = this.getMeshByID(id);
  18369. if (mesh) {
  18370. return mesh;
  18371. }
  18372. var light = this.getLightByID(id);
  18373. if (light) {
  18374. return light;
  18375. }
  18376. var camera = this.getCameraByID(id);
  18377. if (camera) {
  18378. return camera;
  18379. }
  18380. var bone = this.getBoneByID(id);
  18381. return bone;
  18382. };
  18383. Scene.prototype.getNodeByName = function (name) {
  18384. var mesh = this.getMeshByName(name);
  18385. if (mesh) {
  18386. return mesh;
  18387. }
  18388. var light = this.getLightByName(name);
  18389. if (light) {
  18390. return light;
  18391. }
  18392. var camera = this.getCameraByName(name);
  18393. if (camera) {
  18394. return camera;
  18395. }
  18396. var bone = this.getBoneByName(name);
  18397. return bone;
  18398. };
  18399. Scene.prototype.getMeshByName = function (name) {
  18400. for (var index = 0; index < this.meshes.length; index++) {
  18401. if (this.meshes[index].name === name) {
  18402. return this.meshes[index];
  18403. }
  18404. }
  18405. return null;
  18406. };
  18407. Scene.prototype.getSoundByName = function (name) {
  18408. var index;
  18409. if (BABYLON.AudioEngine) {
  18410. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18411. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18412. return this.mainSoundTrack.soundCollection[index];
  18413. }
  18414. }
  18415. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18416. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18417. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18418. return this.soundTracks[sdIndex].soundCollection[index];
  18419. }
  18420. }
  18421. }
  18422. }
  18423. return null;
  18424. };
  18425. Scene.prototype.getLastSkeletonByID = function (id) {
  18426. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18427. if (this.skeletons[index].id === id) {
  18428. return this.skeletons[index];
  18429. }
  18430. }
  18431. return null;
  18432. };
  18433. Scene.prototype.getSkeletonById = function (id) {
  18434. for (var index = 0; index < this.skeletons.length; index++) {
  18435. if (this.skeletons[index].id === id) {
  18436. return this.skeletons[index];
  18437. }
  18438. }
  18439. return null;
  18440. };
  18441. Scene.prototype.getSkeletonByName = function (name) {
  18442. for (var index = 0; index < this.skeletons.length; index++) {
  18443. if (this.skeletons[index].name === name) {
  18444. return this.skeletons[index];
  18445. }
  18446. }
  18447. return null;
  18448. };
  18449. Scene.prototype.getMorphTargetManagerById = function (id) {
  18450. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  18451. if (this.morphTargetManagers[index].uniqueId === id) {
  18452. return this.morphTargetManagers[index];
  18453. }
  18454. }
  18455. return null;
  18456. };
  18457. Scene.prototype.isActiveMesh = function (mesh) {
  18458. return (this._activeMeshes.indexOf(mesh) !== -1);
  18459. };
  18460. /**
  18461. * Return a the first highlight layer of the scene with a given name.
  18462. * @param name The name of the highlight layer to look for.
  18463. * @return The highlight layer if found otherwise null.
  18464. */
  18465. Scene.prototype.getHighlightLayerByName = function (name) {
  18466. for (var index = 0; index < this.highlightLayers.length; index++) {
  18467. if (this.highlightLayers[index].name === name) {
  18468. return this.highlightLayers[index];
  18469. }
  18470. }
  18471. return null;
  18472. };
  18473. Object.defineProperty(Scene.prototype, "uid", {
  18474. /**
  18475. * Return a unique id as a string which can serve as an identifier for the scene
  18476. */
  18477. get: function () {
  18478. if (!this._uid) {
  18479. this._uid = BABYLON.Tools.RandomId();
  18480. }
  18481. return this._uid;
  18482. },
  18483. enumerable: true,
  18484. configurable: true
  18485. });
  18486. /**
  18487. * Add an externaly attached data from its key.
  18488. * This method call will fail and return false, if such key already exists.
  18489. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18490. * @param key the unique key that identifies the data
  18491. * @param data the data object to associate to the key for this Engine instance
  18492. * @return true if no such key were already present and the data was added successfully, false otherwise
  18493. */
  18494. Scene.prototype.addExternalData = function (key, data) {
  18495. if (!this._externalData) {
  18496. this._externalData = new BABYLON.StringDictionary();
  18497. }
  18498. return this._externalData.add(key, data);
  18499. };
  18500. /**
  18501. * Get an externaly attached data from its key
  18502. * @param key the unique key that identifies the data
  18503. * @return the associated data, if present (can be null), or undefined if not present
  18504. */
  18505. Scene.prototype.getExternalData = function (key) {
  18506. if (!this._externalData) {
  18507. return null;
  18508. }
  18509. return this._externalData.get(key);
  18510. };
  18511. /**
  18512. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18513. * @param key the unique key that identifies the data
  18514. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18515. * @return the associated data, can be null if the factory returned null.
  18516. */
  18517. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18518. if (!this._externalData) {
  18519. this._externalData = new BABYLON.StringDictionary();
  18520. }
  18521. return this._externalData.getOrAddWithFactory(key, factory);
  18522. };
  18523. /**
  18524. * Remove an externaly attached data from the Engine instance
  18525. * @param key the unique key that identifies the data
  18526. * @return true if the data was successfully removed, false if it doesn't exist
  18527. */
  18528. Scene.prototype.removeExternalData = function (key) {
  18529. return this._externalData.remove(key);
  18530. };
  18531. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18532. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18533. var material = subMesh.getMaterial();
  18534. if (mesh.showSubMeshesBoundingBox) {
  18535. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  18536. }
  18537. if (material) {
  18538. // Render targets
  18539. if (material.getRenderTargetTextures) {
  18540. if (this._processedMaterials.indexOf(material) === -1) {
  18541. this._processedMaterials.push(material);
  18542. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18543. }
  18544. }
  18545. // Dispatch
  18546. this._activeIndices.addCount(subMesh.indexCount, false);
  18547. this._renderingManager.dispatch(subMesh);
  18548. }
  18549. }
  18550. };
  18551. Scene.prototype._isInIntermediateRendering = function () {
  18552. return this._intermediateRendering;
  18553. };
  18554. /**
  18555. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  18556. */
  18557. Scene.prototype.freezeActiveMeshes = function () {
  18558. this._evaluateActiveMeshes();
  18559. this._activeMeshesFrozen = true;
  18560. return this;
  18561. };
  18562. /**
  18563. * Use this function to restart evaluating active meshes on every frame
  18564. */
  18565. Scene.prototype.unfreezeActiveMeshes = function () {
  18566. this._activeMeshesFrozen = false;
  18567. return this;
  18568. };
  18569. Scene.prototype._evaluateActiveMeshes = function () {
  18570. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  18571. return;
  18572. }
  18573. this.activeCamera._activeMeshes.reset();
  18574. this._activeMeshes.reset();
  18575. this._renderingManager.reset();
  18576. this._processedMaterials.reset();
  18577. this._activeParticleSystems.reset();
  18578. this._activeSkeletons.reset();
  18579. this._softwareSkinnedMeshes.reset();
  18580. if (this._boundingBoxRenderer) {
  18581. this._boundingBoxRenderer.reset();
  18582. }
  18583. // Meshes
  18584. var meshes;
  18585. var len;
  18586. if (this._selectionOctree) {
  18587. var selection = this._selectionOctree.select(this._frustumPlanes);
  18588. meshes = selection.data;
  18589. len = selection.length;
  18590. }
  18591. else {
  18592. len = this.meshes.length;
  18593. meshes = this.meshes;
  18594. }
  18595. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18596. var mesh = meshes[meshIndex];
  18597. if (mesh.isBlocked) {
  18598. continue;
  18599. }
  18600. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18601. if (!mesh.isReady() || !mesh.isEnabled()) {
  18602. continue;
  18603. }
  18604. mesh.computeWorldMatrix();
  18605. // Intersections
  18606. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18607. this._meshesForIntersections.pushNoDuplicate(mesh);
  18608. }
  18609. // Switch to current LOD
  18610. var meshLOD = mesh.getLOD(this.activeCamera);
  18611. if (!meshLOD) {
  18612. continue;
  18613. }
  18614. mesh._preActivate();
  18615. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18616. this._activeMeshes.push(mesh);
  18617. this.activeCamera._activeMeshes.push(mesh);
  18618. mesh._activate(this._renderId);
  18619. if (meshLOD !== mesh) {
  18620. meshLOD._activate(this._renderId);
  18621. }
  18622. this._activeMesh(mesh, meshLOD);
  18623. }
  18624. }
  18625. // Particle systems
  18626. this._particlesDuration.beginMonitoring();
  18627. var beforeParticlesDate = BABYLON.Tools.Now;
  18628. if (this.particlesEnabled) {
  18629. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18630. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18631. var particleSystem = this.particleSystems[particleIndex];
  18632. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  18633. continue;
  18634. }
  18635. var emitter = particleSystem.emitter;
  18636. if (!emitter.position || emitter.isEnabled()) {
  18637. this._activeParticleSystems.push(particleSystem);
  18638. particleSystem.animate();
  18639. this._renderingManager.dispatchParticles(particleSystem);
  18640. }
  18641. }
  18642. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18643. }
  18644. this._particlesDuration.endMonitoring(false);
  18645. };
  18646. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18647. if (mesh.skeleton && this.skeletonsEnabled) {
  18648. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18649. mesh.skeleton.prepare();
  18650. }
  18651. if (!mesh.computeBonesUsingShaders) {
  18652. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18653. }
  18654. }
  18655. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18656. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18657. }
  18658. if (mesh && mesh.subMeshes) {
  18659. // Submeshes Octrees
  18660. var len;
  18661. var subMeshes;
  18662. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18663. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18664. len = intersections.length;
  18665. subMeshes = intersections.data;
  18666. }
  18667. else {
  18668. subMeshes = mesh.subMeshes;
  18669. len = subMeshes.length;
  18670. }
  18671. for (var subIndex = 0; subIndex < len; subIndex++) {
  18672. var subMesh = subMeshes[subIndex];
  18673. this._evaluateSubMesh(subMesh, mesh);
  18674. }
  18675. }
  18676. };
  18677. Scene.prototype.updateTransformMatrix = function (force) {
  18678. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18679. };
  18680. Scene.prototype._renderForCamera = function (camera) {
  18681. var engine = this._engine;
  18682. var startTime = BABYLON.Tools.Now;
  18683. this.activeCamera = camera;
  18684. if (!this.activeCamera)
  18685. throw new Error("Active camera not set");
  18686. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18687. // Viewport
  18688. engine.setViewport(this.activeCamera.viewport);
  18689. // Camera
  18690. this.resetCachedMaterial();
  18691. this._renderId++;
  18692. this.updateTransformMatrix();
  18693. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18694. // Meshes
  18695. this._evaluateActiveMeshesDuration.beginMonitoring();
  18696. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18697. this._evaluateActiveMeshes();
  18698. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18699. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18700. // Software skinning
  18701. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18702. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18703. mesh.applySkeleton(mesh.skeleton);
  18704. }
  18705. // Render targets
  18706. this._renderTargetsDuration.beginMonitoring();
  18707. var needsRestoreFrameBuffer = false;
  18708. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18709. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  18710. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  18711. }
  18712. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18713. this._intermediateRendering = true;
  18714. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18715. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18716. var renderTarget = this._renderTargets.data[renderIndex];
  18717. if (renderTarget._shouldRender()) {
  18718. this._renderId++;
  18719. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18720. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18721. }
  18722. }
  18723. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18724. this._intermediateRendering = false;
  18725. this._renderId++;
  18726. needsRestoreFrameBuffer = true; // Restore back buffer
  18727. }
  18728. // Render HighlightLayer Texture
  18729. var stencilState = this._engine.getStencilBuffer();
  18730. var renderhighlights = false;
  18731. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18732. this._intermediateRendering = true;
  18733. for (var i = 0; i < this.highlightLayers.length; i++) {
  18734. var highlightLayer = this.highlightLayers[i];
  18735. if (highlightLayer.shouldRender() &&
  18736. (!highlightLayer.camera ||
  18737. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18738. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18739. renderhighlights = true;
  18740. var renderTarget = highlightLayer._mainTexture;
  18741. if (renderTarget._shouldRender()) {
  18742. this._renderId++;
  18743. renderTarget.render(false, false);
  18744. needsRestoreFrameBuffer = true;
  18745. }
  18746. }
  18747. }
  18748. this._intermediateRendering = false;
  18749. this._renderId++;
  18750. }
  18751. if (needsRestoreFrameBuffer) {
  18752. engine.restoreDefaultFramebuffer(); // Restore back buffer
  18753. }
  18754. this._renderTargetsDuration.endMonitoring(false);
  18755. // Prepare Frame
  18756. this.postProcessManager._prepareFrame();
  18757. this._renderDuration.beginMonitoring();
  18758. // Backgrounds
  18759. var layerIndex;
  18760. var layer;
  18761. if (this.layers.length) {
  18762. engine.setDepthBuffer(false);
  18763. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18764. layer = this.layers[layerIndex];
  18765. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18766. layer.render();
  18767. }
  18768. }
  18769. engine.setDepthBuffer(true);
  18770. }
  18771. // Render
  18772. BABYLON.Tools.StartPerformanceCounter("Main render");
  18773. // Activate HighlightLayer stencil
  18774. if (renderhighlights) {
  18775. this._engine.setStencilBuffer(true);
  18776. }
  18777. this._renderingManager.render(null, null, true, true);
  18778. // Restore HighlightLayer stencil
  18779. if (renderhighlights) {
  18780. this._engine.setStencilBuffer(stencilState);
  18781. }
  18782. BABYLON.Tools.EndPerformanceCounter("Main render");
  18783. // Bounding boxes
  18784. if (this._boundingBoxRenderer) {
  18785. this._boundingBoxRenderer.render();
  18786. }
  18787. // Lens flares
  18788. if (this.lensFlaresEnabled) {
  18789. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18790. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18791. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18792. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18793. lensFlareSystem.render();
  18794. }
  18795. }
  18796. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18797. }
  18798. // Foregrounds
  18799. if (this.layers.length) {
  18800. engine.setDepthBuffer(false);
  18801. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18802. layer = this.layers[layerIndex];
  18803. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18804. layer.render();
  18805. }
  18806. }
  18807. engine.setDepthBuffer(true);
  18808. }
  18809. // Highlight Layer
  18810. if (renderhighlights) {
  18811. engine.setDepthBuffer(false);
  18812. for (var i = 0; i < this.highlightLayers.length; i++) {
  18813. if (this.highlightLayers[i].shouldRender()) {
  18814. this.highlightLayers[i].render();
  18815. }
  18816. }
  18817. engine.setDepthBuffer(true);
  18818. }
  18819. this._renderDuration.endMonitoring(false);
  18820. // Finalize frame
  18821. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18822. // Update camera
  18823. this.activeCamera._updateFromScene();
  18824. // Reset some special arrays
  18825. this._renderTargets.reset();
  18826. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18827. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18828. };
  18829. Scene.prototype._processSubCameras = function (camera) {
  18830. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18831. this._renderForCamera(camera);
  18832. return;
  18833. }
  18834. // rig cameras
  18835. for (var index = 0; index < camera._rigCameras.length; index++) {
  18836. this._renderForCamera(camera._rigCameras[index]);
  18837. }
  18838. this.activeCamera = camera;
  18839. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18840. // Update camera
  18841. this.activeCamera._updateFromScene();
  18842. };
  18843. Scene.prototype._checkIntersections = function () {
  18844. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18845. var sourceMesh = this._meshesForIntersections.data[index];
  18846. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18847. var action = sourceMesh.actionManager.actions[actionIndex];
  18848. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18849. var parameters = action.getTriggerParameter();
  18850. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18851. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18852. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18853. if (areIntersecting && currentIntersectionInProgress === -1) {
  18854. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18855. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18856. sourceMesh._intersectionsInProgress.push(otherMesh);
  18857. }
  18858. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18859. sourceMesh._intersectionsInProgress.push(otherMesh);
  18860. }
  18861. }
  18862. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18863. //They intersected, and now they don't.
  18864. //is this trigger an exit trigger? execute an event.
  18865. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18866. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18867. }
  18868. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18869. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18870. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18871. }
  18872. }
  18873. }
  18874. }
  18875. }
  18876. };
  18877. Scene.prototype.render = function () {
  18878. if (this.isDisposed) {
  18879. return;
  18880. }
  18881. this._interFrameDuration.endMonitoring();
  18882. this._lastFrameDuration.beginMonitoring();
  18883. this._particlesDuration.fetchNewFrame();
  18884. this._spritesDuration.fetchNewFrame();
  18885. this._activeParticles.fetchNewFrame();
  18886. this._renderDuration.fetchNewFrame();
  18887. this._renderTargetsDuration.fetchNewFrame();
  18888. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18889. this._totalVertices.fetchNewFrame();
  18890. this._activeIndices.fetchNewFrame();
  18891. this._activeBones.fetchNewFrame();
  18892. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18893. this._meshesForIntersections.reset();
  18894. this.resetCachedMaterial();
  18895. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18896. // Actions
  18897. if (this.actionManager) {
  18898. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18899. }
  18900. //Simplification Queue
  18901. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18902. this.simplificationQueue.executeNext();
  18903. }
  18904. if (this._engine.isDeterministicLockStep()) {
  18905. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  18906. var defaultTimeStep = (60.0 / 1000.0);
  18907. if (this._physicsEngine) {
  18908. defaultTimeStep = this._physicsEngine.getTimeStep();
  18909. }
  18910. var maxSubSteps = this._engine.getLockstepMaxSteps();
  18911. this._timeAccumulator += deltaTime;
  18912. // compute the amount of fixed steps we should have taken since the last step
  18913. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  18914. internalSteps = Math.min(internalSteps, maxSubSteps);
  18915. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  18916. this.onBeforeStepObservable.notifyObservers(this);
  18917. // Animations
  18918. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  18919. this._animate();
  18920. // Physics
  18921. if (this._physicsEngine) {
  18922. BABYLON.Tools.StartPerformanceCounter("Physics");
  18923. this._physicsEngine._step(defaultTimeStep);
  18924. BABYLON.Tools.EndPerformanceCounter("Physics");
  18925. }
  18926. this._timeAccumulator -= defaultTimeStep;
  18927. this.onAfterStepObservable.notifyObservers(this);
  18928. this._currentStepId++;
  18929. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  18930. this._evaluateActiveMeshes();
  18931. }
  18932. }
  18933. }
  18934. else {
  18935. // Animations
  18936. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18937. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18938. this._animate();
  18939. // Physics
  18940. if (this._physicsEngine) {
  18941. BABYLON.Tools.StartPerformanceCounter("Physics");
  18942. this._physicsEngine._step(deltaTime / 1000.0);
  18943. BABYLON.Tools.EndPerformanceCounter("Physics");
  18944. }
  18945. }
  18946. // Before render
  18947. this.onBeforeRenderObservable.notifyObservers(this);
  18948. // Customs render targets
  18949. this._renderTargetsDuration.beginMonitoring();
  18950. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18951. var engine = this.getEngine();
  18952. var currentActiveCamera = this.activeCamera;
  18953. if (this.renderTargetsEnabled) {
  18954. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18955. this._intermediateRendering = true;
  18956. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18957. var renderTarget = this.customRenderTargets[customIndex];
  18958. if (renderTarget._shouldRender()) {
  18959. this._renderId++;
  18960. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18961. if (!this.activeCamera)
  18962. throw new Error("Active camera not set");
  18963. // Viewport
  18964. engine.setViewport(this.activeCamera.viewport);
  18965. // Camera
  18966. this.updateTransformMatrix();
  18967. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18968. }
  18969. }
  18970. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18971. this._intermediateRendering = false;
  18972. this._renderId++;
  18973. }
  18974. // Restore back buffer
  18975. if (this.customRenderTargets.length > 0) {
  18976. engine.restoreDefaultFramebuffer();
  18977. }
  18978. this._renderTargetsDuration.endMonitoring();
  18979. this.activeCamera = currentActiveCamera;
  18980. // Procedural textures
  18981. if (this.proceduralTexturesEnabled) {
  18982. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18983. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18984. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18985. if (proceduralTexture._shouldRender()) {
  18986. proceduralTexture.render();
  18987. }
  18988. }
  18989. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18990. }
  18991. // Clear
  18992. if (this.autoClearDepthAndStencil || this.autoClear) {
  18993. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  18994. }
  18995. // Shadows
  18996. if (this.shadowsEnabled) {
  18997. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18998. var light = this.lights[lightIndex];
  18999. var shadowGenerator = light.getShadowGenerator();
  19000. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  19001. var shadowMap = shadowGenerator.getShadowMap();
  19002. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  19003. this._renderTargets.push(shadowMap);
  19004. }
  19005. }
  19006. }
  19007. }
  19008. // Depth renderer
  19009. if (this._depthRenderer) {
  19010. this._renderTargets.push(this._depthRenderer.getDepthMap());
  19011. }
  19012. // Geometry renderer
  19013. if (this._geometryBufferRenderer) {
  19014. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  19015. }
  19016. // RenderPipeline
  19017. if (this._postProcessRenderPipelineManager) {
  19018. this._postProcessRenderPipelineManager.update();
  19019. }
  19020. // Multi-cameras?
  19021. if (this.activeCameras.length > 0) {
  19022. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  19023. if (cameraIndex > 0) {
  19024. this._engine.clear(null, false, true, true);
  19025. }
  19026. this._processSubCameras(this.activeCameras[cameraIndex]);
  19027. }
  19028. }
  19029. else {
  19030. if (!this.activeCamera) {
  19031. throw new Error("No camera defined");
  19032. }
  19033. this._processSubCameras(this.activeCamera);
  19034. }
  19035. // Intersection checks
  19036. this._checkIntersections();
  19037. // Update the audio listener attached to the camera
  19038. if (BABYLON.AudioEngine) {
  19039. this._updateAudioParameters();
  19040. }
  19041. // After render
  19042. if (this.afterRender) {
  19043. this.afterRender();
  19044. }
  19045. this.onAfterRenderObservable.notifyObservers(this);
  19046. // Cleaning
  19047. for (var index = 0; index < this._toBeDisposed.length; index++) {
  19048. this._toBeDisposed.data[index].dispose();
  19049. this._toBeDisposed[index] = null;
  19050. }
  19051. this._toBeDisposed.reset();
  19052. if (this.dumpNextRenderTargets) {
  19053. this.dumpNextRenderTargets = false;
  19054. }
  19055. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  19056. this._interFrameDuration.beginMonitoring();
  19057. this._lastFrameDuration.endMonitoring();
  19058. this._totalMeshesCounter.addCount(this.meshes.length, true);
  19059. this._totalLightsCounter.addCount(this.lights.length, true);
  19060. this._totalMaterialsCounter.addCount(this.materials.length, true);
  19061. this._totalTexturesCounter.addCount(this.textures.length, true);
  19062. this._activeBones.addCount(0, true);
  19063. this._activeIndices.addCount(0, true);
  19064. this._activeParticles.addCount(0, true);
  19065. };
  19066. Scene.prototype._updateAudioParameters = function () {
  19067. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  19068. return;
  19069. }
  19070. var listeningCamera;
  19071. var audioEngine = BABYLON.Engine.audioEngine;
  19072. if (this.activeCameras.length > 0) {
  19073. listeningCamera = this.activeCameras[0];
  19074. }
  19075. else {
  19076. listeningCamera = this.activeCamera;
  19077. }
  19078. if (listeningCamera && audioEngine.canUseWebAudio) {
  19079. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  19080. // for VR cameras
  19081. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  19082. listeningCamera = listeningCamera.rigCameras[0];
  19083. }
  19084. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  19085. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  19086. cameraDirection.normalize();
  19087. // To avoid some errors on GearVR
  19088. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  19089. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  19090. }
  19091. var i;
  19092. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19093. var sound = this.mainSoundTrack.soundCollection[i];
  19094. if (sound.useCustomAttenuation) {
  19095. sound.updateDistanceFromListener();
  19096. }
  19097. }
  19098. for (i = 0; i < this.soundTracks.length; i++) {
  19099. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19100. sound = this.soundTracks[i].soundCollection[j];
  19101. if (sound.useCustomAttenuation) {
  19102. sound.updateDistanceFromListener();
  19103. }
  19104. }
  19105. }
  19106. }
  19107. };
  19108. Object.defineProperty(Scene.prototype, "audioEnabled", {
  19109. // Audio
  19110. get: function () {
  19111. return this._audioEnabled;
  19112. },
  19113. set: function (value) {
  19114. this._audioEnabled = value;
  19115. if (BABYLON.AudioEngine) {
  19116. if (this._audioEnabled) {
  19117. this._enableAudio();
  19118. }
  19119. else {
  19120. this._disableAudio();
  19121. }
  19122. }
  19123. },
  19124. enumerable: true,
  19125. configurable: true
  19126. });
  19127. Scene.prototype._disableAudio = function () {
  19128. var i;
  19129. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19130. this.mainSoundTrack.soundCollection[i].pause();
  19131. }
  19132. for (i = 0; i < this.soundTracks.length; i++) {
  19133. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19134. this.soundTracks[i].soundCollection[j].pause();
  19135. }
  19136. }
  19137. };
  19138. Scene.prototype._enableAudio = function () {
  19139. var i;
  19140. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19141. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  19142. this.mainSoundTrack.soundCollection[i].play();
  19143. }
  19144. }
  19145. for (i = 0; i < this.soundTracks.length; i++) {
  19146. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19147. if (this.soundTracks[i].soundCollection[j].isPaused) {
  19148. this.soundTracks[i].soundCollection[j].play();
  19149. }
  19150. }
  19151. }
  19152. };
  19153. Object.defineProperty(Scene.prototype, "headphone", {
  19154. get: function () {
  19155. return this._headphone;
  19156. },
  19157. set: function (value) {
  19158. this._headphone = value;
  19159. if (BABYLON.AudioEngine) {
  19160. if (this._headphone) {
  19161. this._switchAudioModeForHeadphones();
  19162. }
  19163. else {
  19164. this._switchAudioModeForNormalSpeakers();
  19165. }
  19166. }
  19167. },
  19168. enumerable: true,
  19169. configurable: true
  19170. });
  19171. Scene.prototype._switchAudioModeForHeadphones = function () {
  19172. this.mainSoundTrack.switchPanningModelToHRTF();
  19173. for (var i = 0; i < this.soundTracks.length; i++) {
  19174. this.soundTracks[i].switchPanningModelToHRTF();
  19175. }
  19176. };
  19177. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  19178. this.mainSoundTrack.switchPanningModelToEqualPower();
  19179. for (var i = 0; i < this.soundTracks.length; i++) {
  19180. this.soundTracks[i].switchPanningModelToEqualPower();
  19181. }
  19182. };
  19183. Scene.prototype.enableDepthRenderer = function () {
  19184. if (this._depthRenderer) {
  19185. return this._depthRenderer;
  19186. }
  19187. this._depthRenderer = new BABYLON.DepthRenderer(this);
  19188. return this._depthRenderer;
  19189. };
  19190. Scene.prototype.disableDepthRenderer = function () {
  19191. if (!this._depthRenderer) {
  19192. return;
  19193. }
  19194. this._depthRenderer.dispose();
  19195. this._depthRenderer = null;
  19196. };
  19197. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  19198. if (ratio === void 0) { ratio = 1; }
  19199. if (this._geometryBufferRenderer) {
  19200. return this._geometryBufferRenderer;
  19201. }
  19202. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  19203. if (!this._geometryBufferRenderer.isSupported) {
  19204. this._geometryBufferRenderer = null;
  19205. }
  19206. return this._geometryBufferRenderer;
  19207. };
  19208. Scene.prototype.disableGeometryBufferRenderer = function () {
  19209. if (!this._geometryBufferRenderer) {
  19210. return;
  19211. }
  19212. this._geometryBufferRenderer.dispose();
  19213. this._geometryBufferRenderer = null;
  19214. };
  19215. Scene.prototype.freezeMaterials = function () {
  19216. for (var i = 0; i < this.materials.length; i++) {
  19217. this.materials[i].freeze();
  19218. }
  19219. };
  19220. Scene.prototype.unfreezeMaterials = function () {
  19221. for (var i = 0; i < this.materials.length; i++) {
  19222. this.materials[i].unfreeze();
  19223. }
  19224. };
  19225. Scene.prototype.dispose = function () {
  19226. this.beforeRender = null;
  19227. this.afterRender = null;
  19228. this.skeletons = [];
  19229. this.morphTargetManagers = [];
  19230. this.importedMeshesFiles = new Array();
  19231. this.resetCachedMaterial();
  19232. if (this._depthRenderer) {
  19233. this._depthRenderer.dispose();
  19234. }
  19235. if (this._gamepadManager) {
  19236. this._gamepadManager.dispose();
  19237. this._gamepadManager = null;
  19238. }
  19239. // Smart arrays
  19240. if (this.activeCamera) {
  19241. this.activeCamera._activeMeshes.dispose();
  19242. this.activeCamera = null;
  19243. }
  19244. this._activeMeshes.dispose();
  19245. this._renderingManager.dispose();
  19246. this._processedMaterials.dispose();
  19247. this._activeParticleSystems.dispose();
  19248. this._activeSkeletons.dispose();
  19249. this._softwareSkinnedMeshes.dispose();
  19250. this._renderTargets.dispose();
  19251. if (this._boundingBoxRenderer) {
  19252. this._boundingBoxRenderer.dispose();
  19253. }
  19254. this._meshesForIntersections.dispose();
  19255. this._toBeDisposed.dispose();
  19256. // Debug layer
  19257. if (this._debugLayer) {
  19258. this._debugLayer.hide();
  19259. }
  19260. // Events
  19261. this.onDisposeObservable.notifyObservers(this);
  19262. this.onDisposeObservable.clear();
  19263. this.onBeforeRenderObservable.clear();
  19264. this.onAfterRenderObservable.clear();
  19265. this.detachControl();
  19266. // Release sounds & sounds tracks
  19267. if (BABYLON.AudioEngine) {
  19268. this.disposeSounds();
  19269. }
  19270. // VR Helper
  19271. if (this.VRHelper) {
  19272. this.VRHelper.dispose();
  19273. }
  19274. // Detach cameras
  19275. var canvas = this._engine.getRenderingCanvas();
  19276. var index;
  19277. for (index = 0; index < this.cameras.length; index++) {
  19278. this.cameras[index].detachControl(canvas);
  19279. }
  19280. // Release lights
  19281. while (this.lights.length) {
  19282. this.lights[0].dispose();
  19283. }
  19284. // Release meshes
  19285. while (this.meshes.length) {
  19286. this.meshes[0].dispose(true);
  19287. }
  19288. // Release cameras
  19289. while (this.cameras.length) {
  19290. this.cameras[0].dispose();
  19291. }
  19292. // Release materials
  19293. if (this.defaultMaterial) {
  19294. this.defaultMaterial.dispose();
  19295. }
  19296. while (this.multiMaterials.length) {
  19297. this.multiMaterials[0].dispose();
  19298. }
  19299. while (this.materials.length) {
  19300. this.materials[0].dispose();
  19301. }
  19302. // Release particles
  19303. while (this.particleSystems.length) {
  19304. this.particleSystems[0].dispose();
  19305. }
  19306. // Release sprites
  19307. while (this.spriteManagers.length) {
  19308. this.spriteManagers[0].dispose();
  19309. }
  19310. // Release postProcesses
  19311. while (this.postProcesses.length) {
  19312. this.postProcesses[0].dispose();
  19313. }
  19314. // Release layers
  19315. while (this.layers.length) {
  19316. this.layers[0].dispose();
  19317. }
  19318. while (this.highlightLayers.length) {
  19319. this.highlightLayers[0].dispose();
  19320. }
  19321. // Release textures
  19322. while (this.textures.length) {
  19323. this.textures[0].dispose();
  19324. }
  19325. // Release UBO
  19326. this._sceneUbo.dispose();
  19327. // Post-processes
  19328. this.postProcessManager.dispose();
  19329. if (this._postProcessRenderPipelineManager) {
  19330. this._postProcessRenderPipelineManager.dispose();
  19331. }
  19332. // Physics
  19333. if (this._physicsEngine) {
  19334. this.disablePhysicsEngine();
  19335. }
  19336. // Remove from engine
  19337. index = this._engine.scenes.indexOf(this);
  19338. if (index > -1) {
  19339. this._engine.scenes.splice(index, 1);
  19340. }
  19341. this._engine.wipeCaches();
  19342. this._engine = null;
  19343. this.defaultMaterial = null;
  19344. this.multiMaterials = null;
  19345. this.materials = null;
  19346. };
  19347. Object.defineProperty(Scene.prototype, "isDisposed", {
  19348. get: function () {
  19349. return !this._engine;
  19350. },
  19351. enumerable: true,
  19352. configurable: true
  19353. });
  19354. // Release sounds & sounds tracks
  19355. Scene.prototype.disposeSounds = function () {
  19356. this.mainSoundTrack.dispose();
  19357. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  19358. this.soundTracks[scIndex].dispose();
  19359. }
  19360. };
  19361. // Octrees
  19362. Scene.prototype.getWorldExtends = function () {
  19363. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19364. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19365. for (var index = 0; index < this.meshes.length; index++) {
  19366. var mesh = this.meshes[index];
  19367. mesh.computeWorldMatrix(true);
  19368. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  19369. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  19370. BABYLON.Tools.CheckExtends(minBox, min, max);
  19371. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19372. }
  19373. return {
  19374. min: min,
  19375. max: max
  19376. };
  19377. };
  19378. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  19379. if (maxCapacity === void 0) { maxCapacity = 64; }
  19380. if (maxDepth === void 0) { maxDepth = 2; }
  19381. if (!this._selectionOctree) {
  19382. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  19383. }
  19384. var worldExtends = this.getWorldExtends();
  19385. // Update octree
  19386. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  19387. return this._selectionOctree;
  19388. };
  19389. // Picking
  19390. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  19391. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  19392. var engine = this._engine;
  19393. if (!camera) {
  19394. if (!this.activeCamera)
  19395. throw new Error("Active camera not set");
  19396. camera = this.activeCamera;
  19397. }
  19398. var cameraViewport = camera.viewport;
  19399. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19400. // Moving coordinates to local viewport world
  19401. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19402. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19403. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  19404. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  19405. };
  19406. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  19407. if (!BABYLON.PickingInfo) {
  19408. return null;
  19409. }
  19410. var engine = this._engine;
  19411. if (!camera) {
  19412. if (!this.activeCamera)
  19413. throw new Error("Active camera not set");
  19414. camera = this.activeCamera;
  19415. }
  19416. var cameraViewport = camera.viewport;
  19417. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19418. var identity = BABYLON.Matrix.Identity();
  19419. // Moving coordinates to local viewport world
  19420. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19421. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19422. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  19423. };
  19424. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  19425. if (!BABYLON.PickingInfo) {
  19426. return null;
  19427. }
  19428. var pickingInfo = null;
  19429. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19430. var mesh = this.meshes[meshIndex];
  19431. if (predicate) {
  19432. if (!predicate(mesh)) {
  19433. continue;
  19434. }
  19435. }
  19436. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19437. continue;
  19438. }
  19439. var world = mesh.getWorldMatrix();
  19440. var ray = rayFunction(world);
  19441. var result = mesh.intersects(ray, fastCheck);
  19442. if (!result || !result.hit)
  19443. continue;
  19444. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19445. continue;
  19446. pickingInfo = result;
  19447. if (fastCheck) {
  19448. break;
  19449. }
  19450. }
  19451. return pickingInfo || new BABYLON.PickingInfo();
  19452. };
  19453. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  19454. if (!BABYLON.PickingInfo) {
  19455. return null;
  19456. }
  19457. var pickingInfos = new Array();
  19458. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19459. var mesh = this.meshes[meshIndex];
  19460. if (predicate) {
  19461. if (!predicate(mesh)) {
  19462. continue;
  19463. }
  19464. }
  19465. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19466. continue;
  19467. }
  19468. var world = mesh.getWorldMatrix();
  19469. var ray = rayFunction(world);
  19470. var result = mesh.intersects(ray, false);
  19471. if (!result || !result.hit)
  19472. continue;
  19473. pickingInfos.push(result);
  19474. }
  19475. return pickingInfos;
  19476. };
  19477. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  19478. if (!BABYLON.PickingInfo) {
  19479. return null;
  19480. }
  19481. var pickingInfo = null;
  19482. camera = camera || this.activeCamera;
  19483. if (this.spriteManagers.length > 0) {
  19484. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  19485. var spriteManager = this.spriteManagers[spriteIndex];
  19486. if (!spriteManager.isPickable) {
  19487. continue;
  19488. }
  19489. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  19490. if (!result || !result.hit)
  19491. continue;
  19492. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19493. continue;
  19494. pickingInfo = result;
  19495. if (fastCheck) {
  19496. break;
  19497. }
  19498. }
  19499. }
  19500. return pickingInfo || new BABYLON.PickingInfo();
  19501. };
  19502. /** Launch a ray to try to pick a mesh in the scene
  19503. * @param x position on screen
  19504. * @param y position on screen
  19505. * @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
  19506. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19507. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19508. */
  19509. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  19510. var _this = this;
  19511. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  19512. };
  19513. /** Launch a ray to try to pick a sprite in the scene
  19514. * @param x position on screen
  19515. * @param y position on screen
  19516. * @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
  19517. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19518. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19519. */
  19520. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  19521. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  19522. };
  19523. /** Use the given ray to pick a mesh in the scene
  19524. * @param ray The ray to use to pick meshes
  19525. * @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
  19526. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19527. */
  19528. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  19529. var _this = this;
  19530. return this._internalPick(function (world) {
  19531. if (!_this._pickWithRayInverseMatrix) {
  19532. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19533. }
  19534. world.invertToRef(_this._pickWithRayInverseMatrix);
  19535. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19536. }, predicate, fastCheck);
  19537. };
  19538. /**
  19539. * Launch a ray to try to pick a mesh in the scene
  19540. * @param x X position on screen
  19541. * @param y Y position on screen
  19542. * @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
  19543. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19544. */
  19545. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  19546. var _this = this;
  19547. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  19548. };
  19549. /**
  19550. * Launch a ray to try to pick a mesh in the scene
  19551. * @param ray Ray to use
  19552. * @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
  19553. */
  19554. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  19555. var _this = this;
  19556. return this._internalMultiPick(function (world) {
  19557. if (!_this._pickWithRayInverseMatrix) {
  19558. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19559. }
  19560. world.invertToRef(_this._pickWithRayInverseMatrix);
  19561. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19562. }, predicate);
  19563. };
  19564. Scene.prototype.setPointerOverMesh = function (mesh) {
  19565. if (this._pointerOverMesh === mesh) {
  19566. return;
  19567. }
  19568. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19569. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19570. }
  19571. this._pointerOverMesh = mesh;
  19572. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19573. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19574. }
  19575. };
  19576. Scene.prototype.getPointerOverMesh = function () {
  19577. return this._pointerOverMesh;
  19578. };
  19579. Scene.prototype.setPointerOverSprite = function (sprite) {
  19580. if (this._pointerOverSprite === sprite) {
  19581. return;
  19582. }
  19583. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19584. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19585. }
  19586. this._pointerOverSprite = sprite;
  19587. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19588. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19589. }
  19590. };
  19591. Scene.prototype.getPointerOverSprite = function () {
  19592. return this._pointerOverSprite;
  19593. };
  19594. // Physics
  19595. Scene.prototype.getPhysicsEngine = function () {
  19596. return this._physicsEngine;
  19597. };
  19598. /**
  19599. * Enables physics to the current scene
  19600. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19601. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19602. * @return {boolean} was the physics engine initialized
  19603. */
  19604. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19605. if (this._physicsEngine) {
  19606. return true;
  19607. }
  19608. try {
  19609. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19610. return true;
  19611. }
  19612. catch (e) {
  19613. BABYLON.Tools.Error(e.message);
  19614. return false;
  19615. }
  19616. };
  19617. Scene.prototype.disablePhysicsEngine = function () {
  19618. if (!this._physicsEngine) {
  19619. return;
  19620. }
  19621. this._physicsEngine.dispose();
  19622. this._physicsEngine = undefined;
  19623. };
  19624. Scene.prototype.isPhysicsEnabled = function () {
  19625. return this._physicsEngine !== undefined;
  19626. };
  19627. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19628. var mesh = compound.parts[0].mesh;
  19629. mesh.physicsImpostor.dispose();
  19630. mesh.physicsImpostor = null;
  19631. };
  19632. // Misc.
  19633. Scene.prototype._rebuildGeometries = function () {
  19634. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  19635. var geometry = _a[_i];
  19636. geometry._rebuild();
  19637. }
  19638. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  19639. var mesh = _c[_b];
  19640. mesh._rebuild();
  19641. }
  19642. if (this.postProcessManager) {
  19643. this.postProcessManager._rebuild();
  19644. }
  19645. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  19646. var layer = _e[_d];
  19647. layer._rebuild();
  19648. }
  19649. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  19650. var highlightLayer = _g[_f];
  19651. highlightLayer._rebuild();
  19652. }
  19653. if (this._boundingBoxRenderer) {
  19654. this._boundingBoxRenderer._rebuild();
  19655. }
  19656. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  19657. var system = _j[_h];
  19658. system.rebuild();
  19659. }
  19660. if (this._postProcessRenderPipelineManager) {
  19661. this._postProcessRenderPipelineManager._rebuild();
  19662. }
  19663. };
  19664. Scene.prototype._rebuildTextures = function () {
  19665. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  19666. var texture = _a[_i];
  19667. texture._rebuild();
  19668. }
  19669. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19670. };
  19671. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  19672. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19673. if (replace === void 0) { replace = false; }
  19674. if (attachCameraControls === void 0) { attachCameraControls = false; }
  19675. // Dispose existing camera or light in replace mode.
  19676. if (replace) {
  19677. if (this.activeCamera) {
  19678. this.activeCamera.dispose();
  19679. this.activeCamera = null;
  19680. }
  19681. if (this.lights) {
  19682. for (var i = 0; i < this.lights.length; i++) {
  19683. this.lights[i].dispose();
  19684. }
  19685. }
  19686. }
  19687. // Light
  19688. if (this.lights.length === 0) {
  19689. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19690. }
  19691. // Camera
  19692. if (!this.activeCamera) {
  19693. var worldExtends = this.getWorldExtends();
  19694. var worldSize = worldExtends.max.subtract(worldExtends.min);
  19695. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  19696. var camera;
  19697. var radius = worldSize.length() * 1.5;
  19698. if (createArcRotateCamera) {
  19699. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  19700. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  19701. arcRotateCamera.wheelPrecision = 100 / radius;
  19702. camera = arcRotateCamera;
  19703. }
  19704. else {
  19705. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  19706. freeCamera.setTarget(worldCenter);
  19707. camera = freeCamera;
  19708. }
  19709. camera.minZ = radius * 0.01;
  19710. camera.maxZ = radius * 100;
  19711. camera.speed = radius * 0.2;
  19712. this.activeCamera = camera;
  19713. if (attachCameraControls) {
  19714. camera.attachControl(this.getEngine().getRenderingCanvas());
  19715. }
  19716. }
  19717. };
  19718. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  19719. if (pbr === void 0) { pbr = false; }
  19720. if (scale === void 0) { scale = 1000; }
  19721. if (blur === void 0) { blur = 0; }
  19722. if (environmentTexture) {
  19723. this.environmentTexture = environmentTexture;
  19724. }
  19725. if (!this.environmentTexture) {
  19726. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  19727. return;
  19728. }
  19729. // Skybox
  19730. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  19731. if (pbr) {
  19732. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  19733. hdrSkyboxMaterial.backFaceCulling = false;
  19734. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19735. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19736. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  19737. hdrSkyboxMaterial.disableLighting = true;
  19738. hdrSkyboxMaterial.twoSidedLighting = true;
  19739. hdrSkybox.infiniteDistance = true;
  19740. hdrSkybox.material = hdrSkyboxMaterial;
  19741. }
  19742. else {
  19743. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  19744. skyboxMaterial.backFaceCulling = false;
  19745. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19746. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19747. skyboxMaterial.disableLighting = true;
  19748. hdrSkybox.infiniteDistance = true;
  19749. hdrSkybox.material = skyboxMaterial;
  19750. }
  19751. return hdrSkybox;
  19752. };
  19753. Scene.prototype.createDefaultVRExperience = function () {
  19754. this.VRHelper = new BABYLON.VRExperienceHelper(this, null);
  19755. };
  19756. // Tags
  19757. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19758. if (tagsQuery === undefined) {
  19759. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19760. return list;
  19761. }
  19762. var listByTags = [];
  19763. forEach = forEach || (function (item) { return; });
  19764. for (var i in list) {
  19765. var item = list[i];
  19766. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19767. listByTags.push(item);
  19768. forEach(item);
  19769. }
  19770. }
  19771. return listByTags;
  19772. };
  19773. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19774. return this._getByTags(this.meshes, tagsQuery, forEach);
  19775. };
  19776. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19777. return this._getByTags(this.cameras, tagsQuery, forEach);
  19778. };
  19779. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19780. return this._getByTags(this.lights, tagsQuery, forEach);
  19781. };
  19782. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19783. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19784. };
  19785. /**
  19786. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19787. * This allowed control for front to back rendering or reversly depending of the special needs.
  19788. *
  19789. * @param renderingGroupId The rendering group id corresponding to its index
  19790. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19791. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19792. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19793. */
  19794. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19795. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19796. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19797. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19798. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19799. };
  19800. /**
  19801. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19802. *
  19803. * @param renderingGroupId The rendering group id corresponding to its index
  19804. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19805. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19806. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19807. */
  19808. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19809. if (depth === void 0) { depth = true; }
  19810. if (stencil === void 0) { stencil = true; }
  19811. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  19812. };
  19813. /**
  19814. * Will flag all materials as dirty to trigger new shader compilation
  19815. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  19816. */
  19817. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  19818. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  19819. var material = _a[_i];
  19820. if (predicate && !predicate(material)) {
  19821. continue;
  19822. }
  19823. material.markAsDirty(flag);
  19824. }
  19825. };
  19826. // Statics
  19827. Scene._FOGMODE_NONE = 0;
  19828. Scene._FOGMODE_EXP = 1;
  19829. Scene._FOGMODE_EXP2 = 2;
  19830. Scene._FOGMODE_LINEAR = 3;
  19831. Scene.MinDeltaTime = 1.0;
  19832. Scene.MaxDeltaTime = 1000.0;
  19833. /** The distance in pixel that you have to move to prevent some events */
  19834. Scene.DragMovementThreshold = 10; // in pixels
  19835. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  19836. Scene.LongPressDelay = 500; // in milliseconds
  19837. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  19838. Scene.DoubleClickDelay = 300; // in milliseconds
  19839. /** If you need to check double click without raising a single click at first click, enable this flag */
  19840. Scene.ExclusiveDoubleClickMode = false;
  19841. return Scene;
  19842. }());
  19843. BABYLON.Scene = Scene;
  19844. })(BABYLON || (BABYLON = {}));
  19845. //# sourceMappingURL=babylon.scene.js.map
  19846. var BABYLON;
  19847. (function (BABYLON) {
  19848. var Buffer = (function () {
  19849. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19850. if (engine instanceof BABYLON.Mesh) {
  19851. this._engine = engine.getScene().getEngine();
  19852. }
  19853. else {
  19854. this._engine = engine;
  19855. }
  19856. this._updatable = updatable;
  19857. this._data = data;
  19858. this._strideSize = stride;
  19859. if (!postponeInternalCreation) {
  19860. this.create();
  19861. }
  19862. this._instanced = instanced;
  19863. this._instanceDivisor = instanced ? 1 : 0;
  19864. }
  19865. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19866. // a lot of these parameters are ignored as they are overriden by the buffer
  19867. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19868. };
  19869. // Properties
  19870. Buffer.prototype.isUpdatable = function () {
  19871. return this._updatable;
  19872. };
  19873. Buffer.prototype.getData = function () {
  19874. return this._data;
  19875. };
  19876. Buffer.prototype.getBuffer = function () {
  19877. return this._buffer;
  19878. };
  19879. Buffer.prototype.getStrideSize = function () {
  19880. return this._strideSize;
  19881. };
  19882. Buffer.prototype.getIsInstanced = function () {
  19883. return this._instanced;
  19884. };
  19885. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  19886. get: function () {
  19887. return this._instanceDivisor;
  19888. },
  19889. set: function (value) {
  19890. this._instanceDivisor = value;
  19891. if (value == 0) {
  19892. this._instanced = false;
  19893. }
  19894. else {
  19895. this._instanced = true;
  19896. }
  19897. },
  19898. enumerable: true,
  19899. configurable: true
  19900. });
  19901. // Methods
  19902. Buffer.prototype.create = function (data) {
  19903. if (!data && this._buffer) {
  19904. return; // nothing to do
  19905. }
  19906. data = data || this._data;
  19907. if (!this._buffer) {
  19908. if (this._updatable) {
  19909. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19910. this._data = data;
  19911. }
  19912. else {
  19913. this._buffer = this._engine.createVertexBuffer(data);
  19914. }
  19915. }
  19916. else if (this._updatable) {
  19917. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19918. this._data = data;
  19919. }
  19920. };
  19921. Buffer.prototype._rebuild = function () {
  19922. this._buffer = null;
  19923. this.create(this._data);
  19924. };
  19925. Buffer.prototype.update = function (data) {
  19926. this.create(data);
  19927. };
  19928. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  19929. if (!this._buffer) {
  19930. return;
  19931. }
  19932. if (this._updatable) {
  19933. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  19934. this._data = null;
  19935. }
  19936. };
  19937. Buffer.prototype.dispose = function () {
  19938. if (!this._buffer) {
  19939. return;
  19940. }
  19941. if (this._engine._releaseBuffer(this._buffer)) {
  19942. this._buffer = null;
  19943. }
  19944. };
  19945. return Buffer;
  19946. }());
  19947. BABYLON.Buffer = Buffer;
  19948. })(BABYLON || (BABYLON = {}));
  19949. //# sourceMappingURL=babylon.buffer.js.map
  19950. var BABYLON;
  19951. (function (BABYLON) {
  19952. var VertexBuffer = (function () {
  19953. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  19954. if (!stride) {
  19955. // Deduce stride from kind
  19956. switch (kind) {
  19957. case VertexBuffer.PositionKind:
  19958. stride = 3;
  19959. break;
  19960. case VertexBuffer.NormalKind:
  19961. stride = 3;
  19962. break;
  19963. case VertexBuffer.UVKind:
  19964. case VertexBuffer.UV2Kind:
  19965. case VertexBuffer.UV3Kind:
  19966. case VertexBuffer.UV4Kind:
  19967. case VertexBuffer.UV5Kind:
  19968. case VertexBuffer.UV6Kind:
  19969. stride = 2;
  19970. break;
  19971. case VertexBuffer.TangentKind:
  19972. case VertexBuffer.ColorKind:
  19973. stride = 4;
  19974. break;
  19975. case VertexBuffer.MatricesIndicesKind:
  19976. case VertexBuffer.MatricesIndicesExtraKind:
  19977. stride = 4;
  19978. break;
  19979. case VertexBuffer.MatricesWeightsKind:
  19980. case VertexBuffer.MatricesWeightsExtraKind:
  19981. stride = 4;
  19982. break;
  19983. }
  19984. }
  19985. if (data instanceof BABYLON.Buffer) {
  19986. if (!stride) {
  19987. stride = data.getStrideSize();
  19988. }
  19989. this._buffer = data;
  19990. this._ownsBuffer = false;
  19991. }
  19992. else {
  19993. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  19994. this._ownsBuffer = true;
  19995. }
  19996. this._stride = stride;
  19997. this._offset = offset ? offset : 0;
  19998. this._size = size ? size : stride;
  19999. this._kind = kind;
  20000. }
  20001. VertexBuffer.prototype._rebuild = function () {
  20002. if (!this._buffer) {
  20003. return;
  20004. }
  20005. this._buffer._rebuild();
  20006. };
  20007. /**
  20008. * Returns the kind of the VertexBuffer (string).
  20009. */
  20010. VertexBuffer.prototype.getKind = function () {
  20011. return this._kind;
  20012. };
  20013. // Properties
  20014. /**
  20015. * Boolean : is the VertexBuffer updatable ?
  20016. */
  20017. VertexBuffer.prototype.isUpdatable = function () {
  20018. return this._buffer.isUpdatable();
  20019. };
  20020. /**
  20021. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  20022. */
  20023. VertexBuffer.prototype.getData = function () {
  20024. return this._buffer.getData();
  20025. };
  20026. /**
  20027. * Returns the WebGLBuffer associated to the VertexBuffer.
  20028. */
  20029. VertexBuffer.prototype.getBuffer = function () {
  20030. return this._buffer.getBuffer();
  20031. };
  20032. /**
  20033. * Returns the stride of the VertexBuffer (integer).
  20034. */
  20035. VertexBuffer.prototype.getStrideSize = function () {
  20036. return this._stride;
  20037. };
  20038. /**
  20039. * Returns the offset (integer).
  20040. */
  20041. VertexBuffer.prototype.getOffset = function () {
  20042. return this._offset;
  20043. };
  20044. /**
  20045. * Returns the VertexBuffer total size (integer).
  20046. */
  20047. VertexBuffer.prototype.getSize = function () {
  20048. return this._size;
  20049. };
  20050. /**
  20051. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  20052. */
  20053. VertexBuffer.prototype.getIsInstanced = function () {
  20054. return this._buffer.getIsInstanced();
  20055. };
  20056. /**
  20057. * Returns the instancing divisor, zero for non-instanced (integer).
  20058. */
  20059. VertexBuffer.prototype.getInstanceDivisor = function () {
  20060. return this._buffer.instanceDivisor;
  20061. };
  20062. // Methods
  20063. /**
  20064. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  20065. * Returns the created WebGLBuffer.
  20066. */
  20067. VertexBuffer.prototype.create = function (data) {
  20068. return this._buffer.create(data);
  20069. };
  20070. /**
  20071. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  20072. * Returns the updated WebGLBuffer.
  20073. */
  20074. VertexBuffer.prototype.update = function (data) {
  20075. return this._buffer.update(data);
  20076. };
  20077. /**
  20078. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  20079. * Returns the directly updated WebGLBuffer.
  20080. */
  20081. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  20082. return this._buffer.updateDirectly(data, offset);
  20083. };
  20084. /**
  20085. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  20086. */
  20087. VertexBuffer.prototype.dispose = function () {
  20088. if (this._ownsBuffer) {
  20089. this._buffer.dispose();
  20090. }
  20091. };
  20092. Object.defineProperty(VertexBuffer, "PositionKind", {
  20093. get: function () {
  20094. return VertexBuffer._PositionKind;
  20095. },
  20096. enumerable: true,
  20097. configurable: true
  20098. });
  20099. Object.defineProperty(VertexBuffer, "NormalKind", {
  20100. get: function () {
  20101. return VertexBuffer._NormalKind;
  20102. },
  20103. enumerable: true,
  20104. configurable: true
  20105. });
  20106. Object.defineProperty(VertexBuffer, "TangentKind", {
  20107. get: function () {
  20108. return VertexBuffer._TangentKind;
  20109. },
  20110. enumerable: true,
  20111. configurable: true
  20112. });
  20113. Object.defineProperty(VertexBuffer, "UVKind", {
  20114. get: function () {
  20115. return VertexBuffer._UVKind;
  20116. },
  20117. enumerable: true,
  20118. configurable: true
  20119. });
  20120. Object.defineProperty(VertexBuffer, "UV2Kind", {
  20121. get: function () {
  20122. return VertexBuffer._UV2Kind;
  20123. },
  20124. enumerable: true,
  20125. configurable: true
  20126. });
  20127. Object.defineProperty(VertexBuffer, "UV3Kind", {
  20128. get: function () {
  20129. return VertexBuffer._UV3Kind;
  20130. },
  20131. enumerable: true,
  20132. configurable: true
  20133. });
  20134. Object.defineProperty(VertexBuffer, "UV4Kind", {
  20135. get: function () {
  20136. return VertexBuffer._UV4Kind;
  20137. },
  20138. enumerable: true,
  20139. configurable: true
  20140. });
  20141. Object.defineProperty(VertexBuffer, "UV5Kind", {
  20142. get: function () {
  20143. return VertexBuffer._UV5Kind;
  20144. },
  20145. enumerable: true,
  20146. configurable: true
  20147. });
  20148. Object.defineProperty(VertexBuffer, "UV6Kind", {
  20149. get: function () {
  20150. return VertexBuffer._UV6Kind;
  20151. },
  20152. enumerable: true,
  20153. configurable: true
  20154. });
  20155. Object.defineProperty(VertexBuffer, "ColorKind", {
  20156. get: function () {
  20157. return VertexBuffer._ColorKind;
  20158. },
  20159. enumerable: true,
  20160. configurable: true
  20161. });
  20162. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  20163. get: function () {
  20164. return VertexBuffer._MatricesIndicesKind;
  20165. },
  20166. enumerable: true,
  20167. configurable: true
  20168. });
  20169. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  20170. get: function () {
  20171. return VertexBuffer._MatricesWeightsKind;
  20172. },
  20173. enumerable: true,
  20174. configurable: true
  20175. });
  20176. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  20177. get: function () {
  20178. return VertexBuffer._MatricesIndicesExtraKind;
  20179. },
  20180. enumerable: true,
  20181. configurable: true
  20182. });
  20183. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  20184. get: function () {
  20185. return VertexBuffer._MatricesWeightsExtraKind;
  20186. },
  20187. enumerable: true,
  20188. configurable: true
  20189. });
  20190. // Enums
  20191. VertexBuffer._PositionKind = "position";
  20192. VertexBuffer._NormalKind = "normal";
  20193. VertexBuffer._TangentKind = "tangent";
  20194. VertexBuffer._UVKind = "uv";
  20195. VertexBuffer._UV2Kind = "uv2";
  20196. VertexBuffer._UV3Kind = "uv3";
  20197. VertexBuffer._UV4Kind = "uv4";
  20198. VertexBuffer._UV5Kind = "uv5";
  20199. VertexBuffer._UV6Kind = "uv6";
  20200. VertexBuffer._ColorKind = "color";
  20201. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  20202. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  20203. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  20204. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  20205. return VertexBuffer;
  20206. }());
  20207. BABYLON.VertexBuffer = VertexBuffer;
  20208. })(BABYLON || (BABYLON = {}));
  20209. //# sourceMappingURL=babylon.vertexBuffer.js.map
  20210. var BABYLON;
  20211. (function (BABYLON) {
  20212. var InternalTexture = (function () {
  20213. function InternalTexture(engine, dataSource) {
  20214. this.onLoadedObservable = new BABYLON.Observable();
  20215. // Private
  20216. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  20217. this._references = 1;
  20218. this._engine = engine;
  20219. this._dataSource = dataSource;
  20220. this._webGLTexture = engine._createTexture();
  20221. }
  20222. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  20223. get: function () {
  20224. return this._dataSource;
  20225. },
  20226. enumerable: true,
  20227. configurable: true
  20228. });
  20229. InternalTexture.prototype.incrementReferences = function () {
  20230. this._references++;
  20231. };
  20232. InternalTexture.prototype.updateSize = function (width, height) {
  20233. this.width = width;
  20234. this.height = height;
  20235. this._size = width * height;
  20236. this.baseWidth = width;
  20237. this.baseHeight = height;
  20238. };
  20239. InternalTexture.prototype._rebuild = function () {
  20240. var _this = this;
  20241. var proxy;
  20242. this.isReady = false;
  20243. this._cachedCoordinatesMode = null;
  20244. this._cachedWrapU = null;
  20245. this._cachedWrapV = null;
  20246. this._cachedAnisotropicFilteringLevel = null;
  20247. switch (this._dataSource) {
  20248. case InternalTexture.DATASOURCE_TEMP:
  20249. return;
  20250. case InternalTexture.DATASOURCE_URL:
  20251. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  20252. _this.isReady = true;
  20253. }, null, this._buffer, null, this.format);
  20254. proxy._swapAndDie(this);
  20255. return;
  20256. case InternalTexture.DATASOURCE_RAW:
  20257. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20258. proxy._swapAndDie(this);
  20259. this.isReady = true;
  20260. return;
  20261. case InternalTexture.DATASOURCE_DYNAMIC:
  20262. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  20263. proxy._swapAndDie(this);
  20264. // The engine will make sure to update content so no need to flag it as isReady = true
  20265. return;
  20266. case InternalTexture.DATASOURCE_RENDERTARGET:
  20267. var options = new BABYLON.RenderTargetCreationOptions();
  20268. options.generateDepthBuffer = this._generateDepthBuffer;
  20269. options.generateMipMaps = this.generateMipMaps;
  20270. options.generateStencilBuffer = this._generateStencilBuffer;
  20271. options.samplingMode = this.samplingMode;
  20272. options.type = this.type;
  20273. if (this.isCube) {
  20274. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  20275. }
  20276. else {
  20277. var size = {
  20278. width: this.width,
  20279. height: this.height
  20280. };
  20281. proxy = this._engine.createRenderTargetTexture(size, options);
  20282. }
  20283. proxy._swapAndDie(this);
  20284. this.isReady = true;
  20285. return;
  20286. case InternalTexture.DATASOURCE_CUBE:
  20287. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  20288. _this.isReady = true;
  20289. }, null, this.format, this._extension);
  20290. proxy._swapAndDie(this);
  20291. return;
  20292. case InternalTexture.DATASOURCE_CUBERAW:
  20293. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20294. proxy._swapAndDie(this);
  20295. this.isReady = true;
  20296. return;
  20297. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  20298. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  20299. proxy._swapAndDie(_this);
  20300. _this.isReady = true;
  20301. }, null, this.format, this._extension);
  20302. return;
  20303. }
  20304. };
  20305. InternalTexture.prototype._swapAndDie = function (target) {
  20306. target._webGLTexture = this._webGLTexture;
  20307. if (this._framebuffer) {
  20308. target._framebuffer = this._framebuffer;
  20309. }
  20310. if (this._depthStencilBuffer) {
  20311. target._depthStencilBuffer = this._depthStencilBuffer;
  20312. }
  20313. if (this._lodTextureHigh) {
  20314. if (target._lodTextureHigh) {
  20315. target._lodTextureHigh.dispose();
  20316. }
  20317. target._lodTextureHigh = this._lodTextureHigh;
  20318. }
  20319. if (this._lodTextureMid) {
  20320. if (target._lodTextureMid) {
  20321. target._lodTextureMid.dispose();
  20322. }
  20323. target._lodTextureMid = this._lodTextureMid;
  20324. }
  20325. if (this._lodTextureLow) {
  20326. if (target._lodTextureLow) {
  20327. target._lodTextureLow.dispose();
  20328. }
  20329. target._lodTextureLow = this._lodTextureLow;
  20330. }
  20331. var cache = this._engine.getLoadedTexturesCache();
  20332. var index = cache.indexOf(this);
  20333. if (index !== -1) {
  20334. cache.splice(index, 1);
  20335. }
  20336. };
  20337. InternalTexture.prototype.dispose = function () {
  20338. if (!this._webGLTexture) {
  20339. return;
  20340. }
  20341. this._references--;
  20342. if (this._references === 0) {
  20343. this._engine._releaseTexture(this);
  20344. this._webGLTexture = null;
  20345. }
  20346. };
  20347. InternalTexture.DATASOURCE_UNKNOWN = 0;
  20348. InternalTexture.DATASOURCE_URL = 1;
  20349. InternalTexture.DATASOURCE_TEMP = 2;
  20350. InternalTexture.DATASOURCE_RAW = 3;
  20351. InternalTexture.DATASOURCE_DYNAMIC = 4;
  20352. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  20353. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  20354. InternalTexture.DATASOURCE_CUBE = 7;
  20355. InternalTexture.DATASOURCE_CUBERAW = 8;
  20356. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  20357. return InternalTexture;
  20358. }());
  20359. BABYLON.InternalTexture = InternalTexture;
  20360. })(BABYLON || (BABYLON = {}));
  20361. //# sourceMappingURL=babylon.internalTexture.js.map
  20362. var BABYLON;
  20363. (function (BABYLON) {
  20364. var BaseTexture = (function () {
  20365. function BaseTexture(scene) {
  20366. this._hasAlpha = false;
  20367. this.getAlphaFromRGB = false;
  20368. this.level = 1;
  20369. this.coordinatesIndex = 0;
  20370. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20371. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20372. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20373. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  20374. this.isCube = false;
  20375. this.gammaSpace = true;
  20376. this.invertZ = false;
  20377. this.lodLevelInAlpha = false;
  20378. this.lodGenerationOffset = 0.0;
  20379. this.lodGenerationScale = 0.8;
  20380. this.isRenderTarget = false;
  20381. this.animations = new Array();
  20382. /**
  20383. * An event triggered when the texture is disposed.
  20384. * @type {BABYLON.Observable}
  20385. */
  20386. this.onDisposeObservable = new BABYLON.Observable();
  20387. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20388. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  20389. this._scene.textures.push(this);
  20390. this._uid = null;
  20391. }
  20392. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  20393. get: function () {
  20394. return this._hasAlpha;
  20395. },
  20396. set: function (value) {
  20397. if (this._hasAlpha === value) {
  20398. return;
  20399. }
  20400. this._hasAlpha = value;
  20401. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20402. },
  20403. enumerable: true,
  20404. configurable: true
  20405. });
  20406. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  20407. get: function () {
  20408. return this._coordinatesMode;
  20409. },
  20410. set: function (value) {
  20411. if (this._coordinatesMode === value) {
  20412. return;
  20413. }
  20414. this._coordinatesMode = value;
  20415. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20416. },
  20417. enumerable: true,
  20418. configurable: true
  20419. });
  20420. Object.defineProperty(BaseTexture.prototype, "uid", {
  20421. get: function () {
  20422. if (!this._uid) {
  20423. this._uid = BABYLON.Tools.RandomId();
  20424. }
  20425. return this._uid;
  20426. },
  20427. enumerable: true,
  20428. configurable: true
  20429. });
  20430. BaseTexture.prototype.toString = function () {
  20431. return this.name;
  20432. };
  20433. BaseTexture.prototype.getClassName = function () {
  20434. return "BaseTexture";
  20435. };
  20436. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  20437. set: function (callback) {
  20438. if (this._onDisposeObserver) {
  20439. this.onDisposeObservable.remove(this._onDisposeObserver);
  20440. }
  20441. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20442. },
  20443. enumerable: true,
  20444. configurable: true
  20445. });
  20446. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  20447. get: function () {
  20448. return true;
  20449. },
  20450. enumerable: true,
  20451. configurable: true
  20452. });
  20453. BaseTexture.prototype.getScene = function () {
  20454. return this._scene;
  20455. };
  20456. BaseTexture.prototype.getTextureMatrix = function () {
  20457. return null;
  20458. };
  20459. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20460. return null;
  20461. };
  20462. BaseTexture.prototype.getInternalTexture = function () {
  20463. return this._texture;
  20464. };
  20465. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  20466. return !this.isBlocking || this.isReady();
  20467. };
  20468. BaseTexture.prototype.isReady = function () {
  20469. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20470. this.delayLoad();
  20471. return false;
  20472. }
  20473. if (this._texture) {
  20474. return this._texture.isReady;
  20475. }
  20476. return false;
  20477. };
  20478. BaseTexture.prototype.getSize = function () {
  20479. if (this._texture.width) {
  20480. return new BABYLON.Size(this._texture.width, this._texture.height);
  20481. }
  20482. if (this._texture._size) {
  20483. return new BABYLON.Size(this._texture._size, this._texture._size);
  20484. }
  20485. return BABYLON.Size.Zero();
  20486. };
  20487. BaseTexture.prototype.getBaseSize = function () {
  20488. if (!this.isReady() || !this._texture)
  20489. return BABYLON.Size.Zero();
  20490. if (this._texture._size) {
  20491. return new BABYLON.Size(this._texture._size, this._texture._size);
  20492. }
  20493. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  20494. };
  20495. BaseTexture.prototype.scale = function (ratio) {
  20496. };
  20497. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20498. get: function () {
  20499. return false;
  20500. },
  20501. enumerable: true,
  20502. configurable: true
  20503. });
  20504. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20505. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20506. for (var index = 0; index < texturesCache.length; index++) {
  20507. var texturesCacheEntry = texturesCache[index];
  20508. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  20509. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20510. texturesCacheEntry.incrementReferences();
  20511. return texturesCacheEntry;
  20512. }
  20513. }
  20514. }
  20515. return null;
  20516. };
  20517. BaseTexture.prototype._rebuild = function () {
  20518. };
  20519. BaseTexture.prototype.delayLoad = function () {
  20520. };
  20521. BaseTexture.prototype.clone = function () {
  20522. return null;
  20523. };
  20524. Object.defineProperty(BaseTexture.prototype, "textureType", {
  20525. get: function () {
  20526. if (!this._texture) {
  20527. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20528. }
  20529. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20530. },
  20531. enumerable: true,
  20532. configurable: true
  20533. });
  20534. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  20535. get: function () {
  20536. if (!this._texture) {
  20537. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20538. }
  20539. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20540. },
  20541. enumerable: true,
  20542. configurable: true
  20543. });
  20544. BaseTexture.prototype.readPixels = function (faceIndex) {
  20545. if (faceIndex === void 0) { faceIndex = 0; }
  20546. if (!this._texture) {
  20547. return null;
  20548. }
  20549. var size = this.getSize();
  20550. var engine = this.getScene().getEngine();
  20551. if (this._texture.isCube) {
  20552. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  20553. }
  20554. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  20555. };
  20556. BaseTexture.prototype.releaseInternalTexture = function () {
  20557. if (this._texture) {
  20558. this._texture.dispose();
  20559. this._texture = null;
  20560. }
  20561. };
  20562. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  20563. get: function () {
  20564. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  20565. return null;
  20566. }
  20567. if (!this._texture._sphericalPolynomial) {
  20568. this._texture._sphericalPolynomial =
  20569. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  20570. }
  20571. return this._texture._sphericalPolynomial;
  20572. },
  20573. set: function (value) {
  20574. if (this._texture) {
  20575. this._texture._sphericalPolynomial = value;
  20576. }
  20577. },
  20578. enumerable: true,
  20579. configurable: true
  20580. });
  20581. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  20582. get: function () {
  20583. if (this._texture) {
  20584. return this._texture._lodTextureHigh;
  20585. }
  20586. return null;
  20587. },
  20588. enumerable: true,
  20589. configurable: true
  20590. });
  20591. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  20592. get: function () {
  20593. if (this._texture) {
  20594. return this._texture._lodTextureMid;
  20595. }
  20596. return null;
  20597. },
  20598. enumerable: true,
  20599. configurable: true
  20600. });
  20601. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  20602. get: function () {
  20603. if (this._texture) {
  20604. return this._texture._lodTextureLow;
  20605. }
  20606. return null;
  20607. },
  20608. enumerable: true,
  20609. configurable: true
  20610. });
  20611. BaseTexture.prototype.dispose = function () {
  20612. // Animations
  20613. this.getScene().stopAnimation(this);
  20614. // Remove from scene
  20615. this._scene._removePendingData(this);
  20616. var index = this._scene.textures.indexOf(this);
  20617. if (index >= 0) {
  20618. this._scene.textures.splice(index, 1);
  20619. }
  20620. if (this._texture === undefined) {
  20621. return;
  20622. }
  20623. // Release
  20624. this.releaseInternalTexture();
  20625. // Callback
  20626. this.onDisposeObservable.notifyObservers(this);
  20627. this.onDisposeObservable.clear();
  20628. };
  20629. BaseTexture.prototype.serialize = function () {
  20630. if (!this.name) {
  20631. return null;
  20632. }
  20633. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20634. // Animations
  20635. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20636. return serializationObject;
  20637. };
  20638. BaseTexture.WhenAllReady = function (textures, callback) {
  20639. var numRemaining = textures.length;
  20640. if (numRemaining === 0) {
  20641. callback();
  20642. return;
  20643. }
  20644. var _loop_1 = function () {
  20645. texture = textures[i];
  20646. if (texture.isReady()) {
  20647. if (--numRemaining === 0) {
  20648. callback();
  20649. }
  20650. }
  20651. else {
  20652. onLoadObservable = texture.onLoadObservable;
  20653. var onLoadCallback_1 = function () {
  20654. onLoadObservable.removeCallback(onLoadCallback_1);
  20655. if (--numRemaining === 0) {
  20656. callback();
  20657. }
  20658. };
  20659. onLoadObservable.add(onLoadCallback_1);
  20660. }
  20661. };
  20662. var texture, onLoadObservable;
  20663. for (var i = 0; i < textures.length; i++) {
  20664. _loop_1();
  20665. }
  20666. };
  20667. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  20668. __decorate([
  20669. BABYLON.serialize()
  20670. ], BaseTexture.prototype, "name", void 0);
  20671. __decorate([
  20672. BABYLON.serialize("hasAlpha")
  20673. ], BaseTexture.prototype, "_hasAlpha", void 0);
  20674. __decorate([
  20675. BABYLON.serialize()
  20676. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20677. __decorate([
  20678. BABYLON.serialize()
  20679. ], BaseTexture.prototype, "level", void 0);
  20680. __decorate([
  20681. BABYLON.serialize()
  20682. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20683. __decorate([
  20684. BABYLON.serialize("coordinatesMode")
  20685. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  20686. __decorate([
  20687. BABYLON.serialize()
  20688. ], BaseTexture.prototype, "wrapU", void 0);
  20689. __decorate([
  20690. BABYLON.serialize()
  20691. ], BaseTexture.prototype, "wrapV", void 0);
  20692. __decorate([
  20693. BABYLON.serialize()
  20694. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20695. __decorate([
  20696. BABYLON.serialize()
  20697. ], BaseTexture.prototype, "isCube", void 0);
  20698. __decorate([
  20699. BABYLON.serialize()
  20700. ], BaseTexture.prototype, "gammaSpace", void 0);
  20701. __decorate([
  20702. BABYLON.serialize()
  20703. ], BaseTexture.prototype, "invertZ", void 0);
  20704. __decorate([
  20705. BABYLON.serialize()
  20706. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  20707. __decorate([
  20708. BABYLON.serialize()
  20709. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  20710. __decorate([
  20711. BABYLON.serialize()
  20712. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  20713. __decorate([
  20714. BABYLON.serialize()
  20715. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20716. return BaseTexture;
  20717. }());
  20718. BABYLON.BaseTexture = BaseTexture;
  20719. })(BABYLON || (BABYLON = {}));
  20720. //# sourceMappingURL=babylon.baseTexture.js.map
  20721. var BABYLON;
  20722. (function (BABYLON) {
  20723. var Texture = (function (_super) {
  20724. __extends(Texture, _super);
  20725. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  20726. if (noMipmap === void 0) { noMipmap = false; }
  20727. if (invertY === void 0) { invertY = true; }
  20728. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20729. if (onLoad === void 0) { onLoad = null; }
  20730. if (onError === void 0) { onError = null; }
  20731. if (buffer === void 0) { buffer = null; }
  20732. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20733. var _this = _super.call(this, scene) || this;
  20734. _this.uOffset = 0;
  20735. _this.vOffset = 0;
  20736. _this.uScale = 1.0;
  20737. _this.vScale = 1.0;
  20738. _this.uAng = 0;
  20739. _this.vAng = 0;
  20740. _this.wAng = 0;
  20741. _this._isBlocking = true;
  20742. _this.name = url;
  20743. _this.url = url;
  20744. _this._noMipmap = noMipmap;
  20745. _this._invertY = invertY;
  20746. _this._samplingMode = samplingMode;
  20747. _this._buffer = buffer;
  20748. _this._deleteBuffer = deleteBuffer;
  20749. _this._format = format;
  20750. scene = _this.getScene();
  20751. var load = function () {
  20752. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  20753. _this.onLoadObservable.notifyObservers(_this);
  20754. }
  20755. if (onLoad) {
  20756. onLoad();
  20757. }
  20758. if (!_this.isBlocking) {
  20759. scene.resetCachedMaterial();
  20760. }
  20761. };
  20762. if (!url) {
  20763. _this._delayedOnLoad = load;
  20764. _this._delayedOnError = onError;
  20765. return _this;
  20766. }
  20767. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  20768. if (!_this._texture) {
  20769. if (!scene.useDelayedTextureLoading) {
  20770. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  20771. if (deleteBuffer) {
  20772. delete _this._buffer;
  20773. }
  20774. }
  20775. else {
  20776. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20777. _this._delayedOnLoad = load;
  20778. _this._delayedOnError = onError;
  20779. }
  20780. }
  20781. else {
  20782. if (_this._texture.isReady) {
  20783. BABYLON.Tools.SetImmediate(function () { return load(); });
  20784. }
  20785. else {
  20786. _this._texture.onLoadedObservable.add(load);
  20787. }
  20788. }
  20789. return _this;
  20790. }
  20791. Object.defineProperty(Texture.prototype, "noMipmap", {
  20792. get: function () {
  20793. return this._noMipmap;
  20794. },
  20795. enumerable: true,
  20796. configurable: true
  20797. });
  20798. Object.defineProperty(Texture.prototype, "isBlocking", {
  20799. get: function () {
  20800. return this._isBlocking;
  20801. },
  20802. set: function (value) {
  20803. this._isBlocking = value;
  20804. },
  20805. enumerable: true,
  20806. configurable: true
  20807. });
  20808. Object.defineProperty(Texture.prototype, "samplingMode", {
  20809. get: function () {
  20810. return this._samplingMode;
  20811. },
  20812. enumerable: true,
  20813. configurable: true
  20814. });
  20815. Texture.prototype.updateURL = function (url) {
  20816. this.url = url;
  20817. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20818. this.delayLoad();
  20819. };
  20820. Texture.prototype.delayLoad = function () {
  20821. var _this = this;
  20822. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20823. return;
  20824. }
  20825. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20826. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20827. if (!this._texture) {
  20828. 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);
  20829. if (this._deleteBuffer) {
  20830. delete this._buffer;
  20831. }
  20832. }
  20833. else {
  20834. if (this._texture.isReady) {
  20835. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  20836. }
  20837. else {
  20838. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  20839. }
  20840. }
  20841. };
  20842. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20843. if (!this._texture) {
  20844. return;
  20845. }
  20846. this._samplingMode = samplingMode;
  20847. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20848. };
  20849. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20850. x *= this.uScale;
  20851. y *= this.vScale;
  20852. x -= 0.5 * this.uScale;
  20853. y -= 0.5 * this.vScale;
  20854. z -= 0.5;
  20855. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20856. t.x += 0.5 * this.uScale + this.uOffset;
  20857. t.y += 0.5 * this.vScale + this.vOffset;
  20858. t.z += 0.5;
  20859. };
  20860. Texture.prototype.getTextureMatrix = function () {
  20861. var _this = this;
  20862. if (this.uOffset === this._cachedUOffset &&
  20863. this.vOffset === this._cachedVOffset &&
  20864. this.uScale === this._cachedUScale &&
  20865. this.vScale === this._cachedVScale &&
  20866. this.uAng === this._cachedUAng &&
  20867. this.vAng === this._cachedVAng &&
  20868. this.wAng === this._cachedWAng) {
  20869. return this._cachedTextureMatrix;
  20870. }
  20871. this._cachedUOffset = this.uOffset;
  20872. this._cachedVOffset = this.vOffset;
  20873. this._cachedUScale = this.uScale;
  20874. this._cachedVScale = this.vScale;
  20875. this._cachedUAng = this.uAng;
  20876. this._cachedVAng = this.vAng;
  20877. this._cachedWAng = this.wAng;
  20878. if (!this._cachedTextureMatrix) {
  20879. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20880. this._rowGenerationMatrix = new BABYLON.Matrix();
  20881. this._t0 = BABYLON.Vector3.Zero();
  20882. this._t1 = BABYLON.Vector3.Zero();
  20883. this._t2 = BABYLON.Vector3.Zero();
  20884. }
  20885. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20886. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20887. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20888. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20889. this._t1.subtractInPlace(this._t0);
  20890. this._t2.subtractInPlace(this._t0);
  20891. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20892. this._cachedTextureMatrix.m[0] = this._t1.x;
  20893. this._cachedTextureMatrix.m[1] = this._t1.y;
  20894. this._cachedTextureMatrix.m[2] = this._t1.z;
  20895. this._cachedTextureMatrix.m[4] = this._t2.x;
  20896. this._cachedTextureMatrix.m[5] = this._t2.y;
  20897. this._cachedTextureMatrix.m[6] = this._t2.z;
  20898. this._cachedTextureMatrix.m[8] = this._t0.x;
  20899. this._cachedTextureMatrix.m[9] = this._t0.y;
  20900. this._cachedTextureMatrix.m[10] = this._t0.z;
  20901. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20902. return mat.hasTexture(_this);
  20903. });
  20904. return this._cachedTextureMatrix;
  20905. };
  20906. Texture.prototype.getReflectionTextureMatrix = function () {
  20907. var _this = this;
  20908. var scene = this.getScene();
  20909. if (this.uOffset === this._cachedUOffset &&
  20910. this.vOffset === this._cachedVOffset &&
  20911. this.uScale === this._cachedUScale &&
  20912. this.vScale === this._cachedVScale &&
  20913. this.coordinatesMode === this._cachedCoordinatesMode) {
  20914. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  20915. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  20916. return this._cachedTextureMatrix;
  20917. }
  20918. }
  20919. else {
  20920. return this._cachedTextureMatrix;
  20921. }
  20922. }
  20923. if (!this._cachedTextureMatrix) {
  20924. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20925. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  20926. }
  20927. this._cachedUOffset = this.uOffset;
  20928. this._cachedVOffset = this.vOffset;
  20929. this._cachedUScale = this.uScale;
  20930. this._cachedVScale = this.vScale;
  20931. this._cachedCoordinatesMode = this.coordinatesMode;
  20932. switch (this.coordinatesMode) {
  20933. case Texture.PLANAR_MODE:
  20934. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20935. this._cachedTextureMatrix[0] = this.uScale;
  20936. this._cachedTextureMatrix[5] = this.vScale;
  20937. this._cachedTextureMatrix[12] = this.uOffset;
  20938. this._cachedTextureMatrix[13] = this.vOffset;
  20939. break;
  20940. case Texture.PROJECTION_MODE:
  20941. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  20942. this._projectionModeMatrix.m[0] = 0.5;
  20943. this._projectionModeMatrix.m[5] = -0.5;
  20944. this._projectionModeMatrix.m[10] = 0.0;
  20945. this._projectionModeMatrix.m[12] = 0.5;
  20946. this._projectionModeMatrix.m[13] = 0.5;
  20947. this._projectionModeMatrix.m[14] = 1.0;
  20948. this._projectionModeMatrix.m[15] = 1.0;
  20949. var projectionMatrix = scene.getProjectionMatrix();
  20950. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  20951. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  20952. break;
  20953. default:
  20954. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20955. break;
  20956. }
  20957. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20958. return (mat.getActiveTextures().indexOf(_this) !== -1);
  20959. });
  20960. return this._cachedTextureMatrix;
  20961. };
  20962. Texture.prototype.clone = function () {
  20963. var _this = this;
  20964. return BABYLON.SerializationHelper.Clone(function () {
  20965. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  20966. }, this);
  20967. };
  20968. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  20969. get: function () {
  20970. if (!this._onLoadObservable) {
  20971. this._onLoadObservable = new BABYLON.Observable();
  20972. }
  20973. return this._onLoadObservable;
  20974. },
  20975. enumerable: true,
  20976. configurable: true
  20977. });
  20978. Texture.prototype.serialize = function () {
  20979. var serializationObject = _super.prototype.serialize.call(this);
  20980. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  20981. serializationObject.base64String = this._buffer;
  20982. serializationObject.name = serializationObject.name.replace("data:", "");
  20983. }
  20984. return serializationObject;
  20985. };
  20986. Texture.prototype.getClassName = function () {
  20987. return "Texture";
  20988. };
  20989. Texture.prototype.dispose = function () {
  20990. _super.prototype.dispose.call(this);
  20991. if (this.onLoadObservable) {
  20992. this.onLoadObservable.clear();
  20993. this._onLoadObservable = null;
  20994. }
  20995. this._delayedOnLoad = null;
  20996. this._delayedOnError = null;
  20997. };
  20998. // Statics
  20999. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  21000. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21001. if (onLoad === void 0) { onLoad = null; }
  21002. if (onError === void 0) { onError = null; }
  21003. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  21004. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  21005. };
  21006. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  21007. if (parsedTexture.customType) {
  21008. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  21009. // Update Sampling Mode
  21010. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  21011. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  21012. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  21013. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  21014. }
  21015. }
  21016. return parsedCustomTexture;
  21017. }
  21018. if (parsedTexture.isCube) {
  21019. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  21020. }
  21021. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  21022. return null;
  21023. }
  21024. var texture = BABYLON.SerializationHelper.Parse(function () {
  21025. if (parsedTexture.mirrorPlane) {
  21026. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21027. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  21028. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  21029. return mirrorTexture;
  21030. }
  21031. else if (parsedTexture.isRenderTarget) {
  21032. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21033. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  21034. return renderTargetTexture;
  21035. }
  21036. else {
  21037. var texture;
  21038. if (parsedTexture.base64String) {
  21039. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  21040. }
  21041. else {
  21042. texture = new Texture(rootUrl + parsedTexture.name, scene);
  21043. }
  21044. return texture;
  21045. }
  21046. }, parsedTexture, scene);
  21047. // Update Sampling Mode
  21048. if (parsedTexture.samplingMode) {
  21049. var sampling = parsedTexture.samplingMode;
  21050. if (texture._samplingMode !== sampling) {
  21051. texture.updateSamplingMode(sampling);
  21052. }
  21053. }
  21054. // Animations
  21055. if (parsedTexture.animations) {
  21056. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21057. var parsedAnimation = parsedTexture.animations[animationIndex];
  21058. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21059. }
  21060. }
  21061. return texture;
  21062. };
  21063. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  21064. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21065. if (noMipmap === void 0) { noMipmap = false; }
  21066. if (invertY === void 0) { invertY = true; }
  21067. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21068. if (onLoad === void 0) { onLoad = null; }
  21069. if (onError === void 0) { onError = null; }
  21070. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  21071. if (name.substr(0, 5) !== "data:") {
  21072. name = "data:" + name;
  21073. }
  21074. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  21075. };
  21076. // Constants
  21077. Texture.NEAREST_SAMPLINGMODE = 1;
  21078. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  21079. Texture.BILINEAR_SAMPLINGMODE = 2;
  21080. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  21081. Texture.TRILINEAR_SAMPLINGMODE = 3;
  21082. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  21083. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  21084. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  21085. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  21086. Texture.NEAREST_LINEAR = 7;
  21087. Texture.NEAREST_NEAREST = 8;
  21088. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  21089. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  21090. Texture.LINEAR_LINEAR = 11;
  21091. Texture.LINEAR_NEAREST = 12;
  21092. Texture.EXPLICIT_MODE = 0;
  21093. Texture.SPHERICAL_MODE = 1;
  21094. Texture.PLANAR_MODE = 2;
  21095. Texture.CUBIC_MODE = 3;
  21096. Texture.PROJECTION_MODE = 4;
  21097. Texture.SKYBOX_MODE = 5;
  21098. Texture.INVCUBIC_MODE = 6;
  21099. Texture.EQUIRECTANGULAR_MODE = 7;
  21100. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  21101. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  21102. Texture.CLAMP_ADDRESSMODE = 0;
  21103. Texture.WRAP_ADDRESSMODE = 1;
  21104. Texture.MIRROR_ADDRESSMODE = 2;
  21105. __decorate([
  21106. BABYLON.serialize()
  21107. ], Texture.prototype, "url", void 0);
  21108. __decorate([
  21109. BABYLON.serialize()
  21110. ], Texture.prototype, "uOffset", void 0);
  21111. __decorate([
  21112. BABYLON.serialize()
  21113. ], Texture.prototype, "vOffset", void 0);
  21114. __decorate([
  21115. BABYLON.serialize()
  21116. ], Texture.prototype, "uScale", void 0);
  21117. __decorate([
  21118. BABYLON.serialize()
  21119. ], Texture.prototype, "vScale", void 0);
  21120. __decorate([
  21121. BABYLON.serialize()
  21122. ], Texture.prototype, "uAng", void 0);
  21123. __decorate([
  21124. BABYLON.serialize()
  21125. ], Texture.prototype, "vAng", void 0);
  21126. __decorate([
  21127. BABYLON.serialize()
  21128. ], Texture.prototype, "wAng", void 0);
  21129. __decorate([
  21130. BABYLON.serialize()
  21131. ], Texture.prototype, "isBlocking", null);
  21132. return Texture;
  21133. }(BABYLON.BaseTexture));
  21134. BABYLON.Texture = Texture;
  21135. })(BABYLON || (BABYLON = {}));
  21136. //# sourceMappingURL=babylon.texture.js.map
  21137. var BABYLON;
  21138. (function (BABYLON) {
  21139. var _InstancesBatch = (function () {
  21140. function _InstancesBatch() {
  21141. this.mustReturn = false;
  21142. this.visibleInstances = new Array();
  21143. this.renderSelf = new Array();
  21144. }
  21145. return _InstancesBatch;
  21146. }());
  21147. BABYLON._InstancesBatch = _InstancesBatch;
  21148. var Mesh = (function (_super) {
  21149. __extends(Mesh, _super);
  21150. /**
  21151. * @constructor
  21152. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  21153. * @param {Scene} scene The scene to add this mesh to.
  21154. * @param {Node} parent The parent of this mesh, if it has one
  21155. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  21156. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  21157. * When false, achieved by calling a clone(), also passing False.
  21158. * This will make creation of children, recursive.
  21159. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  21160. */
  21161. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  21162. if (parent === void 0) { parent = null; }
  21163. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  21164. var _this = _super.call(this, name, scene) || this;
  21165. // Events
  21166. /**
  21167. * An event triggered before rendering the mesh
  21168. * @type {BABYLON.Observable}
  21169. */
  21170. _this.onBeforeRenderObservable = new BABYLON.Observable();
  21171. /**
  21172. * An event triggered after rendering the mesh
  21173. * @type {BABYLON.Observable}
  21174. */
  21175. _this.onAfterRenderObservable = new BABYLON.Observable();
  21176. /**
  21177. * An event triggered before drawing the mesh
  21178. * @type {BABYLON.Observable}
  21179. */
  21180. _this.onBeforeDrawObservable = new BABYLON.Observable();
  21181. // Members
  21182. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21183. _this.instances = new Array();
  21184. _this._LODLevels = new Array();
  21185. _this._visibleInstances = {};
  21186. _this._renderIdForInstances = new Array();
  21187. _this._batchCache = new _InstancesBatch();
  21188. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  21189. _this._sideOrientation = Mesh._DEFAULTSIDE;
  21190. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  21191. // Will be used to save a source mesh reference, If any
  21192. _this._source = null;
  21193. if (source) {
  21194. // Source mesh
  21195. _this._source = source;
  21196. // Geometry
  21197. if (source._geometry) {
  21198. source._geometry.applyToMesh(_this);
  21199. }
  21200. // Deep copy
  21201. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  21202. // Parent
  21203. _this.parent = source.parent;
  21204. // Pivot
  21205. _this.setPivotMatrix(source.getPivotMatrix());
  21206. _this.id = name + "." + source.id;
  21207. // Material
  21208. _this.material = source.material;
  21209. var index;
  21210. if (!doNotCloneChildren) {
  21211. // Children
  21212. for (index = 0; index < scene.meshes.length; index++) {
  21213. var mesh = scene.meshes[index];
  21214. if (mesh.parent === source) {
  21215. // doNotCloneChildren is always going to be False
  21216. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  21217. }
  21218. }
  21219. }
  21220. // Physics clone
  21221. var physicsEngine = _this.getScene().getPhysicsEngine();
  21222. if (clonePhysicsImpostor && physicsEngine) {
  21223. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  21224. if (impostor) {
  21225. _this.physicsImpostor = impostor.clone(_this);
  21226. }
  21227. }
  21228. // Particles
  21229. for (index = 0; index < scene.particleSystems.length; index++) {
  21230. var system = scene.particleSystems[index];
  21231. if (system.emitter === source) {
  21232. system.clone(system.name, _this);
  21233. }
  21234. }
  21235. _this.computeWorldMatrix(true);
  21236. }
  21237. // Parent
  21238. if (parent !== null) {
  21239. _this.parent = parent;
  21240. }
  21241. return _this;
  21242. }
  21243. Object.defineProperty(Mesh, "FRONTSIDE", {
  21244. /**
  21245. * Mesh side orientation : usually the external or front surface
  21246. */
  21247. get: function () {
  21248. return Mesh._FRONTSIDE;
  21249. },
  21250. enumerable: true,
  21251. configurable: true
  21252. });
  21253. Object.defineProperty(Mesh, "BACKSIDE", {
  21254. /**
  21255. * Mesh side orientation : usually the internal or back surface
  21256. */
  21257. get: function () {
  21258. return Mesh._BACKSIDE;
  21259. },
  21260. enumerable: true,
  21261. configurable: true
  21262. });
  21263. Object.defineProperty(Mesh, "DOUBLESIDE", {
  21264. /**
  21265. * Mesh side orientation : both internal and external or front and back surfaces
  21266. */
  21267. get: function () {
  21268. return Mesh._DOUBLESIDE;
  21269. },
  21270. enumerable: true,
  21271. configurable: true
  21272. });
  21273. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  21274. /**
  21275. * Mesh side orientation : by default, `FRONTSIDE`
  21276. */
  21277. get: function () {
  21278. return Mesh._DEFAULTSIDE;
  21279. },
  21280. enumerable: true,
  21281. configurable: true
  21282. });
  21283. Object.defineProperty(Mesh, "NO_CAP", {
  21284. /**
  21285. * Mesh cap setting : no cap
  21286. */
  21287. get: function () {
  21288. return Mesh._NO_CAP;
  21289. },
  21290. enumerable: true,
  21291. configurable: true
  21292. });
  21293. Object.defineProperty(Mesh, "CAP_START", {
  21294. /**
  21295. * Mesh cap setting : one cap at the beginning of the mesh
  21296. */
  21297. get: function () {
  21298. return Mesh._CAP_START;
  21299. },
  21300. enumerable: true,
  21301. configurable: true
  21302. });
  21303. Object.defineProperty(Mesh, "CAP_END", {
  21304. /**
  21305. * Mesh cap setting : one cap at the end of the mesh
  21306. */
  21307. get: function () {
  21308. return Mesh._CAP_END;
  21309. },
  21310. enumerable: true,
  21311. configurable: true
  21312. });
  21313. Object.defineProperty(Mesh, "CAP_ALL", {
  21314. /**
  21315. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  21316. */
  21317. get: function () {
  21318. return Mesh._CAP_ALL;
  21319. },
  21320. enumerable: true,
  21321. configurable: true
  21322. });
  21323. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  21324. set: function (callback) {
  21325. if (this._onBeforeDrawObserver) {
  21326. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  21327. }
  21328. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  21329. },
  21330. enumerable: true,
  21331. configurable: true
  21332. });
  21333. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  21334. get: function () {
  21335. return this._morphTargetManager;
  21336. },
  21337. set: function (value) {
  21338. if (this._morphTargetManager === value) {
  21339. return;
  21340. }
  21341. this._morphTargetManager = value;
  21342. this._syncGeometryWithMorphTargetManager();
  21343. },
  21344. enumerable: true,
  21345. configurable: true
  21346. });
  21347. Object.defineProperty(Mesh.prototype, "source", {
  21348. get: function () {
  21349. return this._source;
  21350. },
  21351. enumerable: true,
  21352. configurable: true
  21353. });
  21354. // Methods
  21355. /**
  21356. * Returns the string "Mesh".
  21357. */
  21358. Mesh.prototype.getClassName = function () {
  21359. return "Mesh";
  21360. };
  21361. /**
  21362. * Returns a string.
  21363. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21364. */
  21365. Mesh.prototype.toString = function (fullDetails) {
  21366. var ret = _super.prototype.toString.call(this, fullDetails);
  21367. ret += ", n vertices: " + this.getTotalVertices();
  21368. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  21369. if (this.animations) {
  21370. for (var i = 0; i < this.animations.length; i++) {
  21371. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21372. }
  21373. }
  21374. if (fullDetails) {
  21375. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  21376. }
  21377. return ret;
  21378. };
  21379. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  21380. /**
  21381. * True if the mesh has some Levels Of Details (LOD).
  21382. * Returns a boolean.
  21383. */
  21384. get: function () {
  21385. return this._LODLevels.length > 0;
  21386. },
  21387. enumerable: true,
  21388. configurable: true
  21389. });
  21390. Mesh.prototype._sortLODLevels = function () {
  21391. this._LODLevels.sort(function (a, b) {
  21392. if (a.distance < b.distance) {
  21393. return 1;
  21394. }
  21395. if (a.distance > b.distance) {
  21396. return -1;
  21397. }
  21398. return 0;
  21399. });
  21400. };
  21401. /**
  21402. * Add a mesh as LOD level triggered at the given distance.
  21403. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21404. * @param {number} distance The distance from the center of the object to show this level
  21405. * @param {Mesh} mesh The mesh to be added as LOD level
  21406. * @return {Mesh} This mesh (for chaining)
  21407. */
  21408. Mesh.prototype.addLODLevel = function (distance, mesh) {
  21409. if (mesh && mesh._masterMesh) {
  21410. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  21411. return this;
  21412. }
  21413. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  21414. this._LODLevels.push(level);
  21415. if (mesh) {
  21416. mesh._masterMesh = this;
  21417. }
  21418. this._sortLODLevels();
  21419. return this;
  21420. };
  21421. /**
  21422. * Returns the LOD level mesh at the passed distance or null if not found.
  21423. * It is related to the method `addLODLevel(distance, mesh)`.
  21424. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21425. * Returns an object Mesh or `null`.
  21426. */
  21427. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  21428. for (var index = 0; index < this._LODLevels.length; index++) {
  21429. var level = this._LODLevels[index];
  21430. if (level.distance === distance) {
  21431. return level.mesh;
  21432. }
  21433. }
  21434. return null;
  21435. };
  21436. /**
  21437. * Remove a mesh from the LOD array
  21438. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21439. * @param {Mesh} mesh The mesh to be removed.
  21440. * @return {Mesh} This mesh (for chaining)
  21441. */
  21442. Mesh.prototype.removeLODLevel = function (mesh) {
  21443. for (var index = 0; index < this._LODLevels.length; index++) {
  21444. if (this._LODLevels[index].mesh === mesh) {
  21445. this._LODLevels.splice(index, 1);
  21446. if (mesh) {
  21447. mesh._masterMesh = null;
  21448. }
  21449. }
  21450. }
  21451. this._sortLODLevels();
  21452. return this;
  21453. };
  21454. /**
  21455. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  21456. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21457. */
  21458. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  21459. if (!this._LODLevels || this._LODLevels.length === 0) {
  21460. return this;
  21461. }
  21462. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  21463. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  21464. if (this.onLODLevelSelection) {
  21465. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  21466. }
  21467. return this;
  21468. }
  21469. for (var index = 0; index < this._LODLevels.length; index++) {
  21470. var level = this._LODLevels[index];
  21471. if (level.distance < distanceToCamera) {
  21472. if (level.mesh) {
  21473. level.mesh._preActivate();
  21474. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21475. }
  21476. if (this.onLODLevelSelection) {
  21477. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  21478. }
  21479. return level.mesh;
  21480. }
  21481. }
  21482. if (this.onLODLevelSelection) {
  21483. this.onLODLevelSelection(distanceToCamera, this, this);
  21484. }
  21485. return this;
  21486. };
  21487. Object.defineProperty(Mesh.prototype, "geometry", {
  21488. /**
  21489. * Returns the mesh internal Geometry object.
  21490. */
  21491. get: function () {
  21492. return this._geometry;
  21493. },
  21494. enumerable: true,
  21495. configurable: true
  21496. });
  21497. /**
  21498. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  21499. */
  21500. Mesh.prototype.getTotalVertices = function () {
  21501. if (!this._geometry) {
  21502. return 0;
  21503. }
  21504. return this._geometry.getTotalVertices();
  21505. };
  21506. /**
  21507. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  21508. * 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.
  21509. * You can force the copy with forceCopy === true
  21510. * Returns null if the mesh has no geometry or no vertex buffer.
  21511. * Possible `kind` values :
  21512. * - BABYLON.VertexBuffer.PositionKind
  21513. * - BABYLON.VertexBuffer.UVKind
  21514. * - BABYLON.VertexBuffer.UV2Kind
  21515. * - BABYLON.VertexBuffer.UV3Kind
  21516. * - BABYLON.VertexBuffer.UV4Kind
  21517. * - BABYLON.VertexBuffer.UV5Kind
  21518. * - BABYLON.VertexBuffer.UV6Kind
  21519. * - BABYLON.VertexBuffer.ColorKind
  21520. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21521. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21522. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21523. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21524. */
  21525. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  21526. if (!this._geometry) {
  21527. return null;
  21528. }
  21529. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  21530. };
  21531. /**
  21532. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  21533. * Returns `undefined` if the mesh has no geometry.
  21534. * Possible `kind` values :
  21535. * - BABYLON.VertexBuffer.PositionKind
  21536. * - BABYLON.VertexBuffer.UVKind
  21537. * - BABYLON.VertexBuffer.UV2Kind
  21538. * - BABYLON.VertexBuffer.UV3Kind
  21539. * - BABYLON.VertexBuffer.UV4Kind
  21540. * - BABYLON.VertexBuffer.UV5Kind
  21541. * - BABYLON.VertexBuffer.UV6Kind
  21542. * - BABYLON.VertexBuffer.ColorKind
  21543. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21544. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21545. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21546. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21547. */
  21548. Mesh.prototype.getVertexBuffer = function (kind) {
  21549. if (!this._geometry) {
  21550. return undefined;
  21551. }
  21552. return this._geometry.getVertexBuffer(kind);
  21553. };
  21554. /**
  21555. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  21556. * Possible `kind` values :
  21557. * - BABYLON.VertexBuffer.PositionKind
  21558. * - BABYLON.VertexBuffer.UVKind
  21559. * - BABYLON.VertexBuffer.UV2Kind
  21560. * - BABYLON.VertexBuffer.UV3Kind
  21561. * - BABYLON.VertexBuffer.UV4Kind
  21562. * - BABYLON.VertexBuffer.UV5Kind
  21563. * - BABYLON.VertexBuffer.UV6Kind
  21564. * - BABYLON.VertexBuffer.ColorKind
  21565. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21566. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21567. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21568. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21569. */
  21570. Mesh.prototype.isVerticesDataPresent = function (kind) {
  21571. if (!this._geometry) {
  21572. if (this._delayInfo) {
  21573. return this._delayInfo.indexOf(kind) !== -1;
  21574. }
  21575. return false;
  21576. }
  21577. return this._geometry.isVerticesDataPresent(kind);
  21578. };
  21579. /**
  21580. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  21581. * Possible `kind` values :
  21582. * - BABYLON.VertexBuffer.PositionKind
  21583. * - BABYLON.VertexBuffer.UVKind
  21584. * - BABYLON.VertexBuffer.UV2Kind
  21585. * - BABYLON.VertexBuffer.UV3Kind
  21586. * - BABYLON.VertexBuffer.UV4Kind
  21587. * - BABYLON.VertexBuffer.UV5Kind
  21588. * - BABYLON.VertexBuffer.UV6Kind
  21589. * - BABYLON.VertexBuffer.ColorKind
  21590. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21591. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21592. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21593. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21594. */
  21595. Mesh.prototype.getVerticesDataKinds = function () {
  21596. if (!this._geometry) {
  21597. var result = [];
  21598. if (this._delayInfo) {
  21599. this._delayInfo.forEach(function (kind, index, array) {
  21600. result.push(kind);
  21601. });
  21602. }
  21603. return result;
  21604. }
  21605. return this._geometry.getVerticesDataKinds();
  21606. };
  21607. /**
  21608. * Returns a positive integer : the total number of indices in this mesh geometry.
  21609. * Returns zero if the mesh has no geometry.
  21610. */
  21611. Mesh.prototype.getTotalIndices = function () {
  21612. if (!this._geometry) {
  21613. return 0;
  21614. }
  21615. return this._geometry.getTotalIndices();
  21616. };
  21617. /**
  21618. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  21619. * 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.
  21620. * Returns an empty array if the mesh has no geometry.
  21621. */
  21622. Mesh.prototype.getIndices = function (copyWhenShared) {
  21623. if (!this._geometry) {
  21624. return [];
  21625. }
  21626. return this._geometry.getIndices(copyWhenShared);
  21627. };
  21628. Object.defineProperty(Mesh.prototype, "isBlocked", {
  21629. get: function () {
  21630. return this._masterMesh !== null && this._masterMesh !== undefined;
  21631. },
  21632. enumerable: true,
  21633. configurable: true
  21634. });
  21635. /**
  21636. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  21637. */
  21638. Mesh.prototype.isReady = function () {
  21639. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21640. return false;
  21641. }
  21642. return _super.prototype.isReady.call(this);
  21643. };
  21644. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  21645. get: function () {
  21646. return this._sideOrientation;
  21647. },
  21648. /**
  21649. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  21650. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  21651. */
  21652. set: function (sideO) {
  21653. this._sideOrientation = sideO;
  21654. },
  21655. enumerable: true,
  21656. configurable: true
  21657. });
  21658. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  21659. /**
  21660. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  21661. * This property is pertinent only for updatable parametric shapes.
  21662. */
  21663. get: function () {
  21664. return this._areNormalsFrozen;
  21665. },
  21666. enumerable: true,
  21667. configurable: true
  21668. });
  21669. /**
  21670. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21671. * It has no effect at all on other shapes.
  21672. * It prevents the mesh normals from being recomputed on next `positions` array update.
  21673. * Returns the Mesh.
  21674. */
  21675. Mesh.prototype.freezeNormals = function () {
  21676. this._areNormalsFrozen = true;
  21677. return this;
  21678. };
  21679. /**
  21680. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21681. * It has no effect at all on other shapes.
  21682. * It reactivates the mesh normals computation if it was previously frozen.
  21683. * Returns the Mesh.
  21684. */
  21685. Mesh.prototype.unfreezeNormals = function () {
  21686. this._areNormalsFrozen = false;
  21687. return this;
  21688. };
  21689. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  21690. /**
  21691. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  21692. */
  21693. set: function (count) {
  21694. this._overridenInstanceCount = count;
  21695. },
  21696. enumerable: true,
  21697. configurable: true
  21698. });
  21699. // Methods
  21700. Mesh.prototype._preActivate = function () {
  21701. var sceneRenderId = this.getScene().getRenderId();
  21702. if (this._preActivateId === sceneRenderId) {
  21703. return this;
  21704. }
  21705. this._preActivateId = sceneRenderId;
  21706. this._visibleInstances = null;
  21707. return this;
  21708. };
  21709. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21710. if (this._visibleInstances) {
  21711. this._visibleInstances.intermediateDefaultRenderId = renderId;
  21712. }
  21713. return this;
  21714. };
  21715. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  21716. if (!this._visibleInstances) {
  21717. this._visibleInstances = {};
  21718. this._visibleInstances.defaultRenderId = renderId;
  21719. this._visibleInstances.selfDefaultRenderId = this._renderId;
  21720. }
  21721. if (!this._visibleInstances[renderId]) {
  21722. this._visibleInstances[renderId] = new Array();
  21723. }
  21724. this._visibleInstances[renderId].push(instance);
  21725. return this;
  21726. };
  21727. /**
  21728. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  21729. * This means the mesh underlying bounding box and sphere are recomputed.
  21730. * Returns the Mesh.
  21731. */
  21732. Mesh.prototype.refreshBoundingInfo = function () {
  21733. if (this._boundingInfo.isLocked) {
  21734. return;
  21735. }
  21736. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21737. if (data) {
  21738. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  21739. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21740. }
  21741. if (this.subMeshes) {
  21742. for (var index = 0; index < this.subMeshes.length; index++) {
  21743. this.subMeshes[index].refreshBoundingInfo();
  21744. }
  21745. }
  21746. this._updateBoundingInfo();
  21747. return this;
  21748. };
  21749. Mesh.prototype._createGlobalSubMesh = function (force) {
  21750. var totalVertices = this.getTotalVertices();
  21751. if (!totalVertices || !this.getIndices()) {
  21752. return null;
  21753. }
  21754. // Check if we need to recreate the submeshes
  21755. if (this.subMeshes && this.subMeshes.length > 0) {
  21756. var totalIndices = this.getIndices().length;
  21757. var needToRecreate = false;
  21758. if (force) {
  21759. needToRecreate = true;
  21760. }
  21761. else {
  21762. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21763. var submesh = _a[_i];
  21764. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  21765. needToRecreate = true;
  21766. break;
  21767. }
  21768. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  21769. needToRecreate = true;
  21770. break;
  21771. }
  21772. }
  21773. }
  21774. if (!needToRecreate) {
  21775. return;
  21776. }
  21777. }
  21778. this.releaseSubMeshes();
  21779. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  21780. };
  21781. Mesh.prototype.subdivide = function (count) {
  21782. if (count < 1) {
  21783. return;
  21784. }
  21785. var totalIndices = this.getTotalIndices();
  21786. var subdivisionSize = (totalIndices / count) | 0;
  21787. var offset = 0;
  21788. // Ensure that subdivisionSize is a multiple of 3
  21789. while (subdivisionSize % 3 !== 0) {
  21790. subdivisionSize++;
  21791. }
  21792. this.releaseSubMeshes();
  21793. for (var index = 0; index < count; index++) {
  21794. if (offset >= totalIndices) {
  21795. break;
  21796. }
  21797. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  21798. offset += subdivisionSize;
  21799. }
  21800. this.synchronizeInstances();
  21801. };
  21802. /**
  21803. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21804. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21805. * The `data` are either a numeric array either a Float32Array.
  21806. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  21807. * 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).
  21808. * Note that a new underlying VertexBuffer object is created each call.
  21809. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21810. *
  21811. * Possible `kind` values :
  21812. * - BABYLON.VertexBuffer.PositionKind
  21813. * - BABYLON.VertexBuffer.UVKind
  21814. * - BABYLON.VertexBuffer.UV2Kind
  21815. * - BABYLON.VertexBuffer.UV3Kind
  21816. * - BABYLON.VertexBuffer.UV4Kind
  21817. * - BABYLON.VertexBuffer.UV5Kind
  21818. * - BABYLON.VertexBuffer.UV6Kind
  21819. * - BABYLON.VertexBuffer.ColorKind
  21820. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21821. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21822. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21823. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21824. *
  21825. * Returns the Mesh.
  21826. */
  21827. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21828. if (!this._geometry) {
  21829. var vertexData = new BABYLON.VertexData();
  21830. vertexData.set(data, kind);
  21831. var scene = this.getScene();
  21832. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  21833. }
  21834. else {
  21835. this._geometry.setVerticesData(kind, data, updatable, stride);
  21836. }
  21837. return this;
  21838. };
  21839. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  21840. if (updatable === void 0) { updatable = true; }
  21841. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  21842. return;
  21843. }
  21844. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  21845. };
  21846. /**
  21847. * Sets the mesh VertexBuffer.
  21848. * Returns the Mesh.
  21849. */
  21850. Mesh.prototype.setVerticesBuffer = function (buffer) {
  21851. if (!this._geometry) {
  21852. var scene = this.getScene();
  21853. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  21854. }
  21855. this._geometry.setVerticesBuffer(buffer);
  21856. return this;
  21857. };
  21858. /**
  21859. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21860. * If the mesh has no geometry, it is simply returned as it is.
  21861. * The `data` are either a numeric array either a Float32Array.
  21862. * No new underlying VertexBuffer object is created.
  21863. * 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.
  21864. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  21865. *
  21866. * Possible `kind` values :
  21867. * - BABYLON.VertexBuffer.PositionKind
  21868. * - BABYLON.VertexBuffer.UVKind
  21869. * - BABYLON.VertexBuffer.UV2Kind
  21870. * - BABYLON.VertexBuffer.UV3Kind
  21871. * - BABYLON.VertexBuffer.UV4Kind
  21872. * - BABYLON.VertexBuffer.UV5Kind
  21873. * - BABYLON.VertexBuffer.UV6Kind
  21874. * - BABYLON.VertexBuffer.ColorKind
  21875. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21876. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21877. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21878. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21879. *
  21880. * Returns the Mesh.
  21881. */
  21882. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21883. if (!this._geometry) {
  21884. return;
  21885. }
  21886. if (!makeItUnique) {
  21887. this._geometry.updateVerticesData(kind, data, updateExtends);
  21888. }
  21889. else {
  21890. this.makeGeometryUnique();
  21891. this.updateVerticesData(kind, data, updateExtends, false);
  21892. }
  21893. return this;
  21894. };
  21895. /**
  21896. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  21897. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  21898. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  21899. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  21900. * Returns the Mesh.
  21901. */
  21902. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  21903. if (computeNormals === void 0) { computeNormals = true; }
  21904. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21905. positionFunction(positions);
  21906. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21907. if (computeNormals) {
  21908. var indices = this.getIndices();
  21909. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21910. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21911. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21912. }
  21913. return this;
  21914. };
  21915. /**
  21916. * Creates a un-shared specific occurence of the geometry for the mesh.
  21917. * Returns the Mesh.
  21918. */
  21919. Mesh.prototype.makeGeometryUnique = function () {
  21920. if (!this._geometry) {
  21921. return;
  21922. }
  21923. var oldGeometry = this._geometry;
  21924. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  21925. oldGeometry.releaseForMesh(this, true);
  21926. geometry.applyToMesh(this);
  21927. return this;
  21928. };
  21929. /**
  21930. * Sets the mesh indices.
  21931. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  21932. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21933. * This method creates a new index buffer each call.
  21934. * Returns the Mesh.
  21935. */
  21936. Mesh.prototype.setIndices = function (indices, totalVertices) {
  21937. if (!this._geometry) {
  21938. var vertexData = new BABYLON.VertexData();
  21939. vertexData.indices = indices;
  21940. var scene = this.getScene();
  21941. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  21942. }
  21943. else {
  21944. this._geometry.setIndices(indices, totalVertices);
  21945. }
  21946. return this;
  21947. };
  21948. /**
  21949. * Invert the geometry to move from a right handed system to a left handed one.
  21950. * Returns the Mesh.
  21951. */
  21952. Mesh.prototype.toLeftHanded = function () {
  21953. if (!this._geometry) {
  21954. return;
  21955. }
  21956. this._geometry.toLeftHanded();
  21957. return this;
  21958. };
  21959. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  21960. var engine = this.getScene().getEngine();
  21961. // Wireframe
  21962. var indexToBind;
  21963. if (this._unIndexed) {
  21964. indexToBind = null;
  21965. }
  21966. else {
  21967. switch (fillMode) {
  21968. case BABYLON.Material.PointFillMode:
  21969. indexToBind = null;
  21970. break;
  21971. case BABYLON.Material.WireFrameFillMode:
  21972. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  21973. break;
  21974. default:
  21975. case BABYLON.Material.TriangleFillMode:
  21976. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  21977. break;
  21978. }
  21979. }
  21980. // VBOs
  21981. this._geometry._bind(effect, indexToBind);
  21982. return this;
  21983. };
  21984. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  21985. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21986. return this;
  21987. }
  21988. this.onBeforeDrawObservable.notifyObservers(this);
  21989. var engine = this.getScene().getEngine();
  21990. // Draw order
  21991. switch (fillMode) {
  21992. case BABYLON.Material.PointFillMode:
  21993. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21994. break;
  21995. case BABYLON.Material.WireFrameFillMode:
  21996. if (this._unIndexed) {
  21997. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21998. }
  21999. else {
  22000. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  22001. }
  22002. break;
  22003. default:
  22004. if (this._unIndexed) {
  22005. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22006. }
  22007. else {
  22008. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  22009. }
  22010. }
  22011. return this;
  22012. };
  22013. /**
  22014. * Registers for this mesh a javascript function called just before the rendering process.
  22015. * This function is passed the current mesh.
  22016. * Return the Mesh.
  22017. */
  22018. Mesh.prototype.registerBeforeRender = function (func) {
  22019. this.onBeforeRenderObservable.add(func);
  22020. return this;
  22021. };
  22022. /**
  22023. * Disposes a previously registered javascript function called before the rendering.
  22024. * This function is passed the current mesh.
  22025. * Returns the Mesh.
  22026. */
  22027. Mesh.prototype.unregisterBeforeRender = function (func) {
  22028. this.onBeforeRenderObservable.removeCallback(func);
  22029. return this;
  22030. };
  22031. /**
  22032. * Registers for this mesh a javascript function called just after the rendering is complete.
  22033. * This function is passed the current mesh.
  22034. * Returns the Mesh.
  22035. */
  22036. Mesh.prototype.registerAfterRender = function (func) {
  22037. this.onAfterRenderObservable.add(func);
  22038. return this;
  22039. };
  22040. /**
  22041. * Disposes a previously registered javascript function called after the rendering.
  22042. * This function is passed the current mesh.
  22043. * Return the Mesh.
  22044. */
  22045. Mesh.prototype.unregisterAfterRender = function (func) {
  22046. this.onAfterRenderObservable.removeCallback(func);
  22047. return this;
  22048. };
  22049. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  22050. var scene = this.getScene();
  22051. this._batchCache.mustReturn = false;
  22052. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  22053. this._batchCache.visibleInstances[subMeshId] = null;
  22054. if (this._visibleInstances) {
  22055. var currentRenderId = scene.getRenderId();
  22056. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  22057. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  22058. var selfRenderId = this._renderId;
  22059. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  22060. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  22061. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  22062. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  22063. }
  22064. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  22065. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  22066. this._batchCache.mustReturn = true;
  22067. return this._batchCache;
  22068. }
  22069. if (currentRenderId !== selfRenderId) {
  22070. this._batchCache.renderSelf[subMeshId] = false;
  22071. }
  22072. }
  22073. this._renderIdForInstances[subMeshId] = currentRenderId;
  22074. }
  22075. return this._batchCache;
  22076. };
  22077. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  22078. var visibleInstances = batch.visibleInstances[subMesh._id];
  22079. var matricesCount = visibleInstances.length + 1;
  22080. var bufferSize = matricesCount * 16 * 4;
  22081. var currentInstancesBufferSize = this._instancesBufferSize;
  22082. var instancesBuffer = this._instancesBuffer;
  22083. while (this._instancesBufferSize < bufferSize) {
  22084. this._instancesBufferSize *= 2;
  22085. }
  22086. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  22087. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  22088. }
  22089. var offset = 0;
  22090. var instancesCount = 0;
  22091. var world = this.getWorldMatrix();
  22092. if (batch.renderSelf[subMesh._id]) {
  22093. world.copyToArray(this._instancesData, offset);
  22094. offset += 16;
  22095. instancesCount++;
  22096. }
  22097. if (visibleInstances) {
  22098. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  22099. var instance = visibleInstances[instanceIndex];
  22100. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  22101. offset += 16;
  22102. instancesCount++;
  22103. }
  22104. }
  22105. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  22106. if (instancesBuffer) {
  22107. instancesBuffer.dispose();
  22108. }
  22109. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  22110. this._instancesBuffer = instancesBuffer;
  22111. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  22112. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  22113. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  22114. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  22115. }
  22116. else {
  22117. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  22118. }
  22119. this._bind(subMesh, effect, fillMode);
  22120. this._draw(subMesh, fillMode, instancesCount);
  22121. engine.unbindInstanceAttributes();
  22122. return this;
  22123. };
  22124. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  22125. var scene = this.getScene();
  22126. var engine = scene.getEngine();
  22127. if (hardwareInstancedRendering) {
  22128. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  22129. }
  22130. else {
  22131. if (batch.renderSelf[subMesh._id]) {
  22132. // Draw
  22133. if (onBeforeDraw) {
  22134. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  22135. }
  22136. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  22137. }
  22138. if (batch.visibleInstances[subMesh._id]) {
  22139. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  22140. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  22141. // World
  22142. var world = instance.getWorldMatrix();
  22143. if (onBeforeDraw) {
  22144. onBeforeDraw(true, world, effectiveMaterial);
  22145. }
  22146. // Draw
  22147. this._draw(subMesh, fillMode);
  22148. }
  22149. }
  22150. }
  22151. return this;
  22152. };
  22153. /**
  22154. * Triggers the draw call for the mesh.
  22155. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  22156. * Returns the Mesh.
  22157. */
  22158. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  22159. this.checkOcclusionQuery();
  22160. if (this._isOccluded) {
  22161. return;
  22162. }
  22163. var scene = this.getScene();
  22164. // Managing instances
  22165. var batch = this._getInstancesRenderList(subMesh._id);
  22166. if (batch.mustReturn) {
  22167. return this;
  22168. }
  22169. // Checking geometry state
  22170. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  22171. return this;
  22172. }
  22173. var callbackIndex;
  22174. this.onBeforeRenderObservable.notifyObservers(this);
  22175. var engine = scene.getEngine();
  22176. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  22177. // Material
  22178. var effectiveMaterial = subMesh.getMaterial();
  22179. if (!effectiveMaterial) {
  22180. return this;
  22181. }
  22182. if (effectiveMaterial.storeEffectOnSubMeshes) {
  22183. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  22184. return this;
  22185. }
  22186. }
  22187. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  22188. return this;
  22189. }
  22190. // Alpha mode
  22191. if (enableAlphaMode) {
  22192. engine.setAlphaMode(effectiveMaterial.alphaMode);
  22193. }
  22194. // Outline - step 1
  22195. var savedDepthWrite = engine.getDepthWrite();
  22196. if (this.renderOutline) {
  22197. engine.setDepthWrite(false);
  22198. scene.getOutlineRenderer().render(subMesh, batch);
  22199. engine.setDepthWrite(savedDepthWrite);
  22200. }
  22201. var effect;
  22202. if (effectiveMaterial.storeEffectOnSubMeshes) {
  22203. effect = subMesh.effect;
  22204. }
  22205. else {
  22206. effect = effectiveMaterial.getEffect();
  22207. }
  22208. effectiveMaterial._preBind(effect);
  22209. // Bind
  22210. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  22211. if (!hardwareInstancedRendering) {
  22212. this._bind(subMesh, effect, fillMode);
  22213. }
  22214. var world = this.getWorldMatrix();
  22215. if (effectiveMaterial.storeEffectOnSubMeshes) {
  22216. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  22217. }
  22218. else {
  22219. effectiveMaterial.bind(world, this);
  22220. }
  22221. // Draw
  22222. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  22223. // Unbind
  22224. effectiveMaterial.unbind();
  22225. // Outline - step 2
  22226. if (this.renderOutline && savedDepthWrite) {
  22227. engine.setDepthWrite(true);
  22228. engine.setColorWrite(false);
  22229. scene.getOutlineRenderer().render(subMesh, batch);
  22230. engine.setColorWrite(true);
  22231. }
  22232. // Overlay
  22233. if (this.renderOverlay) {
  22234. var currentMode = engine.getAlphaMode();
  22235. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22236. scene.getOutlineRenderer().render(subMesh, batch, true);
  22237. engine.setAlphaMode(currentMode);
  22238. }
  22239. this.onAfterRenderObservable.notifyObservers(this);
  22240. return this;
  22241. };
  22242. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  22243. if (isInstance) {
  22244. effectiveMaterial.bindOnlyWorldMatrix(world);
  22245. }
  22246. return this;
  22247. };
  22248. /**
  22249. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  22250. */
  22251. Mesh.prototype.getEmittedParticleSystems = function () {
  22252. var results = new Array();
  22253. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22254. var particleSystem = this.getScene().particleSystems[index];
  22255. if (particleSystem.emitter === this) {
  22256. results.push(particleSystem);
  22257. }
  22258. }
  22259. return results;
  22260. };
  22261. /**
  22262. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  22263. */
  22264. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  22265. var results = new Array();
  22266. var descendants = this.getDescendants();
  22267. descendants.push(this);
  22268. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22269. var particleSystem = this.getScene().particleSystems[index];
  22270. var emitter = particleSystem.emitter;
  22271. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  22272. results.push(particleSystem);
  22273. }
  22274. }
  22275. return results;
  22276. };
  22277. Mesh.prototype._checkDelayState = function () {
  22278. var scene = this.getScene();
  22279. if (this._geometry) {
  22280. this._geometry.load(scene);
  22281. }
  22282. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22283. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  22284. this._queueLoad(this, scene);
  22285. }
  22286. return this;
  22287. };
  22288. Mesh.prototype._queueLoad = function (mesh, scene) {
  22289. var _this = this;
  22290. scene._addPendingData(mesh);
  22291. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  22292. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  22293. if (data instanceof ArrayBuffer) {
  22294. _this._delayLoadingFunction(data, _this);
  22295. }
  22296. else {
  22297. _this._delayLoadingFunction(JSON.parse(data), _this);
  22298. }
  22299. _this.instances.forEach(function (instance) {
  22300. instance._syncSubMeshes();
  22301. });
  22302. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22303. scene._removePendingData(_this);
  22304. }, function () { }, scene.database, getBinaryData);
  22305. return this;
  22306. };
  22307. /**
  22308. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  22309. */
  22310. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  22311. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22312. return false;
  22313. }
  22314. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  22315. return false;
  22316. }
  22317. this._checkDelayState();
  22318. return true;
  22319. };
  22320. /**
  22321. * Sets the mesh material by the material or multiMaterial `id` property.
  22322. * The material `id` is a string identifying the material or the multiMaterial.
  22323. * This method returns the Mesh.
  22324. */
  22325. Mesh.prototype.setMaterialByID = function (id) {
  22326. var materials = this.getScene().materials;
  22327. var index;
  22328. for (index = materials.length - 1; index > -1; index--) {
  22329. if (materials[index].id === id) {
  22330. this.material = materials[index];
  22331. return this;
  22332. }
  22333. }
  22334. // Multi
  22335. var multiMaterials = this.getScene().multiMaterials;
  22336. for (index = multiMaterials.length - 1; index > -1; index--) {
  22337. if (multiMaterials[index].id === id) {
  22338. this.material = multiMaterials[index];
  22339. return this;
  22340. }
  22341. }
  22342. return this;
  22343. };
  22344. /**
  22345. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  22346. */
  22347. Mesh.prototype.getAnimatables = function () {
  22348. var results = [];
  22349. if (this.material) {
  22350. results.push(this.material);
  22351. }
  22352. if (this.skeleton) {
  22353. results.push(this.skeleton);
  22354. }
  22355. return results;
  22356. };
  22357. /**
  22358. * Modifies the mesh geometry according to the passed transformation matrix.
  22359. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  22360. * The mesh normals are modified accordingly the same transformation.
  22361. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22362. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22363. * Returns the Mesh.
  22364. */
  22365. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  22366. // Position
  22367. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22368. return this;
  22369. }
  22370. var submeshes = this.subMeshes.splice(0);
  22371. this._resetPointsArrayCache();
  22372. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22373. var temp = [];
  22374. var index;
  22375. for (index = 0; index < data.length; index += 3) {
  22376. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  22377. }
  22378. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  22379. // Normals
  22380. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22381. return this;
  22382. }
  22383. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22384. temp = [];
  22385. for (index = 0; index < data.length; index += 3) {
  22386. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  22387. }
  22388. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  22389. // flip faces?
  22390. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  22391. this.flipFaces();
  22392. }
  22393. // Restore submeshes
  22394. this.releaseSubMeshes();
  22395. this.subMeshes = submeshes;
  22396. return this;
  22397. };
  22398. /**
  22399. * Modifies the mesh geometry according to its own current World Matrix.
  22400. * The mesh World Matrix is then reset.
  22401. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  22402. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22403. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22404. * Returns the Mesh.
  22405. */
  22406. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  22407. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  22408. this.scaling.copyFromFloats(1, 1, 1);
  22409. this.position.copyFromFloats(0, 0, 0);
  22410. this.rotation.copyFromFloats(0, 0, 0);
  22411. //only if quaternion is already set
  22412. if (this.rotationQuaternion) {
  22413. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  22414. }
  22415. this._worldMatrix = BABYLON.Matrix.Identity();
  22416. return this;
  22417. };
  22418. Object.defineProperty(Mesh.prototype, "_positions", {
  22419. // Cache
  22420. get: function () {
  22421. if (this._geometry) {
  22422. return this._geometry._positions;
  22423. }
  22424. return null;
  22425. },
  22426. enumerable: true,
  22427. configurable: true
  22428. });
  22429. Mesh.prototype._resetPointsArrayCache = function () {
  22430. if (this._geometry) {
  22431. this._geometry._resetPointsArrayCache();
  22432. }
  22433. return this;
  22434. };
  22435. Mesh.prototype._generatePointsArray = function () {
  22436. if (this._geometry) {
  22437. return this._geometry._generatePointsArray();
  22438. }
  22439. return false;
  22440. };
  22441. /**
  22442. * Returns a new Mesh object generated from the current mesh properties.
  22443. * This method must not get confused with createInstance().
  22444. * The parameter `name` is a string, the name given to the new mesh.
  22445. * The optional parameter `newParent` can be any Node object (default `null`).
  22446. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  22447. * 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.
  22448. */
  22449. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  22450. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22451. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  22452. };
  22453. /**
  22454. * Disposes the mesh.
  22455. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  22456. */
  22457. Mesh.prototype.dispose = function (doNotRecurse) {
  22458. var _this = this;
  22459. this.morphTargetManager = undefined;
  22460. if (this._geometry) {
  22461. this._geometry.releaseForMesh(this, true);
  22462. }
  22463. // Sources
  22464. var meshes = this.getScene().meshes;
  22465. meshes.forEach(function (mesh) {
  22466. if (mesh._source && mesh._source === _this) {
  22467. mesh._source = null;
  22468. }
  22469. });
  22470. this._source = null;
  22471. // Instances
  22472. if (this._instancesBuffer) {
  22473. this._instancesBuffer.dispose();
  22474. this._instancesBuffer = null;
  22475. }
  22476. while (this.instances.length) {
  22477. this.instances[0].dispose();
  22478. }
  22479. // Highlight layers.
  22480. var highlightLayers = this.getScene().highlightLayers;
  22481. for (var i = 0; i < highlightLayers.length; i++) {
  22482. var highlightLayer = highlightLayers[i];
  22483. if (highlightLayer) {
  22484. highlightLayer.removeMesh(this);
  22485. highlightLayer.removeExcludedMesh(this);
  22486. }
  22487. }
  22488. _super.prototype.dispose.call(this, doNotRecurse);
  22489. };
  22490. /**
  22491. * Modifies the mesh geometry according to a displacement map.
  22492. * 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.
  22493. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22494. * This method returns nothing.
  22495. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  22496. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22497. * 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.
  22498. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22499. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22500. *
  22501. * Returns the Mesh.
  22502. */
  22503. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  22504. var _this = this;
  22505. var scene = this.getScene();
  22506. var onload = function (img) {
  22507. // Getting height map data
  22508. var canvas = document.createElement("canvas");
  22509. var context = canvas.getContext("2d");
  22510. var heightMapWidth = img.width;
  22511. var heightMapHeight = img.height;
  22512. canvas.width = heightMapWidth;
  22513. canvas.height = heightMapHeight;
  22514. context.drawImage(img, 0, 0);
  22515. // Create VertexData from map data
  22516. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22517. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  22518. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  22519. //execute success callback, if set
  22520. if (onSuccess) {
  22521. onSuccess(_this);
  22522. }
  22523. };
  22524. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22525. return this;
  22526. };
  22527. /**
  22528. * Modifies the mesh geometry according to a displacementMap buffer.
  22529. * 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.
  22530. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22531. * This method returns nothing.
  22532. * 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.
  22533. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  22534. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22535. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22536. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22537. *
  22538. * Returns the Mesh.
  22539. */
  22540. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  22541. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  22542. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  22543. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22544. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  22545. return this;
  22546. }
  22547. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22548. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22549. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22550. var position = BABYLON.Vector3.Zero();
  22551. var normal = BABYLON.Vector3.Zero();
  22552. var uv = BABYLON.Vector2.Zero();
  22553. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  22554. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  22555. for (var index = 0; index < positions.length; index += 3) {
  22556. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  22557. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  22558. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  22559. // Compute height
  22560. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  22561. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  22562. var pos = (u + v * heightMapWidth) * 4;
  22563. var r = buffer[pos] / 255.0;
  22564. var g = buffer[pos + 1] / 255.0;
  22565. var b = buffer[pos + 2] / 255.0;
  22566. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22567. normal.normalize();
  22568. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  22569. position = position.add(normal);
  22570. position.toArray(positions, index);
  22571. }
  22572. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  22573. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  22574. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  22575. return this;
  22576. };
  22577. /**
  22578. * Modify the mesh to get a flat shading rendering.
  22579. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  22580. * This method returns the Mesh.
  22581. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  22582. */
  22583. Mesh.prototype.convertToFlatShadedMesh = function () {
  22584. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  22585. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22586. var kinds = this.getVerticesDataKinds();
  22587. var vbs = [];
  22588. var data = [];
  22589. var newdata = [];
  22590. var updatableNormals = false;
  22591. var kindIndex;
  22592. var kind;
  22593. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22594. kind = kinds[kindIndex];
  22595. var vertexBuffer = this.getVertexBuffer(kind);
  22596. if (kind === BABYLON.VertexBuffer.NormalKind) {
  22597. updatableNormals = vertexBuffer.isUpdatable();
  22598. kinds.splice(kindIndex, 1);
  22599. kindIndex--;
  22600. continue;
  22601. }
  22602. vbs[kind] = vertexBuffer;
  22603. data[kind] = vbs[kind].getData();
  22604. newdata[kind] = [];
  22605. }
  22606. // Save previous submeshes
  22607. var previousSubmeshes = this.subMeshes.slice(0);
  22608. var indices = this.getIndices();
  22609. var totalIndices = this.getTotalIndices();
  22610. // Generating unique vertices per face
  22611. var index;
  22612. for (index = 0; index < totalIndices; index++) {
  22613. var vertexIndex = indices[index];
  22614. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22615. kind = kinds[kindIndex];
  22616. var stride = vbs[kind].getStrideSize();
  22617. for (var offset = 0; offset < stride; offset++) {
  22618. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22619. }
  22620. }
  22621. }
  22622. // Updating faces & normal
  22623. var normals = [];
  22624. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  22625. for (index = 0; index < totalIndices; index += 3) {
  22626. indices[index] = index;
  22627. indices[index + 1] = index + 1;
  22628. indices[index + 2] = index + 2;
  22629. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  22630. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  22631. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  22632. var p1p2 = p1.subtract(p2);
  22633. var p3p2 = p3.subtract(p2);
  22634. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22635. // Store same normals for every vertex
  22636. for (var localIndex = 0; localIndex < 3; localIndex++) {
  22637. normals.push(normal.x);
  22638. normals.push(normal.y);
  22639. normals.push(normal.z);
  22640. }
  22641. }
  22642. this.setIndices(indices);
  22643. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  22644. // Updating vertex buffers
  22645. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22646. kind = kinds[kindIndex];
  22647. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22648. }
  22649. // Updating submeshes
  22650. this.releaseSubMeshes();
  22651. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22652. var previousOne = previousSubmeshes[submeshIndex];
  22653. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22654. }
  22655. this.synchronizeInstances();
  22656. return this;
  22657. };
  22658. /**
  22659. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  22660. * In other words, more vertices, no more indices and a single bigger VBO.
  22661. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  22662. * Returns the Mesh.
  22663. */
  22664. Mesh.prototype.convertToUnIndexedMesh = function () {
  22665. /// <summary>Remove indices by unfolding faces into buffers</summary>
  22666. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22667. var kinds = this.getVerticesDataKinds();
  22668. var vbs = [];
  22669. var data = [];
  22670. var newdata = [];
  22671. var updatableNormals = false;
  22672. var kindIndex;
  22673. var kind;
  22674. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22675. kind = kinds[kindIndex];
  22676. var vertexBuffer = this.getVertexBuffer(kind);
  22677. vbs[kind] = vertexBuffer;
  22678. data[kind] = vbs[kind].getData();
  22679. newdata[kind] = [];
  22680. }
  22681. // Save previous submeshes
  22682. var previousSubmeshes = this.subMeshes.slice(0);
  22683. var indices = this.getIndices();
  22684. var totalIndices = this.getTotalIndices();
  22685. // Generating unique vertices per face
  22686. var index;
  22687. for (index = 0; index < totalIndices; index++) {
  22688. var vertexIndex = indices[index];
  22689. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22690. kind = kinds[kindIndex];
  22691. var stride = vbs[kind].getStrideSize();
  22692. for (var offset = 0; offset < stride; offset++) {
  22693. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22694. }
  22695. }
  22696. }
  22697. // Updating indices
  22698. for (index = 0; index < totalIndices; index += 3) {
  22699. indices[index] = index;
  22700. indices[index + 1] = index + 1;
  22701. indices[index + 2] = index + 2;
  22702. }
  22703. this.setIndices(indices);
  22704. // Updating vertex buffers
  22705. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22706. kind = kinds[kindIndex];
  22707. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22708. }
  22709. // Updating submeshes
  22710. this.releaseSubMeshes();
  22711. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22712. var previousOne = previousSubmeshes[submeshIndex];
  22713. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22714. }
  22715. this._unIndexed = true;
  22716. this.synchronizeInstances();
  22717. return this;
  22718. };
  22719. /**
  22720. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  22721. * This method returns the Mesh.
  22722. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  22723. */
  22724. Mesh.prototype.flipFaces = function (flipNormals) {
  22725. if (flipNormals === void 0) { flipNormals = false; }
  22726. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  22727. var i;
  22728. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22729. for (i = 0; i < vertex_data.normals.length; i++) {
  22730. vertex_data.normals[i] *= -1;
  22731. }
  22732. }
  22733. var temp;
  22734. for (i = 0; i < vertex_data.indices.length; i += 3) {
  22735. // reassign indices
  22736. temp = vertex_data.indices[i + 1];
  22737. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  22738. vertex_data.indices[i + 2] = temp;
  22739. }
  22740. vertex_data.applyToMesh(this);
  22741. return this;
  22742. };
  22743. // Instances
  22744. /**
  22745. * Creates a new InstancedMesh object from the mesh model.
  22746. * An instance shares the same properties and the same material than its model.
  22747. * Only these properties of each instance can then be set individually :
  22748. * - position
  22749. * - rotation
  22750. * - rotationQuaternion
  22751. * - setPivotMatrix
  22752. * - scaling
  22753. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  22754. * Warning : this method is not supported for Line mesh and LineSystem
  22755. */
  22756. Mesh.prototype.createInstance = function (name) {
  22757. return new BABYLON.InstancedMesh(name, this);
  22758. };
  22759. /**
  22760. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  22761. * After this call, all the mesh instances have the same submeshes than the current mesh.
  22762. * This method returns the Mesh.
  22763. */
  22764. Mesh.prototype.synchronizeInstances = function () {
  22765. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  22766. var instance = this.instances[instanceIndex];
  22767. instance._syncSubMeshes();
  22768. }
  22769. return this;
  22770. };
  22771. /**
  22772. * Simplify the mesh according to the given array of settings.
  22773. * Function will return immediately and will simplify async. It returns the Mesh.
  22774. * @param settings a collection of simplification settings.
  22775. * @param parallelProcessing should all levels calculate parallel or one after the other.
  22776. * @param type the type of simplification to run.
  22777. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  22778. */
  22779. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  22780. if (parallelProcessing === void 0) { parallelProcessing = true; }
  22781. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  22782. this.getScene().simplificationQueue.addTask({
  22783. settings: settings,
  22784. parallelProcessing: parallelProcessing,
  22785. mesh: this,
  22786. simplificationType: simplificationType,
  22787. successCallback: successCallback
  22788. });
  22789. return this;
  22790. };
  22791. /**
  22792. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  22793. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  22794. * This should be used together with the simplification to avoid disappearing triangles.
  22795. * Returns the Mesh.
  22796. * @param successCallback an optional success callback to be called after the optimization finished.
  22797. */
  22798. Mesh.prototype.optimizeIndices = function (successCallback) {
  22799. var _this = this;
  22800. var indices = this.getIndices();
  22801. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22802. var vectorPositions = [];
  22803. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  22804. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  22805. }
  22806. var dupes = [];
  22807. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  22808. var realPos = vectorPositions.length - 1 - iteration;
  22809. var testedPosition = vectorPositions[realPos];
  22810. for (var j = 0; j < realPos; ++j) {
  22811. var againstPosition = vectorPositions[j];
  22812. if (testedPosition.equals(againstPosition)) {
  22813. dupes[realPos] = j;
  22814. break;
  22815. }
  22816. }
  22817. }, function () {
  22818. for (var i = 0; i < indices.length; ++i) {
  22819. indices[i] = dupes[indices[i]] || indices[i];
  22820. }
  22821. //indices are now reordered
  22822. var originalSubMeshes = _this.subMeshes.slice(0);
  22823. _this.setIndices(indices);
  22824. _this.subMeshes = originalSubMeshes;
  22825. if (successCallback) {
  22826. successCallback(_this);
  22827. }
  22828. });
  22829. return this;
  22830. };
  22831. Mesh.prototype.serialize = function (serializationObject) {
  22832. serializationObject.name = this.name;
  22833. serializationObject.id = this.id;
  22834. serializationObject.type = this.getClassName();
  22835. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  22836. serializationObject.tags = BABYLON.Tags.GetTags(this);
  22837. }
  22838. serializationObject.position = this.position.asArray();
  22839. if (this.rotationQuaternion) {
  22840. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  22841. }
  22842. else if (this.rotation) {
  22843. serializationObject.rotation = this.rotation.asArray();
  22844. }
  22845. serializationObject.scaling = this.scaling.asArray();
  22846. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  22847. serializationObject.isEnabled = this.isEnabled();
  22848. serializationObject.isVisible = this.isVisible;
  22849. serializationObject.infiniteDistance = this.infiniteDistance;
  22850. serializationObject.pickable = this.isPickable;
  22851. serializationObject.receiveShadows = this.receiveShadows;
  22852. serializationObject.billboardMode = this.billboardMode;
  22853. serializationObject.visibility = this.visibility;
  22854. serializationObject.checkCollisions = this.checkCollisions;
  22855. serializationObject.isBlocker = this.isBlocker;
  22856. // Parent
  22857. if (this.parent) {
  22858. serializationObject.parentId = this.parent.id;
  22859. }
  22860. // Geometry
  22861. var geometry = this._geometry;
  22862. if (geometry) {
  22863. var geometryId = geometry.id;
  22864. serializationObject.geometryId = geometryId;
  22865. // SubMeshes
  22866. serializationObject.subMeshes = [];
  22867. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  22868. var subMesh = this.subMeshes[subIndex];
  22869. serializationObject.subMeshes.push({
  22870. materialIndex: subMesh.materialIndex,
  22871. verticesStart: subMesh.verticesStart,
  22872. verticesCount: subMesh.verticesCount,
  22873. indexStart: subMesh.indexStart,
  22874. indexCount: subMesh.indexCount
  22875. });
  22876. }
  22877. }
  22878. // Material
  22879. if (this.material) {
  22880. serializationObject.materialId = this.material.id;
  22881. }
  22882. else {
  22883. this.material = null;
  22884. }
  22885. // Morph targets
  22886. if (this.morphTargetManager) {
  22887. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  22888. }
  22889. // Skeleton
  22890. if (this.skeleton) {
  22891. serializationObject.skeletonId = this.skeleton.id;
  22892. }
  22893. // Physics
  22894. //TODO implement correct serialization for physics impostors.
  22895. if (this.getPhysicsImpostor()) {
  22896. var impostor = this.getPhysicsImpostor();
  22897. serializationObject.physicsMass = impostor.getParam("mass");
  22898. serializationObject.physicsFriction = impostor.getParam("friction");
  22899. serializationObject.physicsRestitution = impostor.getParam("mass");
  22900. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  22901. }
  22902. // Metadata
  22903. if (this.metadata) {
  22904. serializationObject.metadata = this.metadata;
  22905. }
  22906. // Instances
  22907. serializationObject.instances = [];
  22908. for (var index = 0; index < this.instances.length; index++) {
  22909. var instance = this.instances[index];
  22910. var serializationInstance = {
  22911. name: instance.name,
  22912. position: instance.position.asArray(),
  22913. scaling: instance.scaling.asArray()
  22914. };
  22915. if (instance.rotationQuaternion) {
  22916. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  22917. }
  22918. else if (instance.rotation) {
  22919. serializationInstance.rotation = instance.rotation.asArray();
  22920. }
  22921. serializationObject.instances.push(serializationInstance);
  22922. // Animations
  22923. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  22924. serializationInstance.ranges = instance.serializeAnimationRanges();
  22925. }
  22926. //
  22927. // Animations
  22928. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22929. serializationObject.ranges = this.serializeAnimationRanges();
  22930. // Layer mask
  22931. serializationObject.layerMask = this.layerMask;
  22932. // Alpha
  22933. serializationObject.alphaIndex = this.alphaIndex;
  22934. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  22935. // Overlay
  22936. serializationObject.overlayAlpha = this.overlayAlpha;
  22937. serializationObject.overlayColor = this.overlayColor.asArray();
  22938. serializationObject.renderOverlay = this.renderOverlay;
  22939. // Fog
  22940. serializationObject.applyFog = this.applyFog;
  22941. // Action Manager
  22942. if (this.actionManager) {
  22943. serializationObject.actions = this.actionManager.serialize(this.name);
  22944. }
  22945. };
  22946. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  22947. if (!this.geometry) {
  22948. return;
  22949. }
  22950. this._markSubMeshesAsAttributesDirty();
  22951. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  22952. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  22953. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  22954. this.morphTargetManager = undefined;
  22955. return;
  22956. }
  22957. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  22958. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  22959. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  22960. if (morphTarget.hasNormals) {
  22961. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  22962. }
  22963. if (morphTarget.hasTangents) {
  22964. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  22965. }
  22966. }
  22967. }
  22968. else {
  22969. var index = 0;
  22970. // Positions
  22971. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  22972. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  22973. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  22974. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  22975. }
  22976. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  22977. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  22978. }
  22979. index++;
  22980. }
  22981. }
  22982. };
  22983. // Statics
  22984. /**
  22985. * Returns a new Mesh object what is a deep copy of the passed mesh.
  22986. * The parameter `parsedMesh` is the mesh to be copied.
  22987. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  22988. */
  22989. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  22990. var mesh;
  22991. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  22992. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  22993. }
  22994. else {
  22995. mesh = new Mesh(parsedMesh.name, scene);
  22996. }
  22997. mesh.id = parsedMesh.id;
  22998. if (BABYLON.Tags) {
  22999. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  23000. }
  23001. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  23002. if (parsedMesh.metadata !== undefined) {
  23003. mesh.metadata = parsedMesh.metadata;
  23004. }
  23005. if (parsedMesh.rotationQuaternion) {
  23006. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  23007. }
  23008. else if (parsedMesh.rotation) {
  23009. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  23010. }
  23011. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  23012. if (parsedMesh.localMatrix) {
  23013. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  23014. }
  23015. else if (parsedMesh.pivotMatrix) {
  23016. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  23017. }
  23018. mesh.setEnabled(parsedMesh.isEnabled);
  23019. mesh.isVisible = parsedMesh.isVisible;
  23020. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  23021. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  23022. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  23023. if (parsedMesh.applyFog !== undefined) {
  23024. mesh.applyFog = parsedMesh.applyFog;
  23025. }
  23026. if (parsedMesh.pickable !== undefined) {
  23027. mesh.isPickable = parsedMesh.pickable;
  23028. }
  23029. if (parsedMesh.alphaIndex !== undefined) {
  23030. mesh.alphaIndex = parsedMesh.alphaIndex;
  23031. }
  23032. mesh.receiveShadows = parsedMesh.receiveShadows;
  23033. mesh.billboardMode = parsedMesh.billboardMode;
  23034. if (parsedMesh.visibility !== undefined) {
  23035. mesh.visibility = parsedMesh.visibility;
  23036. }
  23037. mesh.checkCollisions = parsedMesh.checkCollisions;
  23038. if (parsedMesh.isBlocker !== undefined) {
  23039. mesh.isBlocker = parsedMesh.isBlocker;
  23040. }
  23041. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  23042. // freezeWorldMatrix
  23043. if (parsedMesh.freezeWorldMatrix) {
  23044. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  23045. }
  23046. // Parent
  23047. if (parsedMesh.parentId) {
  23048. mesh._waitingParentId = parsedMesh.parentId;
  23049. }
  23050. // Actions
  23051. if (parsedMesh.actions !== undefined) {
  23052. mesh._waitingActions = parsedMesh.actions;
  23053. }
  23054. // Overlay
  23055. if (parsedMesh.overlayAlpha !== undefined) {
  23056. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  23057. }
  23058. if (parsedMesh.overlayColor !== undefined) {
  23059. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  23060. }
  23061. if (parsedMesh.renderOverlay !== undefined) {
  23062. mesh.renderOverlay = parsedMesh.renderOverlay;
  23063. }
  23064. // Geometry
  23065. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  23066. if (parsedMesh.delayLoadingFile) {
  23067. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23068. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  23069. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  23070. if (parsedMesh._binaryInfo) {
  23071. mesh._binaryInfo = parsedMesh._binaryInfo;
  23072. }
  23073. mesh._delayInfo = [];
  23074. if (parsedMesh.hasUVs) {
  23075. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  23076. }
  23077. if (parsedMesh.hasUVs2) {
  23078. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  23079. }
  23080. if (parsedMesh.hasUVs3) {
  23081. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  23082. }
  23083. if (parsedMesh.hasUVs4) {
  23084. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  23085. }
  23086. if (parsedMesh.hasUVs5) {
  23087. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  23088. }
  23089. if (parsedMesh.hasUVs6) {
  23090. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  23091. }
  23092. if (parsedMesh.hasColors) {
  23093. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  23094. }
  23095. if (parsedMesh.hasMatricesIndices) {
  23096. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23097. }
  23098. if (parsedMesh.hasMatricesWeights) {
  23099. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23100. }
  23101. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  23102. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  23103. mesh._checkDelayState();
  23104. }
  23105. }
  23106. else {
  23107. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  23108. }
  23109. // Material
  23110. if (parsedMesh.materialId) {
  23111. mesh.setMaterialByID(parsedMesh.materialId);
  23112. }
  23113. else {
  23114. mesh.material = null;
  23115. }
  23116. // Morph targets
  23117. if (parsedMesh.morphTargetManagerId > -1) {
  23118. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  23119. }
  23120. // Skeleton
  23121. if (parsedMesh.skeletonId > -1) {
  23122. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  23123. if (parsedMesh.numBoneInfluencers) {
  23124. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  23125. }
  23126. }
  23127. // Animations
  23128. if (parsedMesh.animations) {
  23129. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23130. var parsedAnimation = parsedMesh.animations[animationIndex];
  23131. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23132. }
  23133. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  23134. }
  23135. if (parsedMesh.autoAnimate) {
  23136. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  23137. }
  23138. // Layer Mask
  23139. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  23140. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  23141. }
  23142. else {
  23143. mesh.layerMask = 0x0FFFFFFF;
  23144. }
  23145. // Physics
  23146. if (parsedMesh.physicsImpostor) {
  23147. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  23148. mass: parsedMesh.physicsMass,
  23149. friction: parsedMesh.physicsFriction,
  23150. restitution: parsedMesh.physicsRestitution
  23151. }, scene);
  23152. }
  23153. // Instances
  23154. if (parsedMesh.instances) {
  23155. for (var index = 0; index < parsedMesh.instances.length; index++) {
  23156. var parsedInstance = parsedMesh.instances[index];
  23157. var instance = mesh.createInstance(parsedInstance.name);
  23158. if (BABYLON.Tags) {
  23159. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  23160. }
  23161. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  23162. if (parsedInstance.parentId) {
  23163. instance._waitingParentId = parsedInstance.parentId;
  23164. }
  23165. if (parsedInstance.rotationQuaternion) {
  23166. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  23167. }
  23168. else if (parsedInstance.rotation) {
  23169. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  23170. }
  23171. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  23172. instance.checkCollisions = mesh.checkCollisions;
  23173. if (parsedMesh.animations) {
  23174. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23175. parsedAnimation = parsedMesh.animations[animationIndex];
  23176. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23177. }
  23178. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  23179. }
  23180. }
  23181. }
  23182. return mesh;
  23183. };
  23184. /**
  23185. * Creates a ribbon mesh.
  23186. * Please consider using the same method from the MeshBuilder class instead.
  23187. * 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.
  23188. *
  23189. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  23190. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  23191. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  23192. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  23193. * 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.
  23194. * 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.
  23195. * 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
  23196. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23197. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23198. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23199. */
  23200. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  23201. return BABYLON.MeshBuilder.CreateRibbon(name, {
  23202. pathArray: pathArray,
  23203. closeArray: closeArray,
  23204. closePath: closePath,
  23205. offset: offset,
  23206. updatable: updatable,
  23207. sideOrientation: sideOrientation,
  23208. instance: instance
  23209. }, scene);
  23210. };
  23211. /**
  23212. * Creates a plane polygonal mesh. By default, this is a disc.
  23213. * Please consider using the same method from the MeshBuilder class instead.
  23214. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  23215. * 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.
  23216. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23217. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23218. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23219. */
  23220. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  23221. var options = {
  23222. radius: radius,
  23223. tessellation: tessellation,
  23224. sideOrientation: sideOrientation,
  23225. updatable: updatable
  23226. };
  23227. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  23228. };
  23229. /**
  23230. * Creates a box mesh.
  23231. * Please consider using the same method from the MeshBuilder class instead.
  23232. * The parameter `size` sets the size (float) of each box side (default 1).
  23233. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23234. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23235. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23236. */
  23237. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  23238. var options = {
  23239. size: size,
  23240. sideOrientation: sideOrientation,
  23241. updatable: updatable
  23242. };
  23243. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  23244. };
  23245. /**
  23246. * Creates a sphere mesh.
  23247. * Please consider using the same method from the MeshBuilder class instead.
  23248. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  23249. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  23250. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23251. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23252. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23253. */
  23254. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  23255. var options = {
  23256. segments: segments,
  23257. diameterX: diameter,
  23258. diameterY: diameter,
  23259. diameterZ: diameter,
  23260. sideOrientation: sideOrientation,
  23261. updatable: updatable
  23262. };
  23263. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  23264. };
  23265. /**
  23266. * Creates a cylinder or a cone mesh.
  23267. * Please consider using the same method from the MeshBuilder class instead.
  23268. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  23269. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  23270. * 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.
  23271. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  23272. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  23273. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23274. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23275. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23276. */
  23277. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  23278. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  23279. if (scene !== undefined) {
  23280. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  23281. updatable = scene;
  23282. }
  23283. scene = subdivisions;
  23284. subdivisions = 1;
  23285. }
  23286. var options = {
  23287. height: height,
  23288. diameterTop: diameterTop,
  23289. diameterBottom: diameterBottom,
  23290. tessellation: tessellation,
  23291. subdivisions: subdivisions,
  23292. sideOrientation: sideOrientation,
  23293. updatable: updatable
  23294. };
  23295. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  23296. };
  23297. // Torus (Code from SharpDX.org)
  23298. /**
  23299. * Creates a torus mesh.
  23300. * Please consider using the same method from the MeshBuilder class instead.
  23301. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  23302. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  23303. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  23304. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23305. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23306. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23307. */
  23308. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  23309. var options = {
  23310. diameter: diameter,
  23311. thickness: thickness,
  23312. tessellation: tessellation,
  23313. sideOrientation: sideOrientation,
  23314. updatable: updatable
  23315. };
  23316. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  23317. };
  23318. /**
  23319. * Creates a torus knot mesh.
  23320. * Please consider using the same method from the MeshBuilder class instead.
  23321. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  23322. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  23323. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  23324. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  23325. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23326. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23327. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23328. */
  23329. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  23330. var options = {
  23331. radius: radius,
  23332. tube: tube,
  23333. radialSegments: radialSegments,
  23334. tubularSegments: tubularSegments,
  23335. p: p,
  23336. q: q,
  23337. sideOrientation: sideOrientation,
  23338. updatable: updatable
  23339. };
  23340. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  23341. };
  23342. /**
  23343. * Creates a line mesh.
  23344. * Please consider using the same method from the MeshBuilder class instead.
  23345. * 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.
  23346. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23347. * The parameter `points` is an array successive Vector3.
  23348. * 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
  23349. * When updating an instance, remember that only point positions can change, not the number of points.
  23350. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23351. */
  23352. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  23353. var options = {
  23354. points: points,
  23355. updatable: updatable,
  23356. instance: instance
  23357. };
  23358. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  23359. };
  23360. /**
  23361. * Creates a dashed line mesh.
  23362. * Please consider using the same method from the MeshBuilder class instead.
  23363. * 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.
  23364. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23365. * The parameter `points` is an array successive Vector3.
  23366. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  23367. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  23368. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  23369. * 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
  23370. * When updating an instance, remember that only point positions can change, not the number of points.
  23371. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23372. */
  23373. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  23374. var options = {
  23375. points: points,
  23376. dashSize: dashSize,
  23377. gapSize: gapSize,
  23378. dashNb: dashNb,
  23379. updatable: updatable,
  23380. instance: instance
  23381. };
  23382. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  23383. };
  23384. /**
  23385. * Creates a polygon mesh.
  23386. * Please consider using the same method from the MeshBuilder class instead.
  23387. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  23388. * 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.
  23389. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23390. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23391. * Remember you can only change the shape positions, not their number when updating a polygon.
  23392. */
  23393. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  23394. var options = {
  23395. shape: shape,
  23396. holes: holes,
  23397. updatable: updatable,
  23398. sideOrientation: sideOrientation
  23399. };
  23400. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  23401. };
  23402. /**
  23403. * Creates an extruded polygon mesh, with depth in the Y direction.
  23404. * Please consider using the same method from the MeshBuilder class instead.
  23405. */
  23406. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  23407. var options = {
  23408. shape: shape,
  23409. holes: holes,
  23410. depth: depth,
  23411. updatable: updatable,
  23412. sideOrientation: sideOrientation
  23413. };
  23414. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  23415. };
  23416. /**
  23417. * Creates an extruded shape mesh.
  23418. * 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.
  23419. * Please consider using the same method from the MeshBuilder class instead.
  23420. *
  23421. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23422. * 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
  23423. * extruded along the Z axis.
  23424. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23425. * 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.
  23426. * The parameter `scale` (float, default 1) is the value to scale the shape.
  23427. * 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
  23428. * 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
  23429. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23430. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23431. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23432. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23433. */
  23434. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  23435. var options = {
  23436. shape: shape,
  23437. path: path,
  23438. scale: scale,
  23439. rotation: rotation,
  23440. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23441. sideOrientation: sideOrientation,
  23442. instance: instance,
  23443. updatable: updatable
  23444. };
  23445. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  23446. };
  23447. /**
  23448. * Creates an custom extruded shape mesh.
  23449. * 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.
  23450. * Please consider using the same method from the MeshBuilder class instead.
  23451. *
  23452. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23453. * 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
  23454. * extruded along the Z axis.
  23455. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23456. * 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
  23457. * and the distance of this point from the begining of the path :
  23458. * ```javascript
  23459. * var rotationFunction = function(i, distance) {
  23460. * // do things
  23461. * return rotationValue; }
  23462. * ```
  23463. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  23464. * 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
  23465. * and the distance of this point from the begining of the path :
  23466. * ```javascript
  23467. * var scaleFunction = function(i, distance) {
  23468. * // do things
  23469. * return scaleValue;}
  23470. * ```
  23471. * It must returns a float value that will be the scale value applied to the shape on each path point.
  23472. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  23473. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  23474. * 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
  23475. * 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
  23476. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23477. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23478. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23479. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23480. */
  23481. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  23482. var options = {
  23483. shape: shape,
  23484. path: path,
  23485. scaleFunction: scaleFunction,
  23486. rotationFunction: rotationFunction,
  23487. ribbonCloseArray: ribbonCloseArray,
  23488. ribbonClosePath: ribbonClosePath,
  23489. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23490. sideOrientation: sideOrientation,
  23491. instance: instance,
  23492. updatable: updatable
  23493. };
  23494. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  23495. };
  23496. /**
  23497. * Creates lathe mesh.
  23498. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  23499. * Please consider using the same method from the MeshBuilder class instead.
  23500. * 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
  23501. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  23502. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  23503. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  23504. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23505. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23506. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23507. */
  23508. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  23509. var options = {
  23510. shape: shape,
  23511. radius: radius,
  23512. tessellation: tessellation,
  23513. sideOrientation: sideOrientation,
  23514. updatable: updatable
  23515. };
  23516. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  23517. };
  23518. /**
  23519. * Creates a plane mesh.
  23520. * Please consider using the same method from the MeshBuilder class instead.
  23521. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  23522. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23523. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23524. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23525. */
  23526. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  23527. var options = {
  23528. size: size,
  23529. width: size,
  23530. height: size,
  23531. sideOrientation: sideOrientation,
  23532. updatable: updatable
  23533. };
  23534. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  23535. };
  23536. /**
  23537. * Creates a ground mesh.
  23538. * Please consider using the same method from the MeshBuilder class instead.
  23539. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  23540. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  23541. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23542. */
  23543. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  23544. var options = {
  23545. width: width,
  23546. height: height,
  23547. subdivisions: subdivisions,
  23548. updatable: updatable
  23549. };
  23550. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  23551. };
  23552. /**
  23553. * Creates a tiled ground mesh.
  23554. * Please consider using the same method from the MeshBuilder class instead.
  23555. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  23556. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  23557. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  23558. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  23559. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  23560. * numbers of subdivisions on the ground width and height of each tile.
  23561. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23562. */
  23563. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  23564. var options = {
  23565. xmin: xmin,
  23566. zmin: zmin,
  23567. xmax: xmax,
  23568. zmax: zmax,
  23569. subdivisions: subdivisions,
  23570. precision: precision,
  23571. updatable: updatable
  23572. };
  23573. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  23574. };
  23575. /**
  23576. * Creates a ground mesh from a height map.
  23577. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  23578. * Please consider using the same method from the MeshBuilder class instead.
  23579. * The parameter `url` sets the URL of the height map image resource.
  23580. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  23581. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  23582. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  23583. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  23584. * 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).
  23585. * This function is passed the newly built mesh :
  23586. * ```javascript
  23587. * function(mesh) { // do things
  23588. * return; }
  23589. * ```
  23590. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23591. */
  23592. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  23593. var options = {
  23594. width: width,
  23595. height: height,
  23596. subdivisions: subdivisions,
  23597. minHeight: minHeight,
  23598. maxHeight: maxHeight,
  23599. updatable: updatable,
  23600. onReady: onReady
  23601. };
  23602. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  23603. };
  23604. /**
  23605. * Creates a tube mesh.
  23606. * 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.
  23607. * Please consider using the same method from the MeshBuilder class instead.
  23608. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  23609. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  23610. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  23611. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  23612. * 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.
  23613. * It must return a radius value (positive float) :
  23614. * ```javascript
  23615. * var radiusFunction = function(i, distance) {
  23616. * // do things
  23617. * return radius; }
  23618. * ```
  23619. * 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
  23620. * 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
  23621. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23622. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23623. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23624. */
  23625. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  23626. var options = {
  23627. path: path,
  23628. radius: radius,
  23629. tessellation: tessellation,
  23630. radiusFunction: radiusFunction,
  23631. arc: 1,
  23632. cap: cap,
  23633. updatable: updatable,
  23634. sideOrientation: sideOrientation,
  23635. instance: instance
  23636. };
  23637. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  23638. };
  23639. /**
  23640. * Creates a polyhedron mesh.
  23641. * Please consider using the same method from the MeshBuilder class instead.
  23642. * 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
  23643. * to choose the wanted type.
  23644. * The parameter `size` (positive float, default 1) sets the polygon size.
  23645. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23646. * 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`.
  23647. * 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
  23648. * 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)`).
  23649. * 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
  23650. * 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.
  23651. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23652. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23653. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23654. */
  23655. Mesh.CreatePolyhedron = function (name, options, scene) {
  23656. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  23657. };
  23658. /**
  23659. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  23660. * Please consider using the same method from the MeshBuilder class instead.
  23661. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  23662. * 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`).
  23663. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  23664. * 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.
  23665. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23666. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23667. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23668. */
  23669. Mesh.CreateIcoSphere = function (name, options, scene) {
  23670. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  23671. };
  23672. /**
  23673. * Creates a decal mesh.
  23674. * Please consider using the same method from the MeshBuilder class instead.
  23675. * 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.
  23676. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23677. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23678. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23679. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23680. */
  23681. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  23682. var options = {
  23683. position: position,
  23684. normal: normal,
  23685. size: size,
  23686. angle: angle
  23687. };
  23688. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  23689. };
  23690. // Skeletons
  23691. /**
  23692. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23693. */
  23694. Mesh.prototype.setPositionsForCPUSkinning = function () {
  23695. var source;
  23696. if (!this._sourcePositions) {
  23697. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23698. this._sourcePositions = new Float32Array(source);
  23699. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  23700. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  23701. }
  23702. }
  23703. return this._sourcePositions;
  23704. };
  23705. /**
  23706. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23707. */
  23708. Mesh.prototype.setNormalsForCPUSkinning = function () {
  23709. var source;
  23710. if (!this._sourceNormals) {
  23711. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23712. this._sourceNormals = new Float32Array(source);
  23713. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  23714. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  23715. }
  23716. }
  23717. return this._sourceNormals;
  23718. };
  23719. /**
  23720. * Updates the vertex buffer by applying transformation from the bones.
  23721. * Returns the Mesh.
  23722. *
  23723. * @param {skeleton} skeleton to apply
  23724. */
  23725. Mesh.prototype.applySkeleton = function (skeleton) {
  23726. if (!this.geometry) {
  23727. return this;
  23728. }
  23729. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  23730. return this;
  23731. }
  23732. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  23733. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23734. return this;
  23735. }
  23736. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23737. return this;
  23738. }
  23739. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23740. return this;
  23741. }
  23742. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23743. return this;
  23744. }
  23745. if (!this._sourcePositions) {
  23746. var submeshes = this.subMeshes.slice();
  23747. this.setPositionsForCPUSkinning();
  23748. this.subMeshes = submeshes;
  23749. }
  23750. if (!this._sourceNormals) {
  23751. this.setNormalsForCPUSkinning();
  23752. }
  23753. // positionsData checks for not being Float32Array will only pass at most once
  23754. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23755. if (!(positionsData instanceof Float32Array)) {
  23756. positionsData = new Float32Array(positionsData);
  23757. }
  23758. // normalsData checks for not being Float32Array will only pass at most once
  23759. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23760. if (!(normalsData instanceof Float32Array)) {
  23761. normalsData = new Float32Array(normalsData);
  23762. }
  23763. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23764. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23765. var needExtras = this.numBoneInfluencers > 4;
  23766. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  23767. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  23768. var skeletonMatrices = skeleton.getTransformMatrices(this);
  23769. var tempVector3 = BABYLON.Vector3.Zero();
  23770. var finalMatrix = new BABYLON.Matrix();
  23771. var tempMatrix = new BABYLON.Matrix();
  23772. var matWeightIdx = 0;
  23773. var inf;
  23774. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  23775. var weight;
  23776. for (inf = 0; inf < 4; inf++) {
  23777. weight = matricesWeightsData[matWeightIdx + inf];
  23778. if (weight > 0) {
  23779. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23780. finalMatrix.addToSelf(tempMatrix);
  23781. }
  23782. else
  23783. break;
  23784. }
  23785. if (needExtras) {
  23786. for (inf = 0; inf < 4; inf++) {
  23787. weight = matricesWeightsExtraData[matWeightIdx + inf];
  23788. if (weight > 0) {
  23789. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23790. finalMatrix.addToSelf(tempMatrix);
  23791. }
  23792. else
  23793. break;
  23794. }
  23795. }
  23796. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  23797. tempVector3.toArray(positionsData, index);
  23798. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  23799. tempVector3.toArray(normalsData, index);
  23800. finalMatrix.reset();
  23801. }
  23802. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  23803. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  23804. return this;
  23805. };
  23806. // Tools
  23807. /**
  23808. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  23809. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  23810. */
  23811. Mesh.MinMax = function (meshes) {
  23812. var minVector = null;
  23813. var maxVector = null;
  23814. meshes.forEach(function (mesh, index, array) {
  23815. var boundingBox = mesh.getBoundingInfo().boundingBox;
  23816. if (!minVector) {
  23817. minVector = boundingBox.minimumWorld;
  23818. maxVector = boundingBox.maximumWorld;
  23819. }
  23820. else {
  23821. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  23822. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  23823. }
  23824. });
  23825. return {
  23826. min: minVector,
  23827. max: maxVector
  23828. };
  23829. };
  23830. /**
  23831. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  23832. */
  23833. Mesh.Center = function (meshesOrMinMaxVector) {
  23834. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  23835. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  23836. };
  23837. /**
  23838. * Merge the array of meshes into a single mesh for performance reasons.
  23839. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  23840. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  23841. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  23842. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  23843. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  23844. */
  23845. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  23846. if (disposeSource === void 0) { disposeSource = true; }
  23847. var index;
  23848. if (!allow32BitsIndices) {
  23849. var totalVertices = 0;
  23850. // Counting vertices
  23851. for (index = 0; index < meshes.length; index++) {
  23852. if (meshes[index]) {
  23853. totalVertices += meshes[index].getTotalVertices();
  23854. if (totalVertices > 65536) {
  23855. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  23856. return null;
  23857. }
  23858. }
  23859. }
  23860. }
  23861. // Merge
  23862. var vertexData;
  23863. var otherVertexData;
  23864. var indiceArray = new Array();
  23865. var source;
  23866. for (index = 0; index < meshes.length; index++) {
  23867. if (meshes[index]) {
  23868. meshes[index].computeWorldMatrix(true);
  23869. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  23870. otherVertexData.transform(meshes[index].getWorldMatrix());
  23871. if (vertexData) {
  23872. vertexData.merge(otherVertexData);
  23873. }
  23874. else {
  23875. vertexData = otherVertexData;
  23876. source = meshes[index];
  23877. }
  23878. if (subdivideWithSubMeshes) {
  23879. indiceArray.push(meshes[index].getTotalIndices());
  23880. }
  23881. }
  23882. }
  23883. if (!meshSubclass) {
  23884. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  23885. }
  23886. vertexData.applyToMesh(meshSubclass);
  23887. // Setting properties
  23888. meshSubclass.material = source.material;
  23889. meshSubclass.checkCollisions = source.checkCollisions;
  23890. // Cleaning
  23891. if (disposeSource) {
  23892. for (index = 0; index < meshes.length; index++) {
  23893. if (meshes[index]) {
  23894. meshes[index].dispose();
  23895. }
  23896. }
  23897. }
  23898. // Subdivide
  23899. if (subdivideWithSubMeshes) {
  23900. //-- Suppresions du submesh global
  23901. meshSubclass.releaseSubMeshes();
  23902. index = 0;
  23903. var offset = 0;
  23904. //-- aplique la subdivision en fonction du tableau d'indices
  23905. while (index < indiceArray.length) {
  23906. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  23907. offset += indiceArray[index];
  23908. index++;
  23909. }
  23910. }
  23911. return meshSubclass;
  23912. };
  23913. // Consts
  23914. Mesh._FRONTSIDE = 0;
  23915. Mesh._BACKSIDE = 1;
  23916. Mesh._DOUBLESIDE = 2;
  23917. Mesh._DEFAULTSIDE = 0;
  23918. Mesh._NO_CAP = 0;
  23919. Mesh._CAP_START = 1;
  23920. Mesh._CAP_END = 2;
  23921. Mesh._CAP_ALL = 3;
  23922. return Mesh;
  23923. }(BABYLON.AbstractMesh));
  23924. BABYLON.Mesh = Mesh;
  23925. })(BABYLON || (BABYLON = {}));
  23926. //# sourceMappingURL=babylon.mesh.js.map
  23927. var BABYLON;
  23928. (function (BABYLON) {
  23929. var BaseSubMesh = (function () {
  23930. function BaseSubMesh() {
  23931. }
  23932. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  23933. get: function () {
  23934. return this._materialEffect;
  23935. },
  23936. enumerable: true,
  23937. configurable: true
  23938. });
  23939. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  23940. if (this._materialEffect === effect) {
  23941. if (!effect) {
  23942. this._materialDefines = undefined;
  23943. }
  23944. return;
  23945. }
  23946. this._materialDefines = defines;
  23947. this._materialEffect = effect;
  23948. };
  23949. return BaseSubMesh;
  23950. }());
  23951. BABYLON.BaseSubMesh = BaseSubMesh;
  23952. var SubMesh = (function (_super) {
  23953. __extends(SubMesh, _super);
  23954. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  23955. if (createBoundingBox === void 0) { createBoundingBox = true; }
  23956. var _this = _super.call(this) || this;
  23957. _this.materialIndex = materialIndex;
  23958. _this.verticesStart = verticesStart;
  23959. _this.verticesCount = verticesCount;
  23960. _this.indexStart = indexStart;
  23961. _this.indexCount = indexCount;
  23962. _this._renderId = 0;
  23963. _this._mesh = mesh;
  23964. _this._renderingMesh = renderingMesh || mesh;
  23965. mesh.subMeshes.push(_this);
  23966. _this._trianglePlanes = [];
  23967. _this._id = mesh.subMeshes.length - 1;
  23968. if (createBoundingBox) {
  23969. _this.refreshBoundingInfo();
  23970. mesh.computeWorldMatrix(true);
  23971. }
  23972. return _this;
  23973. }
  23974. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  23975. get: function () {
  23976. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  23977. },
  23978. enumerable: true,
  23979. configurable: true
  23980. });
  23981. /**
  23982. * Returns the submesh BoudingInfo object.
  23983. */
  23984. SubMesh.prototype.getBoundingInfo = function () {
  23985. if (this.IsGlobal) {
  23986. return this._mesh.getBoundingInfo();
  23987. }
  23988. return this._boundingInfo;
  23989. };
  23990. /**
  23991. * Sets the submesh BoundingInfo.
  23992. * Return the SubMesh.
  23993. */
  23994. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  23995. this._boundingInfo = boundingInfo;
  23996. return this;
  23997. };
  23998. /**
  23999. * Returns the mesh of the current submesh.
  24000. */
  24001. SubMesh.prototype.getMesh = function () {
  24002. return this._mesh;
  24003. };
  24004. /**
  24005. * Returns the rendering mesh of the submesh.
  24006. */
  24007. SubMesh.prototype.getRenderingMesh = function () {
  24008. return this._renderingMesh;
  24009. };
  24010. /**
  24011. * Returns the submesh material.
  24012. */
  24013. SubMesh.prototype.getMaterial = function () {
  24014. var rootMaterial = this._renderingMesh.material;
  24015. if (rootMaterial && rootMaterial.getSubMaterial) {
  24016. var multiMaterial = rootMaterial;
  24017. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  24018. if (this._currentMaterial !== effectiveMaterial) {
  24019. this._currentMaterial = effectiveMaterial;
  24020. this._materialDefines = undefined;
  24021. }
  24022. return effectiveMaterial;
  24023. }
  24024. if (!rootMaterial) {
  24025. return this._mesh.getScene().defaultMaterial;
  24026. }
  24027. return rootMaterial;
  24028. };
  24029. // Methods
  24030. /**
  24031. * Sets a new updated BoundingInfo object to the submesh.
  24032. * Returns the SubMesh.
  24033. */
  24034. SubMesh.prototype.refreshBoundingInfo = function () {
  24035. this._lastColliderWorldVertices = null;
  24036. if (this.IsGlobal) {
  24037. return;
  24038. }
  24039. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24040. if (!data) {
  24041. this._boundingInfo = this._mesh._boundingInfo;
  24042. return;
  24043. }
  24044. var indices = this._renderingMesh.getIndices();
  24045. var extend;
  24046. //is this the only submesh?
  24047. if (this.indexStart === 0 && this.indexCount === indices.length) {
  24048. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  24049. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  24050. }
  24051. else {
  24052. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  24053. }
  24054. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24055. return this;
  24056. };
  24057. SubMesh.prototype._checkCollision = function (collider) {
  24058. return this.getBoundingInfo()._checkCollision(collider);
  24059. };
  24060. /**
  24061. * Updates the submesh BoundingInfo.
  24062. * Returns the Submesh.
  24063. */
  24064. SubMesh.prototype.updateBoundingInfo = function (world) {
  24065. if (!this.getBoundingInfo()) {
  24066. this.refreshBoundingInfo();
  24067. }
  24068. this.getBoundingInfo().update(world);
  24069. return this;
  24070. };
  24071. /**
  24072. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  24073. * Boolean returned.
  24074. */
  24075. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  24076. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  24077. };
  24078. /**
  24079. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  24080. * Boolean returned.
  24081. */
  24082. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  24083. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  24084. };
  24085. /**
  24086. * Renders the submesh.
  24087. * Returns it.
  24088. */
  24089. SubMesh.prototype.render = function (enableAlphaMode) {
  24090. this._renderingMesh.render(this, enableAlphaMode);
  24091. return this;
  24092. };
  24093. /**
  24094. * Returns a new Index Buffer.
  24095. * Type returned : WebGLBuffer.
  24096. */
  24097. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  24098. if (!this._linesIndexBuffer) {
  24099. var linesIndices = [];
  24100. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24101. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  24102. }
  24103. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  24104. this.linesIndexCount = linesIndices.length;
  24105. }
  24106. return this._linesIndexBuffer;
  24107. };
  24108. /**
  24109. * True is the passed Ray intersects the submesh bounding box.
  24110. * Boolean returned.
  24111. */
  24112. SubMesh.prototype.canIntersects = function (ray) {
  24113. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  24114. };
  24115. /**
  24116. * Returns an object IntersectionInfo.
  24117. */
  24118. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  24119. var intersectInfo = null;
  24120. // LineMesh first as it's also a Mesh...
  24121. if (this._mesh instanceof BABYLON.LinesMesh) {
  24122. var lineMesh = this._mesh;
  24123. // Line test
  24124. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  24125. var p0 = positions[indices[index]];
  24126. var p1 = positions[indices[index + 1]];
  24127. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  24128. if (length < 0) {
  24129. continue;
  24130. }
  24131. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  24132. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  24133. if (fastCheck) {
  24134. break;
  24135. }
  24136. }
  24137. }
  24138. }
  24139. else {
  24140. // Triangles test
  24141. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24142. var p0 = positions[indices[index]];
  24143. var p1 = positions[indices[index + 1]];
  24144. var p2 = positions[indices[index + 2]];
  24145. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  24146. if (currentIntersectInfo) {
  24147. if (currentIntersectInfo.distance < 0) {
  24148. continue;
  24149. }
  24150. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  24151. intersectInfo = currentIntersectInfo;
  24152. intersectInfo.faceId = index / 3;
  24153. if (fastCheck) {
  24154. break;
  24155. }
  24156. }
  24157. }
  24158. }
  24159. }
  24160. return intersectInfo;
  24161. };
  24162. SubMesh.prototype._rebuild = function () {
  24163. if (this._linesIndexBuffer) {
  24164. this._linesIndexBuffer = null;
  24165. }
  24166. };
  24167. // Clone
  24168. /**
  24169. * Creates a new Submesh from the passed Mesh.
  24170. */
  24171. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  24172. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  24173. if (!this.IsGlobal) {
  24174. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  24175. }
  24176. return result;
  24177. };
  24178. // Dispose
  24179. /**
  24180. * Disposes the Submesh.
  24181. * Returns nothing.
  24182. */
  24183. SubMesh.prototype.dispose = function () {
  24184. if (this._linesIndexBuffer) {
  24185. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  24186. this._linesIndexBuffer = null;
  24187. }
  24188. // Remove from mesh
  24189. var index = this._mesh.subMeshes.indexOf(this);
  24190. this._mesh.subMeshes.splice(index, 1);
  24191. };
  24192. // Statics
  24193. /**
  24194. * Creates a new Submesh from the passed parameters :
  24195. * - materialIndex (integer) : the index of the main mesh material.
  24196. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  24197. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  24198. * - mesh (Mesh) : the main mesh to create the submesh from.
  24199. * - renderingMesh (optional Mesh) : rendering mesh.
  24200. */
  24201. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  24202. var minVertexIndex = Number.MAX_VALUE;
  24203. var maxVertexIndex = -Number.MAX_VALUE;
  24204. renderingMesh = renderingMesh || mesh;
  24205. var indices = renderingMesh.getIndices();
  24206. for (var index = startIndex; index < startIndex + indexCount; index++) {
  24207. var vertexIndex = indices[index];
  24208. if (vertexIndex < minVertexIndex)
  24209. minVertexIndex = vertexIndex;
  24210. if (vertexIndex > maxVertexIndex)
  24211. maxVertexIndex = vertexIndex;
  24212. }
  24213. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  24214. };
  24215. return SubMesh;
  24216. }(BaseSubMesh));
  24217. BABYLON.SubMesh = SubMesh;
  24218. })(BABYLON || (BABYLON = {}));
  24219. //# sourceMappingURL=babylon.subMesh.js.map
  24220. var BABYLON;
  24221. (function (BABYLON) {
  24222. var EffectFallbacks = (function () {
  24223. function EffectFallbacks() {
  24224. this._defines = {};
  24225. this._currentRank = 32;
  24226. this._maxRank = -1;
  24227. }
  24228. EffectFallbacks.prototype.unBindMesh = function () {
  24229. this._mesh = null;
  24230. };
  24231. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24232. if (!this._defines[rank]) {
  24233. if (rank < this._currentRank) {
  24234. this._currentRank = rank;
  24235. }
  24236. if (rank > this._maxRank) {
  24237. this._maxRank = rank;
  24238. }
  24239. this._defines[rank] = new Array();
  24240. }
  24241. this._defines[rank].push(define);
  24242. };
  24243. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  24244. this._meshRank = rank;
  24245. this._mesh = mesh;
  24246. if (rank < this._currentRank) {
  24247. this._currentRank = rank;
  24248. }
  24249. if (rank > this._maxRank) {
  24250. this._maxRank = rank;
  24251. }
  24252. };
  24253. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  24254. get: function () {
  24255. return this._currentRank <= this._maxRank;
  24256. },
  24257. enumerable: true,
  24258. configurable: true
  24259. });
  24260. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24261. // First we try to switch to CPU skinning
  24262. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  24263. this._mesh.computeBonesUsingShaders = false;
  24264. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  24265. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24266. var scene = this._mesh.getScene();
  24267. for (var index = 0; index < scene.meshes.length; index++) {
  24268. var otherMesh = scene.meshes[index];
  24269. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  24270. otherMesh.computeBonesUsingShaders = false;
  24271. }
  24272. }
  24273. }
  24274. else {
  24275. var currentFallbacks = this._defines[this._currentRank];
  24276. if (currentFallbacks) {
  24277. for (var index = 0; index < currentFallbacks.length; index++) {
  24278. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24279. }
  24280. }
  24281. this._currentRank++;
  24282. }
  24283. return currentDefines;
  24284. };
  24285. return EffectFallbacks;
  24286. }());
  24287. BABYLON.EffectFallbacks = EffectFallbacks;
  24288. var EffectCreationOptions = (function () {
  24289. function EffectCreationOptions() {
  24290. }
  24291. return EffectCreationOptions;
  24292. }());
  24293. BABYLON.EffectCreationOptions = EffectCreationOptions;
  24294. var Effect = (function () {
  24295. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24296. var _this = this;
  24297. this.uniqueId = 0;
  24298. this.onCompileObservable = new BABYLON.Observable();
  24299. this.onErrorObservable = new BABYLON.Observable();
  24300. this.onBindObservable = new BABYLON.Observable();
  24301. this._uniformBuffersNames = {};
  24302. this._isReady = false;
  24303. this._compilationError = "";
  24304. this.name = baseName;
  24305. if (attributesNamesOrOptions.attributes) {
  24306. var options = attributesNamesOrOptions;
  24307. this._engine = uniformsNamesOrEngine;
  24308. this._attributesNames = options.attributes;
  24309. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  24310. this._samplers = options.samplers;
  24311. this.defines = options.defines;
  24312. this.onError = options.onError;
  24313. this.onCompiled = options.onCompiled;
  24314. this._fallbacks = options.fallbacks;
  24315. this._indexParameters = options.indexParameters;
  24316. if (options.uniformBuffersNames) {
  24317. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  24318. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  24319. }
  24320. }
  24321. }
  24322. else {
  24323. this._engine = engine;
  24324. this.defines = defines;
  24325. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  24326. this._samplers = samplers;
  24327. this._attributesNames = attributesNamesOrOptions;
  24328. this.onError = onError;
  24329. this.onCompiled = onCompiled;
  24330. this._indexParameters = indexParameters;
  24331. this._fallbacks = fallbacks;
  24332. }
  24333. this.uniqueId = Effect._uniqueIdSeed++;
  24334. var vertexSource;
  24335. var fragmentSource;
  24336. if (baseName.vertexElement) {
  24337. vertexSource = document.getElementById(baseName.vertexElement);
  24338. if (!vertexSource) {
  24339. vertexSource = baseName.vertexElement;
  24340. }
  24341. }
  24342. else {
  24343. vertexSource = baseName.vertex || baseName;
  24344. }
  24345. if (baseName.fragmentElement) {
  24346. fragmentSource = document.getElementById(baseName.fragmentElement);
  24347. if (!fragmentSource) {
  24348. fragmentSource = baseName.fragmentElement;
  24349. }
  24350. }
  24351. else {
  24352. fragmentSource = baseName.fragment || baseName;
  24353. }
  24354. this._loadVertexShader(vertexSource, function (vertexCode) {
  24355. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24356. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  24357. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24358. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24359. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  24360. if (baseName) {
  24361. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + baseName + "\n" + migratedVertexCode;
  24362. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + baseName + "\n" + migratedFragmentCode;
  24363. }
  24364. else {
  24365. _this._vertexSourceCode = migratedVertexCode;
  24366. _this._fragmentSourceCode = migratedFragmentCode;
  24367. }
  24368. _this._prepareEffect();
  24369. });
  24370. });
  24371. });
  24372. });
  24373. });
  24374. });
  24375. }
  24376. Object.defineProperty(Effect.prototype, "key", {
  24377. get: function () {
  24378. return this._key;
  24379. },
  24380. enumerable: true,
  24381. configurable: true
  24382. });
  24383. // Properties
  24384. Effect.prototype.isReady = function () {
  24385. return this._isReady;
  24386. };
  24387. Effect.prototype.getEngine = function () {
  24388. return this._engine;
  24389. };
  24390. Effect.prototype.getProgram = function () {
  24391. return this._program;
  24392. };
  24393. Effect.prototype.getAttributesNames = function () {
  24394. return this._attributesNames;
  24395. };
  24396. Effect.prototype.getAttributeLocation = function (index) {
  24397. return this._attributes[index];
  24398. };
  24399. Effect.prototype.getAttributeLocationByName = function (name) {
  24400. var index = this._attributesNames.indexOf(name);
  24401. return this._attributes[index];
  24402. };
  24403. Effect.prototype.getAttributesCount = function () {
  24404. return this._attributes.length;
  24405. };
  24406. Effect.prototype.getUniformIndex = function (uniformName) {
  24407. return this._uniformsNames.indexOf(uniformName);
  24408. };
  24409. Effect.prototype.getUniform = function (uniformName) {
  24410. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24411. };
  24412. Effect.prototype.getSamplers = function () {
  24413. return this._samplers;
  24414. };
  24415. Effect.prototype.getCompilationError = function () {
  24416. return this._compilationError;
  24417. };
  24418. // Methods
  24419. Effect.prototype.executeWhenCompiled = function (func) {
  24420. if (this.isReady()) {
  24421. func(this);
  24422. return;
  24423. }
  24424. this.onCompileObservable.add(function (effect) {
  24425. func(effect);
  24426. });
  24427. };
  24428. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24429. // DOM element ?
  24430. if (vertex instanceof HTMLElement) {
  24431. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24432. callback(vertexCode);
  24433. return;
  24434. }
  24435. // Base64 encoded ?
  24436. if (vertex.substr(0, 7) === "base64:") {
  24437. var vertexBinary = window.atob(vertex.substr(7));
  24438. callback(vertexBinary);
  24439. return;
  24440. }
  24441. // Is in local store ?
  24442. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24443. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24444. return;
  24445. }
  24446. var vertexShaderUrl;
  24447. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24448. vertexShaderUrl = vertex;
  24449. }
  24450. else {
  24451. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24452. }
  24453. // Vertex shader
  24454. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24455. };
  24456. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24457. // DOM element ?
  24458. if (fragment instanceof HTMLElement) {
  24459. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24460. callback(fragmentCode);
  24461. return;
  24462. }
  24463. // Base64 encoded ?
  24464. if (fragment.substr(0, 7) === "base64:") {
  24465. var fragmentBinary = window.atob(fragment.substr(7));
  24466. callback(fragmentBinary);
  24467. return;
  24468. }
  24469. // Is in local store ?
  24470. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24471. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24472. return;
  24473. }
  24474. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24475. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24476. return;
  24477. }
  24478. var fragmentShaderUrl;
  24479. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24480. fragmentShaderUrl = fragment;
  24481. }
  24482. else {
  24483. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24484. }
  24485. // Fragment shader
  24486. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24487. };
  24488. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  24489. // Rebuild shaders source code
  24490. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  24491. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  24492. vertexCode = prefix + vertexCode;
  24493. fragmentCode = prefix + fragmentCode;
  24494. // Number lines of shaders source code
  24495. var i = 2;
  24496. var regex = /\n/gm;
  24497. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24498. i = 2;
  24499. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24500. // Dump shaders name and formatted source code
  24501. if (this.name.vertexElement) {
  24502. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  24503. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  24504. }
  24505. else if (this.name.vertex) {
  24506. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  24507. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  24508. }
  24509. else {
  24510. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  24511. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  24512. }
  24513. };
  24514. ;
  24515. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  24516. var preparedSourceCode = this._processPrecision(sourceCode);
  24517. if (this._engine.webGLVersion == 1) {
  24518. callback(preparedSourceCode);
  24519. return;
  24520. }
  24521. // Already converted
  24522. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  24523. callback(preparedSourceCode.replace("#version 300 es", ""));
  24524. return;
  24525. }
  24526. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  24527. // Remove extensions
  24528. // #extension GL_OES_standard_derivatives : enable
  24529. // #extension GL_EXT_shader_texture_lod : enable
  24530. // #extension GL_EXT_frag_depth : enable
  24531. // #extension GL_EXT_draw_buffers : require
  24532. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  24533. var result = preparedSourceCode.replace(regex, "");
  24534. // Migrate to GLSL v300
  24535. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  24536. result = result.replace(/attribute[ \t]/g, "in ");
  24537. result = result.replace(/[ \t]attribute/g, " in");
  24538. if (isFragment) {
  24539. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  24540. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  24541. result = result.replace(/texture2D\(/g, "texture(");
  24542. result = result.replace(/textureCube\(/g, "texture(");
  24543. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  24544. result = result.replace(/gl_FragColor/g, "glFragColor");
  24545. result = result.replace(/gl_FragData/g, "glFragData");
  24546. result = result.replace(/void\s+?main\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  24547. }
  24548. callback(result);
  24549. };
  24550. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24551. var _this = this;
  24552. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24553. var match = regex.exec(sourceCode);
  24554. var returnValue = new String(sourceCode);
  24555. while (match != null) {
  24556. var includeFile = match[1];
  24557. // Uniform declaration
  24558. if (includeFile.indexOf("__decl__") !== -1) {
  24559. includeFile = includeFile.replace(/__decl__/, "");
  24560. if (this._engine.supportsUniformBuffers) {
  24561. includeFile = includeFile.replace(/Vertex/, "Ubo");
  24562. includeFile = includeFile.replace(/Fragment/, "Ubo");
  24563. }
  24564. includeFile = includeFile + "Declaration";
  24565. }
  24566. if (Effect.IncludesShadersStore[includeFile]) {
  24567. // Substitution
  24568. var includeContent = Effect.IncludesShadersStore[includeFile];
  24569. if (match[2]) {
  24570. var splits = match[3].split(",");
  24571. for (var index = 0; index < splits.length; index += 2) {
  24572. var source = new RegExp(splits[index], "g");
  24573. var dest = splits[index + 1];
  24574. includeContent = includeContent.replace(source, dest);
  24575. }
  24576. }
  24577. if (match[4]) {
  24578. var indexString = match[5];
  24579. if (indexString.indexOf("..") !== -1) {
  24580. var indexSplits = indexString.split("..");
  24581. var minIndex = parseInt(indexSplits[0]);
  24582. var maxIndex = parseInt(indexSplits[1]);
  24583. var sourceIncludeContent = includeContent.slice(0);
  24584. includeContent = "";
  24585. if (isNaN(maxIndex)) {
  24586. maxIndex = this._indexParameters[indexSplits[1]];
  24587. }
  24588. for (var i = minIndex; i < maxIndex; i++) {
  24589. if (!this._engine.supportsUniformBuffers) {
  24590. // Ubo replacement
  24591. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24592. return p1 + "{X}";
  24593. });
  24594. }
  24595. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24596. }
  24597. }
  24598. else {
  24599. if (!this._engine.supportsUniformBuffers) {
  24600. // Ubo replacement
  24601. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24602. return p1 + "{X}";
  24603. });
  24604. }
  24605. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24606. }
  24607. }
  24608. // Replace
  24609. returnValue = returnValue.replace(match[0], includeContent);
  24610. }
  24611. else {
  24612. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24613. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24614. Effect.IncludesShadersStore[includeFile] = fileContent;
  24615. _this._processIncludes(returnValue, callback);
  24616. });
  24617. return;
  24618. }
  24619. match = regex.exec(sourceCode);
  24620. }
  24621. callback(returnValue);
  24622. };
  24623. Effect.prototype._processPrecision = function (source) {
  24624. if (source.indexOf("precision highp float") === -1) {
  24625. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24626. source = "precision mediump float;\n" + source;
  24627. }
  24628. else {
  24629. source = "precision highp float;\n" + source;
  24630. }
  24631. }
  24632. else {
  24633. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24634. source = source.replace("precision highp float", "precision mediump float");
  24635. }
  24636. }
  24637. return source;
  24638. };
  24639. Effect.prototype._prepareEffect = function () {
  24640. var attributesNames = this._attributesNames;
  24641. var defines = this.defines;
  24642. var fallbacks = this._fallbacks;
  24643. this._valueCache = {};
  24644. try {
  24645. var engine = this._engine;
  24646. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24647. if (engine.webGLVersion > 1) {
  24648. for (var name in this._uniformBuffersNames) {
  24649. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  24650. }
  24651. }
  24652. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24653. this._attributes = engine.getAttributes(this._program, attributesNames);
  24654. var index;
  24655. for (index = 0; index < this._samplers.length; index++) {
  24656. var sampler = this.getUniform(this._samplers[index]);
  24657. if (sampler == null) {
  24658. this._samplers.splice(index, 1);
  24659. index--;
  24660. }
  24661. }
  24662. engine.bindSamplers(this);
  24663. this._compilationError = "";
  24664. this._isReady = true;
  24665. if (this.onCompiled) {
  24666. this.onCompiled(this);
  24667. }
  24668. this.onCompileObservable.notifyObservers(this);
  24669. this.onCompileObservable.clear();
  24670. // Unbind mesh reference in fallbacks
  24671. if (this._fallbacks) {
  24672. this._fallbacks.unBindMesh();
  24673. }
  24674. }
  24675. catch (e) {
  24676. this._compilationError = e.message;
  24677. // Let's go through fallbacks then
  24678. BABYLON.Tools.Error("Unable to compile effect:");
  24679. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  24680. return " " + uniform;
  24681. }));
  24682. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  24683. return " " + attribute;
  24684. }));
  24685. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24686. BABYLON.Tools.Error("Error: " + this._compilationError);
  24687. if (fallbacks && fallbacks.isMoreFallbacks) {
  24688. BABYLON.Tools.Error("Trying next fallback.");
  24689. this.defines = fallbacks.reduce(this.defines);
  24690. this._prepareEffect();
  24691. }
  24692. else {
  24693. if (this.onError) {
  24694. this.onError(this, this._compilationError);
  24695. }
  24696. this.onErrorObservable.notifyObservers(this);
  24697. this.onErrorObservable.clear();
  24698. // Unbind mesh reference in fallbacks
  24699. if (this._fallbacks) {
  24700. this._fallbacks.unBindMesh();
  24701. }
  24702. }
  24703. }
  24704. };
  24705. Object.defineProperty(Effect.prototype, "isSupported", {
  24706. get: function () {
  24707. return this._compilationError === "";
  24708. },
  24709. enumerable: true,
  24710. configurable: true
  24711. });
  24712. Effect.prototype._bindTexture = function (channel, texture) {
  24713. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24714. };
  24715. Effect.prototype.setTexture = function (channel, texture) {
  24716. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24717. };
  24718. Effect.prototype.setTextureArray = function (channel, textures) {
  24719. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24720. var initialPos = this._samplers.indexOf(channel);
  24721. for (var index = 1; index < textures.length; index++) {
  24722. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24723. }
  24724. }
  24725. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24726. };
  24727. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24728. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24729. };
  24730. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24731. var cache = this._valueCache[uniformName];
  24732. var flag = matrix.updateFlag;
  24733. if (cache !== undefined && cache === flag) {
  24734. return false;
  24735. }
  24736. this._valueCache[uniformName] = flag;
  24737. return true;
  24738. };
  24739. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24740. var cache = this._valueCache[uniformName];
  24741. if (!cache) {
  24742. cache = [x, y];
  24743. this._valueCache[uniformName] = cache;
  24744. return true;
  24745. }
  24746. var changed = false;
  24747. if (cache[0] !== x) {
  24748. cache[0] = x;
  24749. changed = true;
  24750. }
  24751. if (cache[1] !== y) {
  24752. cache[1] = y;
  24753. changed = true;
  24754. }
  24755. return changed;
  24756. };
  24757. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24758. var cache = this._valueCache[uniformName];
  24759. if (!cache) {
  24760. cache = [x, y, z];
  24761. this._valueCache[uniformName] = cache;
  24762. return true;
  24763. }
  24764. var changed = false;
  24765. if (cache[0] !== x) {
  24766. cache[0] = x;
  24767. changed = true;
  24768. }
  24769. if (cache[1] !== y) {
  24770. cache[1] = y;
  24771. changed = true;
  24772. }
  24773. if (cache[2] !== z) {
  24774. cache[2] = z;
  24775. changed = true;
  24776. }
  24777. return changed;
  24778. };
  24779. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24780. var cache = this._valueCache[uniformName];
  24781. if (!cache) {
  24782. cache = [x, y, z, w];
  24783. this._valueCache[uniformName] = cache;
  24784. return true;
  24785. }
  24786. var changed = false;
  24787. if (cache[0] !== x) {
  24788. cache[0] = x;
  24789. changed = true;
  24790. }
  24791. if (cache[1] !== y) {
  24792. cache[1] = y;
  24793. changed = true;
  24794. }
  24795. if (cache[2] !== z) {
  24796. cache[2] = z;
  24797. changed = true;
  24798. }
  24799. if (cache[3] !== w) {
  24800. cache[3] = w;
  24801. changed = true;
  24802. }
  24803. return changed;
  24804. };
  24805. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  24806. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  24807. return;
  24808. }
  24809. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  24810. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  24811. };
  24812. Effect.prototype.bindUniformBlock = function (blockName, index) {
  24813. this._engine.bindUniformBlock(this._program, blockName, index);
  24814. };
  24815. Effect.prototype.setIntArray = function (uniformName, array) {
  24816. this._valueCache[uniformName] = null;
  24817. this._engine.setIntArray(this.getUniform(uniformName), array);
  24818. return this;
  24819. };
  24820. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24821. this._valueCache[uniformName] = null;
  24822. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24823. return this;
  24824. };
  24825. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24826. this._valueCache[uniformName] = null;
  24827. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24828. return this;
  24829. };
  24830. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24831. this._valueCache[uniformName] = null;
  24832. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24833. return this;
  24834. };
  24835. Effect.prototype.setFloatArray = function (uniformName, array) {
  24836. this._valueCache[uniformName] = null;
  24837. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24838. return this;
  24839. };
  24840. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24841. this._valueCache[uniformName] = null;
  24842. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24843. return this;
  24844. };
  24845. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24846. this._valueCache[uniformName] = null;
  24847. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24848. return this;
  24849. };
  24850. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24851. this._valueCache[uniformName] = null;
  24852. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24853. return this;
  24854. };
  24855. Effect.prototype.setArray = function (uniformName, array) {
  24856. this._valueCache[uniformName] = null;
  24857. this._engine.setArray(this.getUniform(uniformName), array);
  24858. return this;
  24859. };
  24860. Effect.prototype.setArray2 = function (uniformName, array) {
  24861. this._valueCache[uniformName] = null;
  24862. this._engine.setArray2(this.getUniform(uniformName), array);
  24863. return this;
  24864. };
  24865. Effect.prototype.setArray3 = function (uniformName, array) {
  24866. this._valueCache[uniformName] = null;
  24867. this._engine.setArray3(this.getUniform(uniformName), array);
  24868. return this;
  24869. };
  24870. Effect.prototype.setArray4 = function (uniformName, array) {
  24871. this._valueCache[uniformName] = null;
  24872. this._engine.setArray4(this.getUniform(uniformName), array);
  24873. return this;
  24874. };
  24875. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24876. if (!matrices) {
  24877. return;
  24878. }
  24879. this._valueCache[uniformName] = null;
  24880. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24881. return this;
  24882. };
  24883. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24884. if (this._cacheMatrix(uniformName, matrix)) {
  24885. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24886. }
  24887. return this;
  24888. };
  24889. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24890. this._valueCache[uniformName] = null;
  24891. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24892. return this;
  24893. };
  24894. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24895. this._valueCache[uniformName] = null;
  24896. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  24897. return this;
  24898. };
  24899. Effect.prototype.setFloat = function (uniformName, value) {
  24900. var cache = this._valueCache[uniformName];
  24901. if (cache !== undefined && cache === value)
  24902. return this;
  24903. this._valueCache[uniformName] = value;
  24904. this._engine.setFloat(this.getUniform(uniformName), value);
  24905. return this;
  24906. };
  24907. Effect.prototype.setBool = function (uniformName, bool) {
  24908. var cache = this._valueCache[uniformName];
  24909. if (cache !== undefined && cache === bool)
  24910. return this;
  24911. this._valueCache[uniformName] = bool;
  24912. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24913. return this;
  24914. };
  24915. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24916. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24917. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24918. }
  24919. return this;
  24920. };
  24921. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24922. if (this._cacheFloat2(uniformName, x, y)) {
  24923. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24924. }
  24925. return this;
  24926. };
  24927. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24928. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24929. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24930. }
  24931. return this;
  24932. };
  24933. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24934. if (this._cacheFloat3(uniformName, x, y, z)) {
  24935. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24936. }
  24937. return this;
  24938. };
  24939. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24940. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24941. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24942. }
  24943. return this;
  24944. };
  24945. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24946. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24947. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24948. }
  24949. return this;
  24950. };
  24951. Effect.prototype.setColor3 = function (uniformName, color3) {
  24952. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24953. this._engine.setColor3(this.getUniform(uniformName), color3);
  24954. }
  24955. return this;
  24956. };
  24957. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24958. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24959. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24960. }
  24961. return this;
  24962. };
  24963. Effect.ResetCache = function () {
  24964. Effect._baseCache = {};
  24965. };
  24966. Effect._uniqueIdSeed = 0;
  24967. Effect._baseCache = {};
  24968. // Statics
  24969. Effect.ShadersStore = {};
  24970. Effect.IncludesShadersStore = {};
  24971. return Effect;
  24972. }());
  24973. BABYLON.Effect = Effect;
  24974. })(BABYLON || (BABYLON = {}));
  24975. //# sourceMappingURL=babylon.effect.js.map
  24976. var BABYLON;
  24977. (function (BABYLON) {
  24978. var MaterialHelper = (function () {
  24979. function MaterialHelper() {
  24980. }
  24981. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  24982. defines._needUVs = true;
  24983. defines[key] = true;
  24984. if (texture.getTextureMatrix().isIdentity(true)) {
  24985. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  24986. if (texture.coordinatesIndex === 0) {
  24987. defines["MAINUV1"] = true;
  24988. }
  24989. else {
  24990. defines["MAINUV2"] = true;
  24991. }
  24992. }
  24993. else {
  24994. defines[key + "DIRECTUV"] = 0;
  24995. }
  24996. };
  24997. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  24998. var matrix = texture.getTextureMatrix();
  24999. if (!matrix.isIdentity(true)) {
  25000. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  25001. }
  25002. };
  25003. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  25004. if (defines._areMiscDirty) {
  25005. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  25006. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  25007. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  25008. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  25009. }
  25010. };
  25011. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  25012. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  25013. var changed = false;
  25014. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  25015. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  25016. changed = true;
  25017. }
  25018. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  25019. defines["ALPHATEST"] = !defines["ALPHATEST"];
  25020. changed = true;
  25021. }
  25022. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  25023. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  25024. changed = true;
  25025. }
  25026. if (defines["INSTANCES"] !== useInstances) {
  25027. defines["INSTANCES"] = useInstances;
  25028. changed = true;
  25029. }
  25030. if (changed) {
  25031. defines.markAsUnprocessed();
  25032. }
  25033. };
  25034. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  25035. if (useMorphTargets === void 0) { useMorphTargets = false; }
  25036. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  25037. return false;
  25038. }
  25039. defines._normals = defines._needNormals;
  25040. defines._uvs = defines._needUVs;
  25041. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  25042. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25043. defines["TANGENT"] = true;
  25044. }
  25045. if (defines._needUVs) {
  25046. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  25047. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  25048. }
  25049. else {
  25050. defines["UV1"] = false;
  25051. defines["UV2"] = false;
  25052. }
  25053. if (useVertexColor) {
  25054. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  25055. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  25056. }
  25057. if (useBones) {
  25058. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  25059. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  25060. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  25061. }
  25062. else {
  25063. defines["NUM_BONE_INFLUENCERS"] = 0;
  25064. defines["BonesPerMesh"] = 0;
  25065. }
  25066. }
  25067. if (useMorphTargets) {
  25068. if (mesh.morphTargetManager) {
  25069. var manager = mesh.morphTargetManager;
  25070. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  25071. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  25072. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  25073. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  25074. }
  25075. else {
  25076. defines["MORPHTARGETS_TANGENT"] = false;
  25077. defines["MORPHTARGETS_NORMAL"] = false;
  25078. defines["MORPHTARGETS"] = false;
  25079. defines["NUM_MORPH_INFLUENCERS"] = 0;
  25080. }
  25081. }
  25082. return true;
  25083. };
  25084. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  25085. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25086. if (disableLighting === void 0) { disableLighting = false; }
  25087. if (!defines._areLightsDirty) {
  25088. return defines._needNormals;
  25089. }
  25090. var lightIndex = 0;
  25091. var needNormals = false;
  25092. var needRebuild = false;
  25093. var lightmapMode = false;
  25094. var shadowEnabled = false;
  25095. var specularEnabled = false;
  25096. if (scene.lightsEnabled && !disableLighting) {
  25097. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  25098. var light = _a[_i];
  25099. needNormals = true;
  25100. if (defines["LIGHT" + lightIndex] === undefined) {
  25101. needRebuild = true;
  25102. }
  25103. defines["LIGHT" + lightIndex] = true;
  25104. defines["SPOTLIGHT" + lightIndex] = false;
  25105. defines["HEMILIGHT" + lightIndex] = false;
  25106. defines["POINTLIGHT" + lightIndex] = false;
  25107. defines["DIRLIGHT" + lightIndex] = false;
  25108. var type;
  25109. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  25110. type = "SPOTLIGHT" + lightIndex;
  25111. }
  25112. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  25113. type = "HEMILIGHT" + lightIndex;
  25114. }
  25115. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  25116. type = "POINTLIGHT" + lightIndex;
  25117. }
  25118. else {
  25119. type = "DIRLIGHT" + lightIndex;
  25120. }
  25121. defines[type] = true;
  25122. // Specular
  25123. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  25124. specularEnabled = true;
  25125. }
  25126. // Shadows
  25127. defines["SHADOW" + lightIndex] = false;
  25128. defines["SHADOWPCF" + lightIndex] = false;
  25129. defines["SHADOWESM" + lightIndex] = false;
  25130. defines["SHADOWCUBE" + lightIndex] = false;
  25131. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  25132. var shadowGenerator = light.getShadowGenerator();
  25133. if (shadowGenerator) {
  25134. shadowEnabled = true;
  25135. shadowGenerator.prepareDefines(defines, lightIndex);
  25136. }
  25137. }
  25138. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  25139. lightmapMode = true;
  25140. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  25141. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  25142. }
  25143. else {
  25144. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  25145. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  25146. }
  25147. lightIndex++;
  25148. if (lightIndex === maxSimultaneousLights)
  25149. break;
  25150. }
  25151. }
  25152. defines["SPECULARTERM"] = specularEnabled;
  25153. defines["SHADOWS"] = shadowEnabled;
  25154. // Resetting all other lights if any
  25155. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  25156. if (defines["LIGHT" + index] !== undefined) {
  25157. defines["LIGHT" + index] = false;
  25158. defines["HEMILIGHT" + lightIndex] = false;
  25159. defines["POINTLIGHT" + lightIndex] = false;
  25160. defines["DIRLIGHT" + lightIndex] = false;
  25161. defines["SPOTLIGHT" + lightIndex] = false;
  25162. defines["SHADOW" + lightIndex] = false;
  25163. }
  25164. }
  25165. var caps = scene.getEngine().getCaps();
  25166. if (defines["SHADOWFLOAT"] === undefined) {
  25167. needRebuild = true;
  25168. }
  25169. defines["SHADOWFLOAT"] = shadowEnabled &&
  25170. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  25171. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  25172. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  25173. if (needRebuild) {
  25174. defines.rebuild();
  25175. }
  25176. return needNormals;
  25177. };
  25178. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  25179. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25180. var uniformsList, uniformBuffersList, samplersList, defines;
  25181. if (uniformsListOrOptions.uniformsNames) {
  25182. var options = uniformsListOrOptions;
  25183. uniformsList = options.uniformsNames;
  25184. uniformBuffersList = options.uniformBuffersNames;
  25185. samplersList = options.samplers;
  25186. defines = options.defines;
  25187. maxSimultaneousLights = options.maxSimultaneousLights;
  25188. }
  25189. else {
  25190. uniformsList = uniformsListOrOptions;
  25191. }
  25192. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25193. if (!defines["LIGHT" + lightIndex]) {
  25194. break;
  25195. }
  25196. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  25197. if (uniformBuffersList) {
  25198. uniformBuffersList.push("Light" + lightIndex);
  25199. }
  25200. samplersList.push("shadowSampler" + lightIndex);
  25201. }
  25202. if (defines["NUM_MORPH_INFLUENCERS"]) {
  25203. uniformsList.push("morphTargetInfluences");
  25204. }
  25205. };
  25206. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  25207. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25208. if (!defines["SHADOWS"]) {
  25209. return;
  25210. }
  25211. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25212. if (!defines["LIGHT" + lightIndex]) {
  25213. break;
  25214. }
  25215. if (lightIndex > 0) {
  25216. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  25217. }
  25218. if (defines["SHADOW" + lightIndex]) {
  25219. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  25220. }
  25221. if (defines["SHADOWPCF" + lightIndex]) {
  25222. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  25223. }
  25224. if (defines["SHADOWESM" + lightIndex]) {
  25225. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  25226. }
  25227. }
  25228. };
  25229. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  25230. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  25231. if (influencers > 0) {
  25232. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  25233. var manager = mesh.morphTargetManager;
  25234. var normal = manager.supportsNormals && defines["NORMAL"];
  25235. var tangent = manager.supportsTangents && defines["TANGENT"];
  25236. for (var index = 0; index < influencers; index++) {
  25237. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  25238. if (normal) {
  25239. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  25240. }
  25241. if (tangent) {
  25242. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  25243. }
  25244. if (attribs.length > maxAttributesCount) {
  25245. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  25246. }
  25247. }
  25248. }
  25249. };
  25250. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  25251. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  25252. fallbacks.addCPUSkinningFallback(0, mesh);
  25253. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25254. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25255. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  25256. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  25257. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  25258. }
  25259. }
  25260. };
  25261. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  25262. if (defines["INSTANCES"]) {
  25263. attribs.push("world0");
  25264. attribs.push("world1");
  25265. attribs.push("world2");
  25266. attribs.push("world3");
  25267. }
  25268. };
  25269. // Bindings
  25270. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  25271. if (light.shadowEnabled && mesh.receiveShadows) {
  25272. var shadowGenerator = light.getShadowGenerator();
  25273. if (shadowGenerator) {
  25274. shadowGenerator.bindShadowLight(lightIndex, effect);
  25275. }
  25276. }
  25277. };
  25278. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25279. light.transferToEffect(effect, lightIndex + "");
  25280. };
  25281. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  25282. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25283. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  25284. var lightIndex = 0;
  25285. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  25286. var light = _a[_i];
  25287. var scaledIntensity = light.getScaledIntensity();
  25288. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  25289. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25290. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  25291. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  25292. if (defines["SPECULARTERM"]) {
  25293. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  25294. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  25295. }
  25296. // Shadows
  25297. if (scene.shadowsEnabled) {
  25298. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  25299. }
  25300. light._uniformBuffer.update();
  25301. lightIndex++;
  25302. if (lightIndex === maxSimultaneousLights)
  25303. break;
  25304. }
  25305. };
  25306. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25307. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25308. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25309. effect.setColor3("vFogColor", scene.fogColor);
  25310. }
  25311. };
  25312. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25313. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25314. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25315. if (matrices) {
  25316. effect.setMatrices("mBones", matrices);
  25317. }
  25318. }
  25319. };
  25320. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  25321. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  25322. return;
  25323. }
  25324. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  25325. };
  25326. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25327. if (defines["LOGARITHMICDEPTH"]) {
  25328. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25329. }
  25330. };
  25331. MaterialHelper.BindClipPlane = function (effect, scene) {
  25332. if (scene.clipPlane) {
  25333. var clipPlane = scene.clipPlane;
  25334. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25335. }
  25336. };
  25337. return MaterialHelper;
  25338. }());
  25339. BABYLON.MaterialHelper = MaterialHelper;
  25340. })(BABYLON || (BABYLON = {}));
  25341. //# sourceMappingURL=babylon.materialHelper.js.map
  25342. var BABYLON;
  25343. (function (BABYLON) {
  25344. var MaterialDefines = (function () {
  25345. function MaterialDefines() {
  25346. this._isDirty = true;
  25347. this._areLightsDirty = true;
  25348. this._areAttributesDirty = true;
  25349. this._areTexturesDirty = true;
  25350. this._areFresnelDirty = true;
  25351. this._areMiscDirty = true;
  25352. this._areImageProcessingDirty = true;
  25353. this._normals = false;
  25354. this._uvs = false;
  25355. this._needNormals = false;
  25356. this._needUVs = false;
  25357. }
  25358. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  25359. get: function () {
  25360. return this._isDirty;
  25361. },
  25362. enumerable: true,
  25363. configurable: true
  25364. });
  25365. MaterialDefines.prototype.markAsProcessed = function () {
  25366. this._isDirty = false;
  25367. this._areAttributesDirty = false;
  25368. this._areTexturesDirty = false;
  25369. this._areFresnelDirty = false;
  25370. this._areLightsDirty = false;
  25371. this._areMiscDirty = false;
  25372. this._areImageProcessingDirty = false;
  25373. };
  25374. MaterialDefines.prototype.markAsUnprocessed = function () {
  25375. this._isDirty = true;
  25376. };
  25377. MaterialDefines.prototype.markAllAsDirty = function () {
  25378. this._areTexturesDirty = true;
  25379. this._areAttributesDirty = true;
  25380. this._areLightsDirty = true;
  25381. this._areFresnelDirty = true;
  25382. this._areMiscDirty = true;
  25383. this._areImageProcessingDirty = true;
  25384. this._isDirty = true;
  25385. };
  25386. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  25387. this._areImageProcessingDirty = true;
  25388. this._isDirty = true;
  25389. };
  25390. MaterialDefines.prototype.markAsLightDirty = function () {
  25391. this._areLightsDirty = true;
  25392. this._isDirty = true;
  25393. };
  25394. MaterialDefines.prototype.markAsAttributesDirty = function () {
  25395. this._areAttributesDirty = true;
  25396. this._isDirty = true;
  25397. };
  25398. MaterialDefines.prototype.markAsTexturesDirty = function () {
  25399. this._areTexturesDirty = true;
  25400. this._isDirty = true;
  25401. };
  25402. MaterialDefines.prototype.markAsFresnelDirty = function () {
  25403. this._areFresnelDirty = true;
  25404. this._isDirty = true;
  25405. };
  25406. MaterialDefines.prototype.markAsMiscDirty = function () {
  25407. this._areMiscDirty = true;
  25408. this._isDirty = true;
  25409. };
  25410. MaterialDefines.prototype.rebuild = function () {
  25411. if (this._keys) {
  25412. delete this._keys;
  25413. }
  25414. this._keys = [];
  25415. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  25416. var key = _a[_i];
  25417. if (key[0] === "_") {
  25418. continue;
  25419. }
  25420. this._keys.push(key);
  25421. }
  25422. };
  25423. MaterialDefines.prototype.isEqual = function (other) {
  25424. if (this._keys.length !== other._keys.length) {
  25425. return false;
  25426. }
  25427. for (var index = 0; index < this._keys.length; index++) {
  25428. var prop = this._keys[index];
  25429. if (this[prop] !== other[prop]) {
  25430. return false;
  25431. }
  25432. }
  25433. return true;
  25434. };
  25435. MaterialDefines.prototype.cloneTo = function (other) {
  25436. if (this._keys.length !== other._keys.length) {
  25437. other._keys = this._keys.slice(0);
  25438. }
  25439. for (var index = 0; index < this._keys.length; index++) {
  25440. var prop = this._keys[index];
  25441. other[prop] = this[prop];
  25442. }
  25443. };
  25444. MaterialDefines.prototype.reset = function () {
  25445. for (var index = 0; index < this._keys.length; index++) {
  25446. var prop = this._keys[index];
  25447. if (typeof (this[prop]) === "number") {
  25448. this[prop] = 0;
  25449. }
  25450. else {
  25451. this[prop] = false;
  25452. }
  25453. }
  25454. };
  25455. MaterialDefines.prototype.toString = function () {
  25456. var result = "";
  25457. for (var index = 0; index < this._keys.length; index++) {
  25458. var prop = this._keys[index];
  25459. var value = this[prop];
  25460. if (typeof (value) === "number") {
  25461. result += "#define " + prop + " " + this[prop] + "\n";
  25462. }
  25463. else if (value) {
  25464. result += "#define " + prop + "\n";
  25465. }
  25466. }
  25467. return result;
  25468. };
  25469. return MaterialDefines;
  25470. }());
  25471. BABYLON.MaterialDefines = MaterialDefines;
  25472. var Material = (function () {
  25473. function Material(name, scene, doNotAdd) {
  25474. this.checkReadyOnEveryCall = false;
  25475. this.checkReadyOnlyOnce = false;
  25476. this.state = "";
  25477. this.alpha = 1.0;
  25478. this._backFaceCulling = true;
  25479. this.doNotSerialize = false;
  25480. this.storeEffectOnSubMeshes = false;
  25481. /**
  25482. * An event triggered when the material is disposed.
  25483. * @type {BABYLON.Observable}
  25484. */
  25485. this.onDisposeObservable = new BABYLON.Observable();
  25486. /**
  25487. * An event triggered when the material is bound.
  25488. * @type {BABYLON.Observable}
  25489. */
  25490. this.onBindObservable = new BABYLON.Observable();
  25491. /**
  25492. * An event triggered when the material is unbound.
  25493. * @type {BABYLON.Observable}
  25494. */
  25495. this.onUnBindObservable = new BABYLON.Observable();
  25496. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25497. this.needDepthPrePass = false;
  25498. this.disableDepthWrite = false;
  25499. this._fogEnabled = true;
  25500. this.pointSize = 1.0;
  25501. this.zOffset = 0;
  25502. this._wasPreviouslyReady = false;
  25503. this._fillMode = Material.TriangleFillMode;
  25504. this.name = name;
  25505. this.id = name || BABYLON.Tools.RandomId();
  25506. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25507. if (this._scene.useRightHandedSystem) {
  25508. this.sideOrientation = Material.ClockWiseSideOrientation;
  25509. }
  25510. else {
  25511. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25512. }
  25513. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  25514. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  25515. if (!doNotAdd) {
  25516. this._scene.materials.push(this);
  25517. }
  25518. }
  25519. Object.defineProperty(Material, "TriangleFillMode", {
  25520. get: function () {
  25521. return Material._TriangleFillMode;
  25522. },
  25523. enumerable: true,
  25524. configurable: true
  25525. });
  25526. Object.defineProperty(Material, "WireFrameFillMode", {
  25527. get: function () {
  25528. return Material._WireFrameFillMode;
  25529. },
  25530. enumerable: true,
  25531. configurable: true
  25532. });
  25533. Object.defineProperty(Material, "PointFillMode", {
  25534. get: function () {
  25535. return Material._PointFillMode;
  25536. },
  25537. enumerable: true,
  25538. configurable: true
  25539. });
  25540. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25541. get: function () {
  25542. return Material._ClockWiseSideOrientation;
  25543. },
  25544. enumerable: true,
  25545. configurable: true
  25546. });
  25547. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25548. get: function () {
  25549. return Material._CounterClockWiseSideOrientation;
  25550. },
  25551. enumerable: true,
  25552. configurable: true
  25553. });
  25554. Object.defineProperty(Material, "TextureDirtyFlag", {
  25555. get: function () {
  25556. return Material._TextureDirtyFlag;
  25557. },
  25558. enumerable: true,
  25559. configurable: true
  25560. });
  25561. Object.defineProperty(Material, "LightDirtyFlag", {
  25562. get: function () {
  25563. return Material._LightDirtyFlag;
  25564. },
  25565. enumerable: true,
  25566. configurable: true
  25567. });
  25568. Object.defineProperty(Material, "FresnelDirtyFlag", {
  25569. get: function () {
  25570. return Material._FresnelDirtyFlag;
  25571. },
  25572. enumerable: true,
  25573. configurable: true
  25574. });
  25575. Object.defineProperty(Material, "AttributesDirtyFlag", {
  25576. get: function () {
  25577. return Material._AttributesDirtyFlag;
  25578. },
  25579. enumerable: true,
  25580. configurable: true
  25581. });
  25582. Object.defineProperty(Material, "MiscDirtyFlag", {
  25583. get: function () {
  25584. return Material._MiscDirtyFlag;
  25585. },
  25586. enumerable: true,
  25587. configurable: true
  25588. });
  25589. Object.defineProperty(Material.prototype, "backFaceCulling", {
  25590. get: function () {
  25591. return this._backFaceCulling;
  25592. },
  25593. set: function (value) {
  25594. if (this._backFaceCulling === value) {
  25595. return;
  25596. }
  25597. this._backFaceCulling = value;
  25598. this.markAsDirty(Material.TextureDirtyFlag);
  25599. },
  25600. enumerable: true,
  25601. configurable: true
  25602. });
  25603. Object.defineProperty(Material.prototype, "onDispose", {
  25604. set: function (callback) {
  25605. if (this._onDisposeObserver) {
  25606. this.onDisposeObservable.remove(this._onDisposeObserver);
  25607. }
  25608. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25609. },
  25610. enumerable: true,
  25611. configurable: true
  25612. });
  25613. Object.defineProperty(Material.prototype, "onBind", {
  25614. set: function (callback) {
  25615. if (this._onBindObserver) {
  25616. this.onBindObservable.remove(this._onBindObserver);
  25617. }
  25618. this._onBindObserver = this.onBindObservable.add(callback);
  25619. },
  25620. enumerable: true,
  25621. configurable: true
  25622. });
  25623. Object.defineProperty(Material.prototype, "fogEnabled", {
  25624. get: function () {
  25625. return this._fogEnabled;
  25626. },
  25627. set: function (value) {
  25628. if (this._fogEnabled === value) {
  25629. return;
  25630. }
  25631. this._fogEnabled = value;
  25632. this.markAsDirty(Material.MiscDirtyFlag);
  25633. },
  25634. enumerable: true,
  25635. configurable: true
  25636. });
  25637. Object.defineProperty(Material.prototype, "wireframe", {
  25638. get: function () {
  25639. return this._fillMode === Material.WireFrameFillMode;
  25640. },
  25641. set: function (value) {
  25642. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25643. },
  25644. enumerable: true,
  25645. configurable: true
  25646. });
  25647. Object.defineProperty(Material.prototype, "pointsCloud", {
  25648. get: function () {
  25649. return this._fillMode === Material.PointFillMode;
  25650. },
  25651. set: function (value) {
  25652. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  25653. },
  25654. enumerable: true,
  25655. configurable: true
  25656. });
  25657. Object.defineProperty(Material.prototype, "fillMode", {
  25658. get: function () {
  25659. return this._fillMode;
  25660. },
  25661. set: function (value) {
  25662. if (this._fillMode === value) {
  25663. return;
  25664. }
  25665. this._fillMode = value;
  25666. this.markAsDirty(Material.MiscDirtyFlag);
  25667. },
  25668. enumerable: true,
  25669. configurable: true
  25670. });
  25671. /**
  25672. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25673. * subclasses should override adding information pertainent to themselves
  25674. */
  25675. Material.prototype.toString = function (fullDetails) {
  25676. var ret = "Name: " + this.name;
  25677. if (fullDetails) {
  25678. }
  25679. return ret;
  25680. };
  25681. /**
  25682. * Child classes can use it to update shaders
  25683. */
  25684. Material.prototype.getClassName = function () {
  25685. return "Material";
  25686. };
  25687. Object.defineProperty(Material.prototype, "isFrozen", {
  25688. get: function () {
  25689. return this.checkReadyOnlyOnce;
  25690. },
  25691. enumerable: true,
  25692. configurable: true
  25693. });
  25694. Material.prototype.freeze = function () {
  25695. this.checkReadyOnlyOnce = true;
  25696. };
  25697. Material.prototype.unfreeze = function () {
  25698. this.checkReadyOnlyOnce = false;
  25699. };
  25700. Material.prototype.isReady = function (mesh, useInstances) {
  25701. return true;
  25702. };
  25703. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  25704. return false;
  25705. };
  25706. Material.prototype.getEffect = function () {
  25707. return this._effect;
  25708. };
  25709. Material.prototype.getScene = function () {
  25710. return this._scene;
  25711. };
  25712. Material.prototype.needAlphaBlending = function () {
  25713. return (this.alpha < 1.0);
  25714. };
  25715. Material.prototype.needAlphaTesting = function () {
  25716. return false;
  25717. };
  25718. Material.prototype.getAlphaTestTexture = function () {
  25719. return null;
  25720. };
  25721. Material.prototype.markDirty = function () {
  25722. this._wasPreviouslyReady = false;
  25723. };
  25724. Material.prototype._preBind = function (effect) {
  25725. var engine = this._scene.getEngine();
  25726. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  25727. engine.enableEffect(effect ? effect : this._effect);
  25728. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25729. };
  25730. Material.prototype.bind = function (world, mesh) {
  25731. };
  25732. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  25733. };
  25734. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25735. };
  25736. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  25737. sceneUbo.bindToEffect(effect, "Scene");
  25738. };
  25739. Material.prototype.bindView = function (effect) {
  25740. if (!this._useUBO) {
  25741. effect.setMatrix("view", this.getScene().getViewMatrix());
  25742. }
  25743. else {
  25744. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25745. }
  25746. };
  25747. Material.prototype.bindViewProjection = function (effect) {
  25748. if (!this._useUBO) {
  25749. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25750. }
  25751. else {
  25752. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25753. }
  25754. };
  25755. Material.prototype._afterBind = function (mesh) {
  25756. this._scene._cachedMaterial = this;
  25757. if (mesh) {
  25758. this._scene._cachedVisibility = mesh.visibility;
  25759. }
  25760. else {
  25761. this._scene._cachedVisibility = 1;
  25762. }
  25763. this.onBindObservable.notifyObservers(mesh);
  25764. if (this.disableDepthWrite) {
  25765. var engine = this._scene.getEngine();
  25766. this._cachedDepthWriteState = engine.getDepthWrite();
  25767. engine.setDepthWrite(false);
  25768. }
  25769. };
  25770. Material.prototype.unbind = function () {
  25771. this.onUnBindObservable.notifyObservers(this);
  25772. if (this.disableDepthWrite) {
  25773. var engine = this._scene.getEngine();
  25774. engine.setDepthWrite(this._cachedDepthWriteState);
  25775. }
  25776. };
  25777. Material.prototype.getActiveTextures = function () {
  25778. return [];
  25779. };
  25780. Material.prototype.hasTexture = function (texture) {
  25781. return false;
  25782. };
  25783. Material.prototype.clone = function (name) {
  25784. return null;
  25785. };
  25786. Material.prototype.getBindedMeshes = function () {
  25787. var result = new Array();
  25788. for (var index = 0; index < this._scene.meshes.length; index++) {
  25789. var mesh = this._scene.meshes[index];
  25790. if (mesh.material === this) {
  25791. result.push(mesh);
  25792. }
  25793. }
  25794. return result;
  25795. };
  25796. /**
  25797. * Force shader compilation including textures ready check
  25798. */
  25799. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  25800. var _this = this;
  25801. var subMesh = new BABYLON.BaseSubMesh();
  25802. var scene = this.getScene();
  25803. var engine = scene.getEngine();
  25804. var checkReady = function () {
  25805. if (!_this._scene || !_this._scene.getEngine()) {
  25806. return;
  25807. }
  25808. if (subMesh._materialDefines) {
  25809. subMesh._materialDefines._renderId = -1;
  25810. }
  25811. var alphaTestState = engine.getAlphaTesting();
  25812. var clipPlaneState = scene.clipPlane;
  25813. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  25814. if (options && options.clipPlane) {
  25815. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  25816. }
  25817. if (_this.storeEffectOnSubMeshes) {
  25818. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  25819. if (onCompiled) {
  25820. onCompiled(_this);
  25821. }
  25822. }
  25823. else {
  25824. setTimeout(checkReady, 16);
  25825. }
  25826. }
  25827. else {
  25828. if (_this.isReady(mesh)) {
  25829. if (onCompiled) {
  25830. onCompiled(_this);
  25831. }
  25832. }
  25833. else {
  25834. setTimeout(checkReady, 16);
  25835. }
  25836. }
  25837. engine.setAlphaTesting(alphaTestState);
  25838. if (options && options.clipPlane) {
  25839. scene.clipPlane = clipPlaneState;
  25840. }
  25841. };
  25842. checkReady();
  25843. };
  25844. Material.prototype.markAsDirty = function (flag) {
  25845. if (flag & Material.TextureDirtyFlag) {
  25846. this._markAllSubMeshesAsTexturesDirty();
  25847. }
  25848. if (flag & Material.LightDirtyFlag) {
  25849. this._markAllSubMeshesAsLightsDirty();
  25850. }
  25851. if (flag & Material.FresnelDirtyFlag) {
  25852. this._markAllSubMeshesAsFresnelDirty();
  25853. }
  25854. if (flag & Material.AttributesDirtyFlag) {
  25855. this._markAllSubMeshesAsAttributesDirty();
  25856. }
  25857. if (flag & Material.MiscDirtyFlag) {
  25858. this._markAllSubMeshesAsMiscDirty();
  25859. }
  25860. this.getScene().resetCachedMaterial();
  25861. };
  25862. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  25863. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  25864. var mesh = _a[_i];
  25865. if (!mesh.subMeshes) {
  25866. continue;
  25867. }
  25868. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25869. var subMesh = _c[_b];
  25870. if (subMesh.getMaterial() !== this) {
  25871. continue;
  25872. }
  25873. if (!subMesh._materialDefines) {
  25874. continue;
  25875. }
  25876. func(subMesh._materialDefines);
  25877. }
  25878. }
  25879. };
  25880. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  25881. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  25882. };
  25883. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  25884. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  25885. };
  25886. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  25887. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  25888. };
  25889. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  25890. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  25891. };
  25892. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  25893. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  25894. };
  25895. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  25896. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  25897. };
  25898. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25899. // Animations
  25900. this.getScene().stopAnimation(this);
  25901. // Remove from scene
  25902. var index = this._scene.materials.indexOf(this);
  25903. if (index >= 0) {
  25904. this._scene.materials.splice(index, 1);
  25905. }
  25906. // Remove from meshes
  25907. for (index = 0; index < this._scene.meshes.length; index++) {
  25908. var mesh = this._scene.meshes[index];
  25909. if (mesh.material === this) {
  25910. mesh.material = null;
  25911. if (mesh.geometry) {
  25912. var geometry = mesh.geometry;
  25913. if (this.storeEffectOnSubMeshes) {
  25914. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  25915. var subMesh = _a[_i];
  25916. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  25917. }
  25918. }
  25919. else {
  25920. geometry._releaseVertexArrayObject(this._effect);
  25921. }
  25922. }
  25923. }
  25924. }
  25925. this._uniformBuffer.dispose();
  25926. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  25927. if (forceDisposeEffect && this._effect) {
  25928. if (this.storeEffectOnSubMeshes) {
  25929. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25930. var subMesh = _c[_b];
  25931. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  25932. }
  25933. }
  25934. else {
  25935. this._scene.getEngine()._releaseEffect(this._effect);
  25936. }
  25937. this._effect = null;
  25938. }
  25939. // Callback
  25940. this.onDisposeObservable.notifyObservers(this);
  25941. this.onDisposeObservable.clear();
  25942. this.onBindObservable.clear();
  25943. this.onUnBindObservable.clear();
  25944. };
  25945. Material.prototype.serialize = function () {
  25946. return BABYLON.SerializationHelper.Serialize(this);
  25947. };
  25948. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  25949. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  25950. multiMaterial.id = parsedMultiMaterial.id;
  25951. if (BABYLON.Tags) {
  25952. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  25953. }
  25954. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  25955. var subMatId = parsedMultiMaterial.materials[matIndex];
  25956. if (subMatId) {
  25957. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  25958. }
  25959. else {
  25960. multiMaterial.subMaterials.push(null);
  25961. }
  25962. }
  25963. return multiMaterial;
  25964. };
  25965. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  25966. if (!parsedMaterial.customType) {
  25967. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  25968. }
  25969. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  25970. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  25971. if (!BABYLON.LegacyPBRMaterial) {
  25972. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  25973. return;
  25974. }
  25975. }
  25976. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  25977. return materialType.Parse(parsedMaterial, scene, rootUrl);
  25978. ;
  25979. };
  25980. Material._TriangleFillMode = 0;
  25981. Material._WireFrameFillMode = 1;
  25982. Material._PointFillMode = 2;
  25983. Material._ClockWiseSideOrientation = 0;
  25984. Material._CounterClockWiseSideOrientation = 1;
  25985. Material._TextureDirtyFlag = 1;
  25986. Material._LightDirtyFlag = 2;
  25987. Material._FresnelDirtyFlag = 4;
  25988. Material._AttributesDirtyFlag = 8;
  25989. Material._MiscDirtyFlag = 16;
  25990. __decorate([
  25991. BABYLON.serialize()
  25992. ], Material.prototype, "id", void 0);
  25993. __decorate([
  25994. BABYLON.serialize()
  25995. ], Material.prototype, "name", void 0);
  25996. __decorate([
  25997. BABYLON.serialize()
  25998. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  25999. __decorate([
  26000. BABYLON.serialize()
  26001. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  26002. __decorate([
  26003. BABYLON.serialize()
  26004. ], Material.prototype, "state", void 0);
  26005. __decorate([
  26006. BABYLON.serialize()
  26007. ], Material.prototype, "alpha", void 0);
  26008. __decorate([
  26009. BABYLON.serialize("backFaceCulling")
  26010. ], Material.prototype, "_backFaceCulling", void 0);
  26011. __decorate([
  26012. BABYLON.serialize()
  26013. ], Material.prototype, "sideOrientation", void 0);
  26014. __decorate([
  26015. BABYLON.serialize()
  26016. ], Material.prototype, "alphaMode", void 0);
  26017. __decorate([
  26018. BABYLON.serialize()
  26019. ], Material.prototype, "needDepthPrePass", void 0);
  26020. __decorate([
  26021. BABYLON.serialize()
  26022. ], Material.prototype, "disableDepthWrite", void 0);
  26023. __decorate([
  26024. BABYLON.serialize("fogEnabled")
  26025. ], Material.prototype, "_fogEnabled", void 0);
  26026. __decorate([
  26027. BABYLON.serialize()
  26028. ], Material.prototype, "pointSize", void 0);
  26029. __decorate([
  26030. BABYLON.serialize()
  26031. ], Material.prototype, "zOffset", void 0);
  26032. __decorate([
  26033. BABYLON.serialize()
  26034. ], Material.prototype, "wireframe", null);
  26035. __decorate([
  26036. BABYLON.serialize()
  26037. ], Material.prototype, "pointsCloud", null);
  26038. __decorate([
  26039. BABYLON.serialize()
  26040. ], Material.prototype, "fillMode", null);
  26041. return Material;
  26042. }());
  26043. BABYLON.Material = Material;
  26044. })(BABYLON || (BABYLON = {}));
  26045. //# sourceMappingURL=babylon.material.js.map
  26046. var BABYLON;
  26047. (function (BABYLON) {
  26048. var UniformBuffer = (function () {
  26049. /**
  26050. * Uniform buffer objects.
  26051. *
  26052. * Handles blocks of uniform on the GPU.
  26053. *
  26054. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  26055. *
  26056. * For more information, please refer to :
  26057. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  26058. */
  26059. function UniformBuffer(engine, data, dynamic) {
  26060. this._engine = engine;
  26061. this._noUBO = !engine.supportsUniformBuffers;
  26062. this._dynamic = dynamic;
  26063. this._data = data || [];
  26064. this._uniformLocations = {};
  26065. this._uniformSizes = {};
  26066. this._uniformLocationPointer = 0;
  26067. this._needSync = false;
  26068. if (this._noUBO) {
  26069. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  26070. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  26071. this.updateFloat = this._updateFloatForEffect;
  26072. this.updateFloat2 = this._updateFloat2ForEffect;
  26073. this.updateFloat3 = this._updateFloat3ForEffect;
  26074. this.updateFloat4 = this._updateFloat4ForEffect;
  26075. this.updateMatrix = this._updateMatrixForEffect;
  26076. this.updateVector3 = this._updateVector3ForEffect;
  26077. this.updateVector4 = this._updateVector4ForEffect;
  26078. this.updateColor3 = this._updateColor3ForEffect;
  26079. this.updateColor4 = this._updateColor4ForEffect;
  26080. }
  26081. else {
  26082. this._engine._uniformBuffers.push(this);
  26083. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  26084. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  26085. this.updateFloat = this._updateFloatForUniform;
  26086. this.updateFloat2 = this._updateFloat2ForUniform;
  26087. this.updateFloat3 = this._updateFloat3ForUniform;
  26088. this.updateFloat4 = this._updateFloat4ForUniform;
  26089. this.updateMatrix = this._updateMatrixForUniform;
  26090. this.updateVector3 = this._updateVector3ForUniform;
  26091. this.updateVector4 = this._updateVector4ForUniform;
  26092. this.updateColor3 = this._updateColor3ForUniform;
  26093. this.updateColor4 = this._updateColor4ForUniform;
  26094. }
  26095. }
  26096. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  26097. // Properties
  26098. /**
  26099. * Indicates if the buffer is using the WebGL2 UBO implementation,
  26100. * or just falling back on setUniformXXX calls.
  26101. */
  26102. get: function () {
  26103. return !this._noUBO;
  26104. },
  26105. enumerable: true,
  26106. configurable: true
  26107. });
  26108. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  26109. /**
  26110. * Indicates if the WebGL underlying uniform buffer is in sync
  26111. * with the javascript cache data.
  26112. */
  26113. get: function () {
  26114. return !this._needSync;
  26115. },
  26116. enumerable: true,
  26117. configurable: true
  26118. });
  26119. /**
  26120. * Indicates if the WebGL underlying uniform buffer is dynamic.
  26121. * Also, a dynamic UniformBuffer will disable cache verification and always
  26122. * update the underlying WebGL uniform buffer to the GPU.
  26123. */
  26124. UniformBuffer.prototype.isDynamic = function () {
  26125. return this._dynamic;
  26126. };
  26127. /**
  26128. * The data cache on JS side.
  26129. */
  26130. UniformBuffer.prototype.getData = function () {
  26131. return this._bufferData;
  26132. };
  26133. /**
  26134. * The underlying WebGL Uniform buffer.
  26135. */
  26136. UniformBuffer.prototype.getBuffer = function () {
  26137. return this._buffer;
  26138. };
  26139. /**
  26140. * std140 layout specifies how to align data within an UBO structure.
  26141. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  26142. * for specs.
  26143. */
  26144. UniformBuffer.prototype._fillAlignment = function (size) {
  26145. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  26146. // and 4x4 matrices
  26147. // TODO : change if other types are used
  26148. var alignment;
  26149. if (size <= 2) {
  26150. alignment = size;
  26151. }
  26152. else {
  26153. alignment = 4;
  26154. }
  26155. if ((this._uniformLocationPointer % alignment) !== 0) {
  26156. var oldPointer = this._uniformLocationPointer;
  26157. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  26158. var diff = this._uniformLocationPointer - oldPointer;
  26159. for (var i = 0; i < diff; i++) {
  26160. this._data.push(0);
  26161. }
  26162. }
  26163. };
  26164. /**
  26165. * Adds an uniform in the buffer.
  26166. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  26167. * for the layout to be correct !
  26168. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26169. * @param {number|number[]} size Data size, or data directly.
  26170. */
  26171. UniformBuffer.prototype.addUniform = function (name, size) {
  26172. if (this._noUBO) {
  26173. return;
  26174. }
  26175. if (this._uniformLocations[name] !== undefined) {
  26176. // Already existing uniform
  26177. return;
  26178. }
  26179. // This function must be called in the order of the shader layout !
  26180. // size can be the size of the uniform, or data directly
  26181. var data;
  26182. if (size instanceof Array) {
  26183. data = size;
  26184. size = data.length;
  26185. }
  26186. else {
  26187. size = size;
  26188. data = [];
  26189. // Fill with zeros
  26190. for (var i = 0; i < size; i++) {
  26191. data.push(0);
  26192. }
  26193. }
  26194. this._fillAlignment(size);
  26195. this._uniformSizes[name] = size;
  26196. this._uniformLocations[name] = this._uniformLocationPointer;
  26197. this._uniformLocationPointer += size;
  26198. for (var i = 0; i < size; i++) {
  26199. this._data.push(data[i]);
  26200. }
  26201. this._needSync = true;
  26202. };
  26203. /**
  26204. * Wrapper for addUniform.
  26205. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26206. * @param {Matrix} mat A 4x4 matrix.
  26207. */
  26208. UniformBuffer.prototype.addMatrix = function (name, mat) {
  26209. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  26210. };
  26211. /**
  26212. * Wrapper for addUniform.
  26213. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26214. * @param {number} x
  26215. * @param {number} y
  26216. */
  26217. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  26218. var temp = [x, y];
  26219. this.addUniform(name, temp);
  26220. };
  26221. /**
  26222. * Wrapper for addUniform.
  26223. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26224. * @param {number} x
  26225. * @param {number} y
  26226. * @param {number} z
  26227. */
  26228. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  26229. var temp = [x, y, z];
  26230. this.addUniform(name, temp);
  26231. };
  26232. /**
  26233. * Wrapper for addUniform.
  26234. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26235. * @param {Color3} color
  26236. */
  26237. UniformBuffer.prototype.addColor3 = function (name, color) {
  26238. var temp = [];
  26239. color.toArray(temp);
  26240. this.addUniform(name, temp);
  26241. };
  26242. /**
  26243. * Wrapper for addUniform.
  26244. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26245. * @param {Color3} color
  26246. * @param {number} alpha
  26247. */
  26248. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  26249. var temp = [];
  26250. color.toArray(temp);
  26251. temp.push(alpha);
  26252. this.addUniform(name, temp);
  26253. };
  26254. /**
  26255. * Wrapper for addUniform.
  26256. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26257. * @param {Vector3} vector
  26258. */
  26259. UniformBuffer.prototype.addVector3 = function (name, vector) {
  26260. var temp = [];
  26261. vector.toArray(temp);
  26262. this.addUniform(name, temp);
  26263. };
  26264. /**
  26265. * Wrapper for addUniform.
  26266. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26267. */
  26268. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  26269. this.addUniform(name, 12);
  26270. };
  26271. /**
  26272. * Wrapper for addUniform.
  26273. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26274. */
  26275. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  26276. this.addUniform(name, 8);
  26277. };
  26278. /**
  26279. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  26280. */
  26281. UniformBuffer.prototype.create = function () {
  26282. if (this._noUBO) {
  26283. return;
  26284. }
  26285. if (this._buffer) {
  26286. return; // nothing to do
  26287. }
  26288. // See spec, alignment must be filled as a vec4
  26289. this._fillAlignment(4);
  26290. this._bufferData = new Float32Array(this._data);
  26291. this._rebuild();
  26292. this._needSync = true;
  26293. };
  26294. UniformBuffer.prototype._rebuild = function () {
  26295. if (this._noUBO) {
  26296. return;
  26297. }
  26298. if (this._dynamic) {
  26299. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  26300. }
  26301. else {
  26302. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  26303. }
  26304. };
  26305. /**
  26306. * Updates the WebGL Uniform Buffer on the GPU.
  26307. * If the `dynamic` flag is set to true, no cache comparison is done.
  26308. * Otherwise, the buffer will be updated only if the cache differs.
  26309. */
  26310. UniformBuffer.prototype.update = function () {
  26311. if (!this._buffer) {
  26312. this.create();
  26313. return;
  26314. }
  26315. if (!this._dynamic && !this._needSync) {
  26316. return;
  26317. }
  26318. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  26319. this._needSync = false;
  26320. };
  26321. /**
  26322. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  26323. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26324. * @param {number[]|Float32Array} data Flattened data
  26325. * @param {number} size Size of the data.
  26326. */
  26327. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  26328. var location = this._uniformLocations[uniformName];
  26329. if (location === undefined) {
  26330. if (this._buffer) {
  26331. // Cannot add an uniform if the buffer is already created
  26332. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  26333. return;
  26334. }
  26335. this.addUniform(uniformName, size);
  26336. location = this._uniformLocations[uniformName];
  26337. }
  26338. if (!this._buffer) {
  26339. this.create();
  26340. }
  26341. if (!this._dynamic) {
  26342. // Cache for static uniform buffers
  26343. var changed = false;
  26344. for (var i = 0; i < size; i++) {
  26345. if (this._bufferData[location + i] !== data[i]) {
  26346. changed = true;
  26347. this._bufferData[location + i] = data[i];
  26348. }
  26349. }
  26350. this._needSync = this._needSync || changed;
  26351. }
  26352. else {
  26353. // No cache for dynamic
  26354. for (var i = 0; i < size; i++) {
  26355. this._bufferData[location + i] = data[i];
  26356. }
  26357. }
  26358. };
  26359. // Update methods
  26360. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  26361. // To match std140, matrix must be realigned
  26362. for (var i = 0; i < 3; i++) {
  26363. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  26364. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  26365. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  26366. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26367. }
  26368. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  26369. };
  26370. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  26371. this._currentEffect.setMatrix3x3(name, matrix);
  26372. };
  26373. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  26374. this._currentEffect.setMatrix2x2(name, matrix);
  26375. };
  26376. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  26377. // To match std140, matrix must be realigned
  26378. for (var i = 0; i < 2; i++) {
  26379. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  26380. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  26381. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  26382. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26383. }
  26384. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  26385. };
  26386. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  26387. this._currentEffect.setFloat(name, x);
  26388. };
  26389. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  26390. UniformBuffer._tempBuffer[0] = x;
  26391. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  26392. };
  26393. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  26394. if (suffix === void 0) { suffix = ""; }
  26395. this._currentEffect.setFloat2(name + suffix, x, y);
  26396. };
  26397. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  26398. if (suffix === void 0) { suffix = ""; }
  26399. UniformBuffer._tempBuffer[0] = x;
  26400. UniformBuffer._tempBuffer[1] = y;
  26401. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  26402. };
  26403. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  26404. if (suffix === void 0) { suffix = ""; }
  26405. this._currentEffect.setFloat3(name + suffix, x, y, z);
  26406. };
  26407. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  26408. if (suffix === void 0) { suffix = ""; }
  26409. UniformBuffer._tempBuffer[0] = x;
  26410. UniformBuffer._tempBuffer[1] = y;
  26411. UniformBuffer._tempBuffer[2] = z;
  26412. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26413. };
  26414. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  26415. if (suffix === void 0) { suffix = ""; }
  26416. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  26417. };
  26418. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  26419. if (suffix === void 0) { suffix = ""; }
  26420. UniformBuffer._tempBuffer[0] = x;
  26421. UniformBuffer._tempBuffer[1] = y;
  26422. UniformBuffer._tempBuffer[2] = z;
  26423. UniformBuffer._tempBuffer[3] = w;
  26424. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26425. };
  26426. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  26427. this._currentEffect.setMatrix(name, mat);
  26428. };
  26429. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  26430. this.updateUniform(name, mat.toArray(), 16);
  26431. };
  26432. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  26433. this._currentEffect.setVector3(name, vector);
  26434. };
  26435. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  26436. vector.toArray(UniformBuffer._tempBuffer);
  26437. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26438. };
  26439. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  26440. this._currentEffect.setVector4(name, vector);
  26441. };
  26442. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  26443. vector.toArray(UniformBuffer._tempBuffer);
  26444. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26445. };
  26446. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  26447. if (suffix === void 0) { suffix = ""; }
  26448. this._currentEffect.setColor3(name + suffix, color);
  26449. };
  26450. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  26451. if (suffix === void 0) { suffix = ""; }
  26452. color.toArray(UniformBuffer._tempBuffer);
  26453. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26454. };
  26455. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  26456. if (suffix === void 0) { suffix = ""; }
  26457. this._currentEffect.setColor4(name + suffix, color, alpha);
  26458. };
  26459. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  26460. if (suffix === void 0) { suffix = ""; }
  26461. color.toArray(UniformBuffer._tempBuffer);
  26462. UniformBuffer._tempBuffer[3] = alpha;
  26463. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26464. };
  26465. /**
  26466. * Sets a sampler uniform on the effect.
  26467. * @param {string} name Name of the sampler.
  26468. * @param {Texture} texture
  26469. */
  26470. UniformBuffer.prototype.setTexture = function (name, texture) {
  26471. this._currentEffect.setTexture(name, texture);
  26472. };
  26473. /**
  26474. * Directly updates the value of the uniform in the cache AND on the GPU.
  26475. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26476. * @param {number[]|Float32Array} data Flattened data
  26477. */
  26478. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  26479. this.updateUniform(uniformName, data, data.length);
  26480. this.update();
  26481. };
  26482. /**
  26483. * Binds this uniform buffer to an effect.
  26484. * @param {Effect} effect
  26485. * @param {string} name Name of the uniform block in the shader.
  26486. */
  26487. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  26488. this._currentEffect = effect;
  26489. if (this._noUBO) {
  26490. return;
  26491. }
  26492. effect.bindUniformBuffer(this._buffer, name);
  26493. };
  26494. /**
  26495. * Disposes the uniform buffer.
  26496. */
  26497. UniformBuffer.prototype.dispose = function () {
  26498. if (this._noUBO) {
  26499. return;
  26500. }
  26501. var index = this._engine._uniformBuffers.indexOf(this);
  26502. if (index !== -1) {
  26503. this._engine._uniformBuffers.splice(index, 1);
  26504. }
  26505. if (!this._buffer) {
  26506. return;
  26507. }
  26508. if (this._engine._releaseBuffer(this._buffer)) {
  26509. this._buffer = null;
  26510. }
  26511. };
  26512. // Pool for avoiding memory leaks
  26513. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  26514. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  26515. return UniformBuffer;
  26516. }());
  26517. BABYLON.UniformBuffer = UniformBuffer;
  26518. })(BABYLON || (BABYLON = {}));
  26519. //# sourceMappingURL=babylon.uniformBuffer.js.map
  26520. var BABYLON;
  26521. (function (BABYLON) {
  26522. var PushMaterial = (function (_super) {
  26523. __extends(PushMaterial, _super);
  26524. function PushMaterial(name, scene) {
  26525. var _this = _super.call(this, name, scene) || this;
  26526. _this.storeEffectOnSubMeshes = true;
  26527. return _this;
  26528. }
  26529. PushMaterial.prototype.getEffect = function () {
  26530. return this._activeEffect;
  26531. };
  26532. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  26533. if (!mesh) {
  26534. return false;
  26535. }
  26536. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26537. return true;
  26538. }
  26539. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  26540. };
  26541. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26542. this._activeEffect.setMatrix("world", world);
  26543. };
  26544. PushMaterial.prototype.bind = function (world, mesh) {
  26545. if (!mesh) {
  26546. return;
  26547. }
  26548. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  26549. };
  26550. PushMaterial.prototype._afterBind = function (mesh, effect) {
  26551. _super.prototype._afterBind.call(this, mesh);
  26552. this.getScene()._cachedEffect = effect;
  26553. };
  26554. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  26555. if (visibility === void 0) { visibility = 1; }
  26556. return scene.isCachedMaterialInvalid(this, effect, visibility);
  26557. };
  26558. return PushMaterial;
  26559. }(BABYLON.Material));
  26560. BABYLON.PushMaterial = PushMaterial;
  26561. })(BABYLON || (BABYLON = {}));
  26562. //# sourceMappingURL=babylon.pushMaterial.js.map
  26563. var BABYLON;
  26564. (function (BABYLON) {
  26565. var VertexData = (function () {
  26566. function VertexData() {
  26567. }
  26568. VertexData.prototype.set = function (data, kind) {
  26569. switch (kind) {
  26570. case BABYLON.VertexBuffer.PositionKind:
  26571. this.positions = data;
  26572. break;
  26573. case BABYLON.VertexBuffer.NormalKind:
  26574. this.normals = data;
  26575. break;
  26576. case BABYLON.VertexBuffer.TangentKind:
  26577. this.tangents = data;
  26578. break;
  26579. case BABYLON.VertexBuffer.UVKind:
  26580. this.uvs = data;
  26581. break;
  26582. case BABYLON.VertexBuffer.UV2Kind:
  26583. this.uvs2 = data;
  26584. break;
  26585. case BABYLON.VertexBuffer.UV3Kind:
  26586. this.uvs3 = data;
  26587. break;
  26588. case BABYLON.VertexBuffer.UV4Kind:
  26589. this.uvs4 = data;
  26590. break;
  26591. case BABYLON.VertexBuffer.UV5Kind:
  26592. this.uvs5 = data;
  26593. break;
  26594. case BABYLON.VertexBuffer.UV6Kind:
  26595. this.uvs6 = data;
  26596. break;
  26597. case BABYLON.VertexBuffer.ColorKind:
  26598. this.colors = data;
  26599. break;
  26600. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26601. this.matricesIndices = data;
  26602. break;
  26603. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26604. this.matricesWeights = data;
  26605. break;
  26606. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  26607. this.matricesIndicesExtra = data;
  26608. break;
  26609. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  26610. this.matricesWeightsExtra = data;
  26611. break;
  26612. }
  26613. };
  26614. /**
  26615. * Associates the vertexData to the passed Mesh.
  26616. * Sets it as updatable or not (default `false`).
  26617. * Returns the VertexData.
  26618. */
  26619. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26620. this._applyTo(mesh, updatable);
  26621. return this;
  26622. };
  26623. /**
  26624. * Associates the vertexData to the passed Geometry.
  26625. * Sets it as updatable or not (default `false`).
  26626. * Returns the VertexData.
  26627. */
  26628. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26629. this._applyTo(geometry, updatable);
  26630. return this;
  26631. };
  26632. /**
  26633. * Updates the associated mesh.
  26634. * Returns the VertexData.
  26635. */
  26636. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  26637. this._update(mesh);
  26638. return this;
  26639. };
  26640. /**
  26641. * Updates the associated geometry.
  26642. * Returns the VertexData.
  26643. */
  26644. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  26645. this._update(geometry);
  26646. return this;
  26647. };
  26648. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  26649. if (this.positions) {
  26650. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  26651. }
  26652. if (this.normals) {
  26653. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  26654. }
  26655. if (this.tangents) {
  26656. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  26657. }
  26658. if (this.uvs) {
  26659. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  26660. }
  26661. if (this.uvs2) {
  26662. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  26663. }
  26664. if (this.uvs3) {
  26665. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  26666. }
  26667. if (this.uvs4) {
  26668. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  26669. }
  26670. if (this.uvs5) {
  26671. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  26672. }
  26673. if (this.uvs6) {
  26674. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  26675. }
  26676. if (this.colors) {
  26677. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  26678. }
  26679. if (this.matricesIndices) {
  26680. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  26681. }
  26682. if (this.matricesWeights) {
  26683. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  26684. }
  26685. if (this.matricesIndicesExtra) {
  26686. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  26687. }
  26688. if (this.matricesWeightsExtra) {
  26689. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  26690. }
  26691. if (this.indices) {
  26692. meshOrGeometry.setIndices(this.indices);
  26693. }
  26694. return this;
  26695. };
  26696. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  26697. if (this.positions) {
  26698. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  26699. }
  26700. if (this.normals) {
  26701. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  26702. }
  26703. if (this.tangents) {
  26704. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  26705. }
  26706. if (this.uvs) {
  26707. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  26708. }
  26709. if (this.uvs2) {
  26710. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26711. }
  26712. if (this.uvs3) {
  26713. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26714. }
  26715. if (this.uvs4) {
  26716. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26717. }
  26718. if (this.uvs5) {
  26719. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26720. }
  26721. if (this.uvs6) {
  26722. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26723. }
  26724. if (this.colors) {
  26725. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26726. }
  26727. if (this.matricesIndices) {
  26728. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26729. }
  26730. if (this.matricesWeights) {
  26731. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26732. }
  26733. if (this.matricesIndicesExtra) {
  26734. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  26735. }
  26736. if (this.matricesWeightsExtra) {
  26737. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  26738. }
  26739. if (this.indices) {
  26740. meshOrGeometry.setIndices(this.indices);
  26741. }
  26742. return this;
  26743. };
  26744. /**
  26745. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  26746. * Returns the VertexData.
  26747. */
  26748. VertexData.prototype.transform = function (matrix) {
  26749. var transformed = BABYLON.Vector3.Zero();
  26750. var index;
  26751. if (this.positions) {
  26752. var position = BABYLON.Vector3.Zero();
  26753. for (index = 0; index < this.positions.length; index += 3) {
  26754. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26755. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26756. this.positions[index] = transformed.x;
  26757. this.positions[index + 1] = transformed.y;
  26758. this.positions[index + 2] = transformed.z;
  26759. }
  26760. }
  26761. if (this.normals) {
  26762. var normal = BABYLON.Vector3.Zero();
  26763. for (index = 0; index < this.normals.length; index += 3) {
  26764. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26765. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26766. this.normals[index] = transformed.x;
  26767. this.normals[index + 1] = transformed.y;
  26768. this.normals[index + 2] = transformed.z;
  26769. }
  26770. }
  26771. if (this.tangents) {
  26772. var tangent = BABYLON.Vector4.Zero();
  26773. var tangentTransformed = BABYLON.Vector4.Zero();
  26774. for (index = 0; index < this.tangents.length; index += 4) {
  26775. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  26776. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  26777. this.tangents[index] = tangentTransformed.x;
  26778. this.tangents[index + 1] = tangentTransformed.y;
  26779. this.tangents[index + 2] = tangentTransformed.z;
  26780. this.tangents[index + 3] = tangentTransformed.w;
  26781. }
  26782. }
  26783. return this;
  26784. };
  26785. /**
  26786. * Merges the passed VertexData into the current one.
  26787. * Returns the modified VertexData.
  26788. */
  26789. VertexData.prototype.merge = function (other) {
  26790. if (other.indices) {
  26791. if (!this.indices) {
  26792. this.indices = [];
  26793. }
  26794. var offset = this.positions ? this.positions.length / 3 : 0;
  26795. for (var index = 0; index < other.indices.length; index++) {
  26796. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  26797. this.indices.push(other.indices[index] + offset);
  26798. }
  26799. }
  26800. this.positions = this._mergeElement(this.positions, other.positions);
  26801. this.normals = this._mergeElement(this.normals, other.normals);
  26802. this.tangents = this._mergeElement(this.tangents, other.tangents);
  26803. this.uvs = this._mergeElement(this.uvs, other.uvs);
  26804. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  26805. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  26806. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  26807. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  26808. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  26809. this.colors = this._mergeElement(this.colors, other.colors);
  26810. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  26811. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  26812. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  26813. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  26814. return this;
  26815. };
  26816. VertexData.prototype._mergeElement = function (source, other) {
  26817. if (!other)
  26818. return source;
  26819. if (!source)
  26820. return other;
  26821. var len = other.length + source.length;
  26822. var isSrcTypedArray = source instanceof Float32Array;
  26823. var isOthTypedArray = other instanceof Float32Array;
  26824. // use non-loop method when the source is Float32Array
  26825. if (isSrcTypedArray) {
  26826. var ret32 = new Float32Array(len);
  26827. ret32.set(source);
  26828. ret32.set(other, source.length);
  26829. return ret32;
  26830. // source is number[], when other is also use concat
  26831. }
  26832. else if (!isOthTypedArray) {
  26833. return source.concat(other);
  26834. // source is a number[], but other is a Float32Array, loop required
  26835. }
  26836. else {
  26837. var ret = source.slice(0); // copy source to a separate array
  26838. for (var i = 0, len = other.length; i < len; i++) {
  26839. ret.push(other[i]);
  26840. }
  26841. return ret;
  26842. }
  26843. };
  26844. /**
  26845. * Serializes the VertexData.
  26846. * Returns a serialized object.
  26847. */
  26848. VertexData.prototype.serialize = function () {
  26849. var serializationObject = this.serialize();
  26850. if (this.positions) {
  26851. serializationObject.positions = this.positions;
  26852. }
  26853. if (this.normals) {
  26854. serializationObject.normals = this.normals;
  26855. }
  26856. if (this.tangents) {
  26857. serializationObject.tangents = this.tangents;
  26858. }
  26859. if (this.uvs) {
  26860. serializationObject.uvs = this.uvs;
  26861. }
  26862. if (this.uvs2) {
  26863. serializationObject.uvs2 = this.uvs2;
  26864. }
  26865. if (this.uvs3) {
  26866. serializationObject.uvs3 = this.uvs3;
  26867. }
  26868. if (this.uvs4) {
  26869. serializationObject.uvs4 = this.uvs4;
  26870. }
  26871. if (this.uvs5) {
  26872. serializationObject.uvs5 = this.uvs5;
  26873. }
  26874. if (this.uvs6) {
  26875. serializationObject.uvs6 = this.uvs6;
  26876. }
  26877. if (this.colors) {
  26878. serializationObject.colors = this.colors;
  26879. }
  26880. if (this.matricesIndices) {
  26881. serializationObject.matricesIndices = this.matricesIndices;
  26882. serializationObject.matricesIndices._isExpanded = true;
  26883. }
  26884. if (this.matricesWeights) {
  26885. serializationObject.matricesWeights = this.matricesWeights;
  26886. }
  26887. if (this.matricesIndicesExtra) {
  26888. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  26889. serializationObject.matricesIndicesExtra._isExpanded = true;
  26890. }
  26891. if (this.matricesWeightsExtra) {
  26892. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  26893. }
  26894. serializationObject.indices = this.indices;
  26895. return serializationObject;
  26896. };
  26897. // Statics
  26898. /**
  26899. * Returns the object VertexData associated to the passed mesh.
  26900. */
  26901. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  26902. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  26903. };
  26904. /**
  26905. * Returns the object VertexData associated to the passed geometry.
  26906. */
  26907. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  26908. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  26909. };
  26910. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  26911. var result = new VertexData();
  26912. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26913. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  26914. }
  26915. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26916. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  26917. }
  26918. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26919. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  26920. }
  26921. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26922. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  26923. }
  26924. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26925. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  26926. }
  26927. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26928. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  26929. }
  26930. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26931. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  26932. }
  26933. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26934. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  26935. }
  26936. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26937. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  26938. }
  26939. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26940. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  26941. }
  26942. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26943. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  26944. }
  26945. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26946. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  26947. }
  26948. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  26949. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  26950. }
  26951. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  26952. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  26953. }
  26954. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26955. return result;
  26956. };
  26957. /**
  26958. * Creates the vertexData of the Ribbon.
  26959. */
  26960. VertexData.CreateRibbon = function (options) {
  26961. var pathArray = options.pathArray;
  26962. var closeArray = options.closeArray || false;
  26963. var closePath = options.closePath || false;
  26964. var invertUV = options.invertUV || false;
  26965. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26966. var offset = options.offset || defaultOffset;
  26967. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26968. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26969. var customUV = options.uvs;
  26970. var customColors = options.colors;
  26971. var positions = [];
  26972. var indices = [];
  26973. var normals = [];
  26974. var uvs = [];
  26975. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26976. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26977. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26978. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26979. var minlg; // minimal length among all paths from pathArray
  26980. var lg = []; // array of path lengths : nb of vertex per path
  26981. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26982. var p; // path iterator
  26983. var i; // point iterator
  26984. var j; // point iterator
  26985. // if single path in pathArray
  26986. if (pathArray.length < 2) {
  26987. var ar1 = [];
  26988. var ar2 = [];
  26989. for (i = 0; i < pathArray[0].length - offset; i++) {
  26990. ar1.push(pathArray[0][i]);
  26991. ar2.push(pathArray[0][i + offset]);
  26992. }
  26993. pathArray = [ar1, ar2];
  26994. }
  26995. // positions and horizontal distances (u)
  26996. var idc = 0;
  26997. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  26998. var path;
  26999. var l;
  27000. minlg = pathArray[0].length;
  27001. var vectlg;
  27002. var dist;
  27003. for (p = 0; p < pathArray.length; p++) {
  27004. uTotalDistance[p] = 0;
  27005. us[p] = [0];
  27006. path = pathArray[p];
  27007. l = path.length;
  27008. minlg = (minlg < l) ? minlg : l;
  27009. j = 0;
  27010. while (j < l) {
  27011. positions.push(path[j].x, path[j].y, path[j].z);
  27012. if (j > 0) {
  27013. vectlg = path[j].subtract(path[j - 1]).length();
  27014. dist = vectlg + uTotalDistance[p];
  27015. us[p].push(dist);
  27016. uTotalDistance[p] = dist;
  27017. }
  27018. j++;
  27019. }
  27020. if (closePath) {
  27021. j--;
  27022. positions.push(path[0].x, path[0].y, path[0].z);
  27023. vectlg = path[j].subtract(path[0]).length();
  27024. dist = vectlg + uTotalDistance[p];
  27025. us[p].push(dist);
  27026. uTotalDistance[p] = dist;
  27027. }
  27028. lg[p] = l + closePathCorr;
  27029. idx[p] = idc;
  27030. idc += (l + closePathCorr);
  27031. }
  27032. // vertical distances (v)
  27033. var path1;
  27034. var path2;
  27035. var vertex1;
  27036. var vertex2;
  27037. for (i = 0; i < minlg + closePathCorr; i++) {
  27038. vTotalDistance[i] = 0;
  27039. vs[i] = [0];
  27040. for (p = 0; p < pathArray.length - 1; p++) {
  27041. path1 = pathArray[p];
  27042. path2 = pathArray[p + 1];
  27043. if (i === minlg) {
  27044. vertex1 = path1[0];
  27045. vertex2 = path2[0];
  27046. }
  27047. else {
  27048. vertex1 = path1[i];
  27049. vertex2 = path2[i];
  27050. }
  27051. vectlg = vertex2.subtract(vertex1).length();
  27052. dist = vectlg + vTotalDistance[i];
  27053. vs[i].push(dist);
  27054. vTotalDistance[i] = dist;
  27055. }
  27056. if (closeArray) {
  27057. path1 = pathArray[p];
  27058. path2 = pathArray[0];
  27059. if (i === minlg) {
  27060. vertex2 = path2[0];
  27061. }
  27062. vectlg = vertex2.subtract(vertex1).length();
  27063. dist = vectlg + vTotalDistance[i];
  27064. vTotalDistance[i] = dist;
  27065. }
  27066. }
  27067. // uvs
  27068. var u;
  27069. var v;
  27070. if (customUV) {
  27071. for (p = 0; p < customUV.length; p++) {
  27072. uvs.push(customUV[p].x, customUV[p].y);
  27073. }
  27074. }
  27075. else {
  27076. for (p = 0; p < pathArray.length; p++) {
  27077. for (i = 0; i < minlg + closePathCorr; i++) {
  27078. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  27079. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  27080. if (invertUV) {
  27081. uvs.push(v, u);
  27082. }
  27083. else {
  27084. uvs.push(u, v);
  27085. }
  27086. }
  27087. }
  27088. }
  27089. // indices
  27090. p = 0; // path index
  27091. var pi = 0; // positions array index
  27092. var l1 = lg[p] - 1; // path1 length
  27093. var l2 = lg[p + 1] - 1; // path2 length
  27094. var min = (l1 < l2) ? l1 : l2; // current path stop index
  27095. var shft = idx[1] - idx[0]; // shift
  27096. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  27097. while (pi <= min && p < path1nb) {
  27098. // 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
  27099. indices.push(pi, pi + shft, pi + 1);
  27100. indices.push(pi + shft + 1, pi + 1, pi + shft);
  27101. pi += 1;
  27102. if (pi === min) {
  27103. p++;
  27104. if (p === lg.length - 1) {
  27105. shft = idx[0] - idx[p];
  27106. l1 = lg[p] - 1;
  27107. l2 = lg[0] - 1;
  27108. }
  27109. else {
  27110. shft = idx[p + 1] - idx[p];
  27111. l1 = lg[p] - 1;
  27112. l2 = lg[p + 1] - 1;
  27113. }
  27114. pi = idx[p];
  27115. min = (l1 < l2) ? l1 + pi : l2 + pi;
  27116. }
  27117. }
  27118. // normals
  27119. VertexData.ComputeNormals(positions, indices, normals);
  27120. if (closePath) {
  27121. var indexFirst = 0;
  27122. var indexLast = 0;
  27123. for (p = 0; p < pathArray.length; p++) {
  27124. indexFirst = idx[p] * 3;
  27125. if (p + 1 < pathArray.length) {
  27126. indexLast = (idx[p + 1] - 1) * 3;
  27127. }
  27128. else {
  27129. indexLast = normals.length - 3;
  27130. }
  27131. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  27132. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  27133. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  27134. normals[indexLast] = normals[indexFirst];
  27135. normals[indexLast + 1] = normals[indexFirst + 1];
  27136. normals[indexLast + 2] = normals[indexFirst + 2];
  27137. }
  27138. }
  27139. // sides
  27140. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27141. // Colors
  27142. if (customColors) {
  27143. var colors = new Float32Array(customColors.length * 4);
  27144. for (var c = 0; c < customColors.length; c++) {
  27145. colors[c * 4] = customColors[c].r;
  27146. colors[c * 4 + 1] = customColors[c].g;
  27147. colors[c * 4 + 2] = customColors[c].b;
  27148. colors[c * 4 + 3] = customColors[c].a;
  27149. }
  27150. }
  27151. // Result
  27152. var vertexData = new VertexData();
  27153. var positions32 = new Float32Array(positions);
  27154. var normals32 = new Float32Array(normals);
  27155. var uvs32 = new Float32Array(uvs);
  27156. vertexData.indices = indices;
  27157. vertexData.positions = positions32;
  27158. vertexData.normals = normals32;
  27159. vertexData.uvs = uvs32;
  27160. if (customColors) {
  27161. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  27162. }
  27163. if (closePath) {
  27164. vertexData._idx = idx;
  27165. }
  27166. return vertexData;
  27167. };
  27168. /**
  27169. * Creates the VertexData of the Box.
  27170. */
  27171. VertexData.CreateBox = function (options) {
  27172. var normalsSource = [
  27173. new BABYLON.Vector3(0, 0, 1),
  27174. new BABYLON.Vector3(0, 0, -1),
  27175. new BABYLON.Vector3(1, 0, 0),
  27176. new BABYLON.Vector3(-1, 0, 0),
  27177. new BABYLON.Vector3(0, 1, 0),
  27178. new BABYLON.Vector3(0, -1, 0)
  27179. ];
  27180. var indices = [];
  27181. var positions = [];
  27182. var normals = [];
  27183. var uvs = [];
  27184. var width = options.width || options.size || 1;
  27185. var height = options.height || options.size || 1;
  27186. var depth = options.depth || options.size || 1;
  27187. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27188. var faceUV = options.faceUV || new Array(6);
  27189. var faceColors = options.faceColors;
  27190. var colors = [];
  27191. // default face colors and UV if undefined
  27192. for (var f = 0; f < 6; f++) {
  27193. if (faceUV[f] === undefined) {
  27194. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27195. }
  27196. if (faceColors && faceColors[f] === undefined) {
  27197. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27198. }
  27199. }
  27200. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  27201. // Create each face in turn.
  27202. for (var index = 0; index < normalsSource.length; index++) {
  27203. var normal = normalsSource[index];
  27204. // Get two vectors perpendicular to the face normal and to each other.
  27205. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  27206. var side2 = BABYLON.Vector3.Cross(normal, side1);
  27207. // Six indices (two triangles) per face.
  27208. var verticesLength = positions.length / 3;
  27209. indices.push(verticesLength);
  27210. indices.push(verticesLength + 1);
  27211. indices.push(verticesLength + 2);
  27212. indices.push(verticesLength);
  27213. indices.push(verticesLength + 2);
  27214. indices.push(verticesLength + 3);
  27215. // Four vertices per face.
  27216. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  27217. positions.push(vertex.x, vertex.y, vertex.z);
  27218. normals.push(normal.x, normal.y, normal.z);
  27219. uvs.push(faceUV[index].z, faceUV[index].w);
  27220. if (faceColors) {
  27221. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27222. }
  27223. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  27224. positions.push(vertex.x, vertex.y, vertex.z);
  27225. normals.push(normal.x, normal.y, normal.z);
  27226. uvs.push(faceUV[index].x, faceUV[index].w);
  27227. if (faceColors) {
  27228. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27229. }
  27230. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  27231. positions.push(vertex.x, vertex.y, vertex.z);
  27232. normals.push(normal.x, normal.y, normal.z);
  27233. uvs.push(faceUV[index].x, faceUV[index].y);
  27234. if (faceColors) {
  27235. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27236. }
  27237. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  27238. positions.push(vertex.x, vertex.y, vertex.z);
  27239. normals.push(normal.x, normal.y, normal.z);
  27240. uvs.push(faceUV[index].z, faceUV[index].y);
  27241. if (faceColors) {
  27242. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27243. }
  27244. }
  27245. // sides
  27246. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27247. // Result
  27248. var vertexData = new VertexData();
  27249. vertexData.indices = indices;
  27250. vertexData.positions = positions;
  27251. vertexData.normals = normals;
  27252. vertexData.uvs = uvs;
  27253. if (faceColors) {
  27254. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27255. vertexData.colors = totalColors;
  27256. }
  27257. return vertexData;
  27258. };
  27259. /**
  27260. * Creates the VertexData of the Sphere.
  27261. */
  27262. VertexData.CreateSphere = function (options) {
  27263. var segments = options.segments || 32;
  27264. var diameterX = options.diameterX || options.diameter || 1;
  27265. var diameterY = options.diameterY || options.diameter || 1;
  27266. var diameterZ = options.diameterZ || options.diameter || 1;
  27267. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27268. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  27269. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27270. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  27271. var totalZRotationSteps = 2 + segments;
  27272. var totalYRotationSteps = 2 * totalZRotationSteps;
  27273. var indices = [];
  27274. var positions = [];
  27275. var normals = [];
  27276. var uvs = [];
  27277. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  27278. var normalizedZ = zRotationStep / totalZRotationSteps;
  27279. var angleZ = normalizedZ * Math.PI * slice;
  27280. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  27281. var normalizedY = yRotationStep / totalYRotationSteps;
  27282. var angleY = normalizedY * Math.PI * 2 * arc;
  27283. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  27284. var rotationY = BABYLON.Matrix.RotationY(angleY);
  27285. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  27286. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  27287. var vertex = complete.multiply(radius);
  27288. var normal = complete.divide(radius).normalize();
  27289. positions.push(vertex.x, vertex.y, vertex.z);
  27290. normals.push(normal.x, normal.y, normal.z);
  27291. uvs.push(normalizedY, normalizedZ);
  27292. }
  27293. if (zRotationStep > 0) {
  27294. var verticesCount = positions.length / 3;
  27295. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  27296. indices.push((firstIndex));
  27297. indices.push((firstIndex + 1));
  27298. indices.push(firstIndex + totalYRotationSteps + 1);
  27299. indices.push((firstIndex + totalYRotationSteps + 1));
  27300. indices.push((firstIndex + 1));
  27301. indices.push((firstIndex + totalYRotationSteps + 2));
  27302. }
  27303. }
  27304. }
  27305. // Sides
  27306. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27307. // Result
  27308. var vertexData = new VertexData();
  27309. vertexData.indices = indices;
  27310. vertexData.positions = positions;
  27311. vertexData.normals = normals;
  27312. vertexData.uvs = uvs;
  27313. return vertexData;
  27314. };
  27315. /**
  27316. * Creates the VertexData of the Cylinder or Cone.
  27317. */
  27318. VertexData.CreateCylinder = function (options) {
  27319. var height = options.height || 2;
  27320. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  27321. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  27322. var tessellation = options.tessellation || 24;
  27323. var subdivisions = options.subdivisions || 1;
  27324. var hasRings = options.hasRings;
  27325. var enclose = options.enclose;
  27326. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27327. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27328. var faceUV = options.faceUV || new Array(3);
  27329. var faceColors = options.faceColors;
  27330. // default face colors and UV if undefined
  27331. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  27332. var ringNb = (hasRings) ? subdivisions : 1;
  27333. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  27334. var f;
  27335. for (f = 0; f < surfaceNb; f++) {
  27336. if (faceColors && faceColors[f] === undefined) {
  27337. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27338. }
  27339. }
  27340. for (f = 0; f < surfaceNb; f++) {
  27341. if (faceUV && faceUV[f] === undefined) {
  27342. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27343. }
  27344. }
  27345. var indices = [];
  27346. var positions = [];
  27347. var normals = [];
  27348. var uvs = [];
  27349. var colors = [];
  27350. var angle_step = Math.PI * 2 * arc / tessellation;
  27351. var angle;
  27352. var h;
  27353. var radius;
  27354. var tan = (diameterBottom - diameterTop) / 2 / height;
  27355. var ringVertex = BABYLON.Vector3.Zero();
  27356. var ringNormal = BABYLON.Vector3.Zero();
  27357. var ringFirstVertex = BABYLON.Vector3.Zero();
  27358. var ringFirstNormal = BABYLON.Vector3.Zero();
  27359. var quadNormal = BABYLON.Vector3.Zero();
  27360. var Y = BABYLON.Axis.Y;
  27361. // positions, normals, uvs
  27362. var i;
  27363. var j;
  27364. var r;
  27365. var ringIdx = 1;
  27366. var s = 1; // surface index
  27367. var cs = 0;
  27368. var v = 0;
  27369. for (i = 0; i <= subdivisions; i++) {
  27370. h = i / subdivisions;
  27371. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  27372. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  27373. for (r = 0; r < ringIdx; r++) {
  27374. if (hasRings) {
  27375. s += r;
  27376. }
  27377. if (enclose) {
  27378. s += 2 * r;
  27379. }
  27380. for (j = 0; j <= tessellation; j++) {
  27381. angle = j * angle_step;
  27382. // position
  27383. ringVertex.x = Math.cos(-angle) * radius;
  27384. ringVertex.y = -height / 2 + h * height;
  27385. ringVertex.z = Math.sin(-angle) * radius;
  27386. // normal
  27387. if (diameterTop === 0 && i === subdivisions) {
  27388. // if no top cap, reuse former normals
  27389. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  27390. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  27391. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  27392. }
  27393. else {
  27394. ringNormal.x = ringVertex.x;
  27395. ringNormal.z = ringVertex.z;
  27396. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  27397. ringNormal.normalize();
  27398. }
  27399. // keep first ring vertex values for enclose
  27400. if (j === 0) {
  27401. ringFirstVertex.copyFrom(ringVertex);
  27402. ringFirstNormal.copyFrom(ringNormal);
  27403. }
  27404. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27405. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  27406. if (hasRings) {
  27407. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  27408. }
  27409. else {
  27410. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  27411. }
  27412. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  27413. if (faceColors) {
  27414. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  27415. }
  27416. }
  27417. // if enclose, add four vertices and their dedicated normals
  27418. if (arc !== 1 && enclose) {
  27419. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27420. positions.push(0, ringVertex.y, 0);
  27421. positions.push(0, ringVertex.y, 0);
  27422. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  27423. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  27424. quadNormal.normalize();
  27425. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27426. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  27427. quadNormal.normalize();
  27428. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27429. if (hasRings) {
  27430. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  27431. }
  27432. else {
  27433. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  27434. }
  27435. uvs.push(faceUV[s + 1].x, v);
  27436. uvs.push(faceUV[s + 1].z, v);
  27437. if (hasRings) {
  27438. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  27439. }
  27440. else {
  27441. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  27442. }
  27443. uvs.push(faceUV[s + 2].x, v);
  27444. uvs.push(faceUV[s + 2].z, v);
  27445. if (faceColors) {
  27446. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27447. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27448. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27449. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27450. }
  27451. }
  27452. if (cs !== s) {
  27453. cs = s;
  27454. }
  27455. }
  27456. }
  27457. // indices
  27458. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  27459. var s;
  27460. i = 0;
  27461. for (s = 0; s < subdivisions; s++) {
  27462. for (j = 0; j < tessellation; j++) {
  27463. var i0 = i * (e + 1) + j;
  27464. var i1 = (i + 1) * (e + 1) + j;
  27465. var i2 = i * (e + 1) + (j + 1);
  27466. var i3 = (i + 1) * (e + 1) + (j + 1);
  27467. indices.push(i0, i1, i2);
  27468. indices.push(i3, i2, i1);
  27469. }
  27470. if (arc !== 1 && enclose) {
  27471. indices.push(i0 + 2, i1 + 2, i2 + 2);
  27472. indices.push(i3 + 2, i2 + 2, i1 + 2);
  27473. indices.push(i0 + 4, i1 + 4, i2 + 4);
  27474. indices.push(i3 + 4, i2 + 4, i1 + 4);
  27475. }
  27476. i = (hasRings) ? (i + 2) : (i + 1);
  27477. }
  27478. // Caps
  27479. var createCylinderCap = function (isTop) {
  27480. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  27481. if (radius === 0) {
  27482. return;
  27483. }
  27484. // Cap positions, normals & uvs
  27485. var angle;
  27486. var circleVector;
  27487. var i;
  27488. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  27489. var c;
  27490. if (faceColors) {
  27491. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  27492. }
  27493. // cap center
  27494. var vbase = positions.length / 3;
  27495. var offset = isTop ? height / 2 : -height / 2;
  27496. var center = new BABYLON.Vector3(0, offset, 0);
  27497. positions.push(center.x, center.y, center.z);
  27498. normals.push(0, isTop ? 1 : -1, 0);
  27499. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  27500. if (faceColors) {
  27501. colors.push(c.r, c.g, c.b, c.a);
  27502. }
  27503. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  27504. for (i = 0; i <= tessellation; i++) {
  27505. angle = Math.PI * 2 * i * arc / tessellation;
  27506. var cos = Math.cos(-angle);
  27507. var sin = Math.sin(-angle);
  27508. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  27509. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  27510. positions.push(circleVector.x, circleVector.y, circleVector.z);
  27511. normals.push(0, isTop ? 1 : -1, 0);
  27512. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  27513. if (faceColors) {
  27514. colors.push(c.r, c.g, c.b, c.a);
  27515. }
  27516. }
  27517. // Cap indices
  27518. for (i = 0; i < tessellation; i++) {
  27519. if (!isTop) {
  27520. indices.push(vbase);
  27521. indices.push(vbase + (i + 1));
  27522. indices.push(vbase + (i + 2));
  27523. }
  27524. else {
  27525. indices.push(vbase);
  27526. indices.push(vbase + (i + 2));
  27527. indices.push(vbase + (i + 1));
  27528. }
  27529. }
  27530. };
  27531. // add caps to geometry
  27532. createCylinderCap(false);
  27533. createCylinderCap(true);
  27534. // Sides
  27535. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27536. var vertexData = new VertexData();
  27537. vertexData.indices = indices;
  27538. vertexData.positions = positions;
  27539. vertexData.normals = normals;
  27540. vertexData.uvs = uvs;
  27541. if (faceColors) {
  27542. vertexData.colors = colors;
  27543. }
  27544. return vertexData;
  27545. };
  27546. /**
  27547. * Creates the VertexData of the Torus.
  27548. */
  27549. VertexData.CreateTorus = function (options) {
  27550. var indices = [];
  27551. var positions = [];
  27552. var normals = [];
  27553. var uvs = [];
  27554. var diameter = options.diameter || 1;
  27555. var thickness = options.thickness || 0.5;
  27556. var tessellation = options.tessellation || 16;
  27557. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27558. var stride = tessellation + 1;
  27559. for (var i = 0; i <= tessellation; i++) {
  27560. var u = i / tessellation;
  27561. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  27562. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  27563. for (var j = 0; j <= tessellation; j++) {
  27564. var v = 1 - j / tessellation;
  27565. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  27566. var dx = Math.cos(innerAngle);
  27567. var dy = Math.sin(innerAngle);
  27568. // Create a vertex.
  27569. var normal = new BABYLON.Vector3(dx, dy, 0);
  27570. var position = normal.scale(thickness / 2);
  27571. var textureCoordinate = new BABYLON.Vector2(u, v);
  27572. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  27573. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  27574. positions.push(position.x, position.y, position.z);
  27575. normals.push(normal.x, normal.y, normal.z);
  27576. uvs.push(textureCoordinate.x, textureCoordinate.y);
  27577. // And create indices for two triangles.
  27578. var nextI = (i + 1) % stride;
  27579. var nextJ = (j + 1) % stride;
  27580. indices.push(i * stride + j);
  27581. indices.push(i * stride + nextJ);
  27582. indices.push(nextI * stride + j);
  27583. indices.push(i * stride + nextJ);
  27584. indices.push(nextI * stride + nextJ);
  27585. indices.push(nextI * stride + j);
  27586. }
  27587. }
  27588. // Sides
  27589. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27590. // Result
  27591. var vertexData = new VertexData();
  27592. vertexData.indices = indices;
  27593. vertexData.positions = positions;
  27594. vertexData.normals = normals;
  27595. vertexData.uvs = uvs;
  27596. return vertexData;
  27597. };
  27598. /**
  27599. * Creates the VertexData of the LineSystem.
  27600. */
  27601. VertexData.CreateLineSystem = function (options) {
  27602. var indices = [];
  27603. var positions = [];
  27604. var lines = options.lines;
  27605. var idx = 0;
  27606. for (var l = 0; l < lines.length; l++) {
  27607. var points = lines[l];
  27608. for (var index = 0; index < points.length; index++) {
  27609. positions.push(points[index].x, points[index].y, points[index].z);
  27610. if (index > 0) {
  27611. indices.push(idx - 1);
  27612. indices.push(idx);
  27613. }
  27614. idx++;
  27615. }
  27616. }
  27617. var vertexData = new VertexData();
  27618. vertexData.indices = indices;
  27619. vertexData.positions = positions;
  27620. return vertexData;
  27621. };
  27622. /**
  27623. * Create the VertexData of the DashedLines.
  27624. */
  27625. VertexData.CreateDashedLines = function (options) {
  27626. var dashSize = options.dashSize || 3;
  27627. var gapSize = options.gapSize || 1;
  27628. var dashNb = options.dashNb || 200;
  27629. var points = options.points;
  27630. var positions = new Array();
  27631. var indices = new Array();
  27632. var curvect = BABYLON.Vector3.Zero();
  27633. var lg = 0;
  27634. var nb = 0;
  27635. var shft = 0;
  27636. var dashshft = 0;
  27637. var curshft = 0;
  27638. var idx = 0;
  27639. var i = 0;
  27640. for (i = 0; i < points.length - 1; i++) {
  27641. points[i + 1].subtractToRef(points[i], curvect);
  27642. lg += curvect.length();
  27643. }
  27644. shft = lg / dashNb;
  27645. dashshft = dashSize * shft / (dashSize + gapSize);
  27646. for (i = 0; i < points.length - 1; i++) {
  27647. points[i + 1].subtractToRef(points[i], curvect);
  27648. nb = Math.floor(curvect.length() / shft);
  27649. curvect.normalize();
  27650. for (var j = 0; j < nb; j++) {
  27651. curshft = shft * j;
  27652. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  27653. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  27654. indices.push(idx, idx + 1);
  27655. idx += 2;
  27656. }
  27657. }
  27658. // Result
  27659. var vertexData = new VertexData();
  27660. vertexData.positions = positions;
  27661. vertexData.indices = indices;
  27662. return vertexData;
  27663. };
  27664. /**
  27665. * Creates the VertexData of the Ground.
  27666. */
  27667. VertexData.CreateGround = function (options) {
  27668. var indices = [];
  27669. var positions = [];
  27670. var normals = [];
  27671. var uvs = [];
  27672. var row, col;
  27673. var width = options.width || 1;
  27674. var height = options.height || 1;
  27675. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  27676. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  27677. for (row = 0; row <= subdivisionsY; row++) {
  27678. for (col = 0; col <= subdivisionsX; col++) {
  27679. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  27680. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27681. positions.push(position.x, position.y, position.z);
  27682. normals.push(normal.x, normal.y, normal.z);
  27683. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  27684. }
  27685. }
  27686. for (row = 0; row < subdivisionsY; row++) {
  27687. for (col = 0; col < subdivisionsX; col++) {
  27688. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27689. indices.push(col + 1 + row * (subdivisionsX + 1));
  27690. indices.push(col + row * (subdivisionsX + 1));
  27691. indices.push(col + (row + 1) * (subdivisionsX + 1));
  27692. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27693. indices.push(col + row * (subdivisionsX + 1));
  27694. }
  27695. }
  27696. // Result
  27697. var vertexData = new VertexData();
  27698. vertexData.indices = indices;
  27699. vertexData.positions = positions;
  27700. vertexData.normals = normals;
  27701. vertexData.uvs = uvs;
  27702. return vertexData;
  27703. };
  27704. /**
  27705. * Creates the VertexData of the TiledGround.
  27706. */
  27707. VertexData.CreateTiledGround = function (options) {
  27708. var xmin = options.xmin || -1.0;
  27709. var zmin = options.zmin || -1.0;
  27710. var xmax = options.xmax || 1.0;
  27711. var zmax = options.zmax || 1.0;
  27712. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  27713. var precision = options.precision || { w: 1, h: 1 };
  27714. var indices = [];
  27715. var positions = [];
  27716. var normals = [];
  27717. var uvs = [];
  27718. var row, col, tileRow, tileCol;
  27719. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  27720. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  27721. precision.w = (precision.w < 1) ? 1 : precision.w;
  27722. precision.h = (precision.h < 1) ? 1 : precision.h;
  27723. var tileSize = {
  27724. 'w': (xmax - xmin) / subdivisions.w,
  27725. 'h': (zmax - zmin) / subdivisions.h
  27726. };
  27727. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  27728. // Indices
  27729. var base = positions.length / 3;
  27730. var rowLength = precision.w + 1;
  27731. for (row = 0; row < precision.h; row++) {
  27732. for (col = 0; col < precision.w; col++) {
  27733. var square = [
  27734. base + col + row * rowLength,
  27735. base + (col + 1) + row * rowLength,
  27736. base + (col + 1) + (row + 1) * rowLength,
  27737. base + col + (row + 1) * rowLength
  27738. ];
  27739. indices.push(square[1]);
  27740. indices.push(square[2]);
  27741. indices.push(square[3]);
  27742. indices.push(square[0]);
  27743. indices.push(square[1]);
  27744. indices.push(square[3]);
  27745. }
  27746. }
  27747. // Position, normals and uvs
  27748. var position = BABYLON.Vector3.Zero();
  27749. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27750. for (row = 0; row <= precision.h; row++) {
  27751. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  27752. for (col = 0; col <= precision.w; col++) {
  27753. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  27754. position.y = 0;
  27755. positions.push(position.x, position.y, position.z);
  27756. normals.push(normal.x, normal.y, normal.z);
  27757. uvs.push(col / precision.w, row / precision.h);
  27758. }
  27759. }
  27760. }
  27761. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  27762. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  27763. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  27764. }
  27765. }
  27766. // Result
  27767. var vertexData = new VertexData();
  27768. vertexData.indices = indices;
  27769. vertexData.positions = positions;
  27770. vertexData.normals = normals;
  27771. vertexData.uvs = uvs;
  27772. return vertexData;
  27773. };
  27774. /**
  27775. * Creates the VertexData of the Ground designed from a heightmap.
  27776. */
  27777. VertexData.CreateGroundFromHeightMap = function (options) {
  27778. var indices = [];
  27779. var positions = [];
  27780. var normals = [];
  27781. var uvs = [];
  27782. var row, col;
  27783. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  27784. // Vertices
  27785. for (row = 0; row <= options.subdivisions; row++) {
  27786. for (col = 0; col <= options.subdivisions; col++) {
  27787. 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));
  27788. // Compute height
  27789. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  27790. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  27791. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  27792. var r = options.buffer[pos] / 255.0;
  27793. var g = options.buffer[pos + 1] / 255.0;
  27794. var b = options.buffer[pos + 2] / 255.0;
  27795. var gradient = r * filter.r + g * filter.g + b * filter.b;
  27796. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  27797. // Add vertex
  27798. positions.push(position.x, position.y, position.z);
  27799. normals.push(0, 0, 0);
  27800. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  27801. }
  27802. }
  27803. // Indices
  27804. for (row = 0; row < options.subdivisions; row++) {
  27805. for (col = 0; col < options.subdivisions; col++) {
  27806. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27807. indices.push(col + 1 + row * (options.subdivisions + 1));
  27808. indices.push(col + row * (options.subdivisions + 1));
  27809. indices.push(col + (row + 1) * (options.subdivisions + 1));
  27810. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27811. indices.push(col + row * (options.subdivisions + 1));
  27812. }
  27813. }
  27814. // Normals
  27815. VertexData.ComputeNormals(positions, indices, normals);
  27816. // Result
  27817. var vertexData = new VertexData();
  27818. vertexData.indices = indices;
  27819. vertexData.positions = positions;
  27820. vertexData.normals = normals;
  27821. vertexData.uvs = uvs;
  27822. return vertexData;
  27823. };
  27824. /**
  27825. * Creates the VertexData of the Plane.
  27826. */
  27827. VertexData.CreatePlane = function (options) {
  27828. var indices = [];
  27829. var positions = [];
  27830. var normals = [];
  27831. var uvs = [];
  27832. var width = options.width || options.size || 1;
  27833. var height = options.height || options.size || 1;
  27834. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27835. // Vertices
  27836. var halfWidth = width / 2.0;
  27837. var halfHeight = height / 2.0;
  27838. positions.push(-halfWidth, -halfHeight, 0);
  27839. normals.push(0, 0, -1.0);
  27840. uvs.push(0.0, 0.0);
  27841. positions.push(halfWidth, -halfHeight, 0);
  27842. normals.push(0, 0, -1.0);
  27843. uvs.push(1.0, 0.0);
  27844. positions.push(halfWidth, halfHeight, 0);
  27845. normals.push(0, 0, -1.0);
  27846. uvs.push(1.0, 1.0);
  27847. positions.push(-halfWidth, halfHeight, 0);
  27848. normals.push(0, 0, -1.0);
  27849. uvs.push(0.0, 1.0);
  27850. // Indices
  27851. indices.push(0);
  27852. indices.push(1);
  27853. indices.push(2);
  27854. indices.push(0);
  27855. indices.push(2);
  27856. indices.push(3);
  27857. // Sides
  27858. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27859. // Result
  27860. var vertexData = new VertexData();
  27861. vertexData.indices = indices;
  27862. vertexData.positions = positions;
  27863. vertexData.normals = normals;
  27864. vertexData.uvs = uvs;
  27865. return vertexData;
  27866. };
  27867. /**
  27868. * Creates the VertexData of the Disc or regular Polygon.
  27869. */
  27870. VertexData.CreateDisc = function (options) {
  27871. var positions = [];
  27872. var indices = [];
  27873. var normals = [];
  27874. var uvs = [];
  27875. var radius = options.radius || 0.5;
  27876. var tessellation = options.tessellation || 64;
  27877. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27878. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27879. // positions and uvs
  27880. positions.push(0, 0, 0); // disc center first
  27881. uvs.push(0.5, 0.5);
  27882. var theta = Math.PI * 2 * arc;
  27883. var step = theta / tessellation;
  27884. for (var a = 0; a < theta; a += step) {
  27885. var x = Math.cos(a);
  27886. var y = Math.sin(a);
  27887. var u = (x + 1) / 2;
  27888. var v = (1 - y) / 2;
  27889. positions.push(radius * x, radius * y, 0);
  27890. uvs.push(u, v);
  27891. }
  27892. if (arc === 1) {
  27893. positions.push(positions[3], positions[4], positions[5]); // close the circle
  27894. uvs.push(uvs[2], uvs[3]);
  27895. }
  27896. //indices
  27897. var vertexNb = positions.length / 3;
  27898. for (var i = 1; i < vertexNb - 1; i++) {
  27899. indices.push(i + 1, 0, i);
  27900. }
  27901. // result
  27902. VertexData.ComputeNormals(positions, indices, normals);
  27903. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27904. var vertexData = new VertexData();
  27905. vertexData.indices = indices;
  27906. vertexData.positions = positions;
  27907. vertexData.normals = normals;
  27908. vertexData.uvs = uvs;
  27909. return vertexData;
  27910. };
  27911. /**
  27912. * Re-creates the VertexData of the Polygon for sideOrientation.
  27913. */
  27914. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  27915. var faceUV = fUV || new Array(3);
  27916. var faceColors = fColors;
  27917. var colors = [];
  27918. // default face colors and UV if undefined
  27919. for (var f = 0; f < 3; f++) {
  27920. if (faceUV[f] === undefined) {
  27921. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27922. }
  27923. if (faceColors && faceColors[f] === undefined) {
  27924. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27925. }
  27926. }
  27927. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27928. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27929. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27930. var indices = polygon.getIndices();
  27931. // set face colours and textures
  27932. var idx = 0;
  27933. var face = 0;
  27934. for (var index = 0; index < normals.length; index += 3) {
  27935. //Edge Face no. 1
  27936. if (Math.abs(normals[index + 1]) < 0.001) {
  27937. face = 1;
  27938. }
  27939. //Top Face no. 0
  27940. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  27941. face = 0;
  27942. }
  27943. //Bottom Face no. 2
  27944. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  27945. face = 2;
  27946. }
  27947. idx = index / 3;
  27948. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  27949. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  27950. if (faceColors) {
  27951. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  27952. }
  27953. }
  27954. // sides
  27955. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  27956. // Result
  27957. var vertexData = new VertexData();
  27958. vertexData.indices = indices;
  27959. vertexData.positions = positions;
  27960. vertexData.normals = normals;
  27961. vertexData.uvs = uvs;
  27962. if (faceColors) {
  27963. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27964. vertexData.colors = totalColors;
  27965. }
  27966. return vertexData;
  27967. };
  27968. /**
  27969. * Creates the VertexData of the IcoSphere.
  27970. */
  27971. VertexData.CreateIcoSphere = function (options) {
  27972. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27973. var radius = options.radius || 1;
  27974. var flat = (options.flat === undefined) ? true : options.flat;
  27975. var subdivisions = options.subdivisions || 4;
  27976. var radiusX = options.radiusX || radius;
  27977. var radiusY = options.radiusY || radius;
  27978. var radiusZ = options.radiusZ || radius;
  27979. var t = (1 + Math.sqrt(5)) / 2;
  27980. // 12 vertex x,y,z
  27981. var ico_vertices = [
  27982. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  27983. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  27984. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  27985. ];
  27986. // index of 3 vertex makes a face of icopshere
  27987. var ico_indices = [
  27988. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  27989. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  27990. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  27991. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  27992. ];
  27993. // vertex for uv have aliased position, not for UV
  27994. var vertices_unalias_id = [
  27995. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  27996. // vertex alias
  27997. 0,
  27998. 2,
  27999. 3,
  28000. 3,
  28001. 3,
  28002. 4,
  28003. 7,
  28004. 8,
  28005. 9,
  28006. 9,
  28007. 10,
  28008. 11 // 23: B + 12
  28009. ];
  28010. // uv as integer step (not pixels !)
  28011. var ico_vertexuv = [
  28012. 5, 1, 3, 1, 6, 4, 0, 0,
  28013. 5, 3, 4, 2, 2, 2, 4, 0,
  28014. 2, 0, 1, 1, 6, 0, 6, 2,
  28015. // vertex alias (for same vertex on different faces)
  28016. 0, 4,
  28017. 3, 3,
  28018. 4, 4,
  28019. 3, 1,
  28020. 4, 2,
  28021. 4, 4,
  28022. 0, 2,
  28023. 1, 1,
  28024. 2, 2,
  28025. 3, 3,
  28026. 1, 3,
  28027. 2, 4 // 23: B + 12
  28028. ];
  28029. // Vertices[0, 1, ...9, A, B] : position on UV plane
  28030. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  28031. // First island of uv mapping
  28032. // v = 4h 3+ 2
  28033. // v = 3h 9+ 4
  28034. // v = 2h 9+ 5 B
  28035. // v = 1h 9 1 0
  28036. // v = 0h 3 8 7 A
  28037. // u = 0 1 2 3 4 5 6 *a
  28038. // Second island of uv mapping
  28039. // v = 4h 0+ B+ 4+
  28040. // v = 3h A+ 2+
  28041. // v = 2h 7+ 6 3+
  28042. // v = 1h 8+ 3+
  28043. // v = 0h
  28044. // u = 0 1 2 3 4 5 6 *a
  28045. // Face layout on texture UV mapping
  28046. // ============
  28047. // \ 4 /\ 16 / ======
  28048. // \ / \ / /\ 11 /
  28049. // \/ 7 \/ / \ /
  28050. // ======= / 10 \/
  28051. // /\ 17 /\ =======
  28052. // / \ / \ \ 15 /\
  28053. // / 8 \/ 12 \ \ / \
  28054. // ============ \/ 6 \
  28055. // \ 18 /\ ============
  28056. // \ / \ \ 5 /\ 0 /
  28057. // \/ 13 \ \ / \ /
  28058. // ======= \/ 1 \/
  28059. // =============
  28060. // /\ 19 /\ 2 /\
  28061. // / \ / \ / \
  28062. // / 14 \/ 9 \/ 3 \
  28063. // ===================
  28064. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  28065. var ustep = 138 / 1024;
  28066. var vstep = 239 / 1024;
  28067. var uoffset = 60 / 1024;
  28068. var voffset = 26 / 1024;
  28069. // Second island should have margin, not to touch the first island
  28070. // avoid any borderline artefact in pixel rounding
  28071. var island_u_offset = -40 / 1024;
  28072. var island_v_offset = +20 / 1024;
  28073. // face is either island 0 or 1 :
  28074. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  28075. var island = [
  28076. 0, 0, 0, 0, 1,
  28077. 0, 0, 1, 1, 0,
  28078. 0, 0, 1, 1, 0,
  28079. 0, 1, 1, 1, 0 // 15 - 19
  28080. ];
  28081. var indices = [];
  28082. var positions = [];
  28083. var normals = [];
  28084. var uvs = [];
  28085. var current_indice = 0;
  28086. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  28087. var face_vertex_pos = new Array(3);
  28088. var face_vertex_uv = new Array(3);
  28089. var v012;
  28090. for (v012 = 0; v012 < 3; v012++) {
  28091. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  28092. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  28093. }
  28094. // create all with normals
  28095. for (var face = 0; face < 20; face++) {
  28096. // 3 vertex per face
  28097. for (v012 = 0; v012 < 3; v012++) {
  28098. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  28099. var v_id = ico_indices[3 * face + v012];
  28100. // vertex have 3D position (x,y,z)
  28101. 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]);
  28102. // Normalize to get normal, then scale to radius
  28103. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  28104. // uv Coordinates from vertex ID
  28105. 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);
  28106. }
  28107. // Subdivide the face (interpolate pos, norm, uv)
  28108. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  28109. // - norm is linear interpolation of vertex corner normal
  28110. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  28111. // - uv is linear interpolation
  28112. //
  28113. // Topology is as below for sub-divide by 2
  28114. // vertex shown as v0,v1,v2
  28115. // interp index is i1 to progress in range [v0,v1[
  28116. // interp index is i2 to progress in range [v0,v2[
  28117. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  28118. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28119. //
  28120. //
  28121. // i2 v2
  28122. // ^ ^
  28123. // / / \
  28124. // / / \
  28125. // / / \
  28126. // / / (0,1) \
  28127. // / #---------\
  28128. // / / \ (0,0)'/ \
  28129. // / / \ / \
  28130. // / / \ / \
  28131. // / / (0,0) \ / (1,0) \
  28132. // / #---------#---------\
  28133. // v0 v1
  28134. //
  28135. // --------------------> i1
  28136. //
  28137. // interp of (i1,i2):
  28138. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  28139. // along i1 : lerp(x0,x1, i1/(S-i2))
  28140. //
  28141. // centroid of triangle is needed to get help normal computation
  28142. // (c1,c2) are used for centroid location
  28143. var interp_vertex = function (i1, i2, c1, c2) {
  28144. // vertex is interpolated from
  28145. // - face_vertex_pos[0..2]
  28146. // - face_vertex_uv[0..2]
  28147. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  28148. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  28149. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  28150. pos_interp.normalize();
  28151. var vertex_normal;
  28152. if (flat) {
  28153. // in flat mode, recalculate normal as face centroid normal
  28154. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  28155. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  28156. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  28157. }
  28158. else {
  28159. // in smooth mode, recalculate normal from each single vertex position
  28160. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  28161. }
  28162. // Vertex normal need correction due to X,Y,Z radius scaling
  28163. vertex_normal.x /= radiusX;
  28164. vertex_normal.y /= radiusY;
  28165. vertex_normal.z /= radiusZ;
  28166. vertex_normal.normalize();
  28167. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  28168. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  28169. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  28170. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  28171. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  28172. uvs.push(uv_interp.x, uv_interp.y);
  28173. // push each vertex has member of a face
  28174. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  28175. indices.push(current_indice);
  28176. current_indice++;
  28177. };
  28178. for (var i2 = 0; i2 < subdivisions; i2++) {
  28179. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  28180. // face : (i1,i2) for /\ :
  28181. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  28182. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28183. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28184. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28185. if (i1 + i2 + 1 < subdivisions) {
  28186. // face : (i1,i2)' for \/ :
  28187. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28188. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28189. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28190. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28191. }
  28192. }
  28193. }
  28194. }
  28195. // Sides
  28196. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28197. // Result
  28198. var vertexData = new VertexData();
  28199. vertexData.indices = indices;
  28200. vertexData.positions = positions;
  28201. vertexData.normals = normals;
  28202. vertexData.uvs = uvs;
  28203. return vertexData;
  28204. };
  28205. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  28206. /**
  28207. * Creates the VertexData of the Polyhedron.
  28208. */
  28209. VertexData.CreatePolyhedron = function (options) {
  28210. // provided polyhedron types :
  28211. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  28212. // 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)
  28213. var polyhedra = [];
  28214. 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]] };
  28215. 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]] };
  28216. polyhedra[2] = {
  28217. 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]],
  28218. 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]]
  28219. };
  28220. polyhedra[3] = {
  28221. 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]],
  28222. 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]]
  28223. };
  28224. polyhedra[4] = {
  28225. 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]],
  28226. 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]]
  28227. };
  28228. 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]] };
  28229. 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]] };
  28230. 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]] };
  28231. 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]] };
  28232. 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]] };
  28233. 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]] };
  28234. 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]] };
  28235. 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]] };
  28236. 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]] };
  28237. polyhedra[14] = {
  28238. 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]],
  28239. 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]]
  28240. };
  28241. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  28242. var size = options.size;
  28243. var sizeX = options.sizeX || size || 1;
  28244. var sizeY = options.sizeY || size || 1;
  28245. var sizeZ = options.sizeZ || size || 1;
  28246. var data = options.custom || polyhedra[type];
  28247. var nbfaces = data.face.length;
  28248. var faceUV = options.faceUV || new Array(nbfaces);
  28249. var faceColors = options.faceColors;
  28250. var flat = (options.flat === undefined) ? true : options.flat;
  28251. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28252. var positions = [];
  28253. var indices = [];
  28254. var normals = [];
  28255. var uvs = [];
  28256. var colors = [];
  28257. var index = 0;
  28258. var faceIdx = 0; // face cursor in the array "indexes"
  28259. var indexes = [];
  28260. var i = 0;
  28261. var f = 0;
  28262. var u, v, ang, x, y, tmp;
  28263. // default face colors and UV if undefined
  28264. if (flat) {
  28265. for (f = 0; f < nbfaces; f++) {
  28266. if (faceColors && faceColors[f] === undefined) {
  28267. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28268. }
  28269. if (faceUV && faceUV[f] === undefined) {
  28270. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28271. }
  28272. }
  28273. }
  28274. if (!flat) {
  28275. for (i = 0; i < data.vertex.length; i++) {
  28276. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  28277. uvs.push(0, 0);
  28278. }
  28279. for (f = 0; f < nbfaces; f++) {
  28280. for (i = 0; i < data.face[f].length - 2; i++) {
  28281. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  28282. }
  28283. }
  28284. }
  28285. else {
  28286. for (f = 0; f < nbfaces; f++) {
  28287. var fl = data.face[f].length; // number of vertices of the current face
  28288. ang = 2 * Math.PI / fl;
  28289. x = 0.5 * Math.tan(ang / 2);
  28290. y = 0.5;
  28291. // positions, uvs, colors
  28292. for (i = 0; i < fl; i++) {
  28293. // positions
  28294. 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);
  28295. indexes.push(index);
  28296. index++;
  28297. // uvs
  28298. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  28299. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  28300. uvs.push(u, v);
  28301. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  28302. y = x * Math.sin(ang) + y * Math.cos(ang);
  28303. x = tmp;
  28304. // colors
  28305. if (faceColors) {
  28306. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  28307. }
  28308. }
  28309. // indices from indexes
  28310. for (i = 0; i < fl - 2; i++) {
  28311. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  28312. }
  28313. faceIdx += fl;
  28314. }
  28315. }
  28316. VertexData.ComputeNormals(positions, indices, normals);
  28317. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28318. var vertexData = new VertexData();
  28319. vertexData.positions = positions;
  28320. vertexData.indices = indices;
  28321. vertexData.normals = normals;
  28322. vertexData.uvs = uvs;
  28323. if (faceColors && flat) {
  28324. vertexData.colors = colors;
  28325. }
  28326. return vertexData;
  28327. };
  28328. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  28329. /**
  28330. * Creates the VertexData of the Torus Knot.
  28331. */
  28332. VertexData.CreateTorusKnot = function (options) {
  28333. var indices = [];
  28334. var positions = [];
  28335. var normals = [];
  28336. var uvs = [];
  28337. var radius = options.radius || 2;
  28338. var tube = options.tube || 0.5;
  28339. var radialSegments = options.radialSegments || 32;
  28340. var tubularSegments = options.tubularSegments || 32;
  28341. var p = options.p || 2;
  28342. var q = options.q || 3;
  28343. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28344. // Helper
  28345. var getPos = function (angle) {
  28346. var cu = Math.cos(angle);
  28347. var su = Math.sin(angle);
  28348. var quOverP = q / p * angle;
  28349. var cs = Math.cos(quOverP);
  28350. var tx = radius * (2 + cs) * 0.5 * cu;
  28351. var ty = radius * (2 + cs) * su * 0.5;
  28352. var tz = radius * Math.sin(quOverP) * 0.5;
  28353. return new BABYLON.Vector3(tx, ty, tz);
  28354. };
  28355. // Vertices
  28356. var i;
  28357. var j;
  28358. for (i = 0; i <= radialSegments; i++) {
  28359. var modI = i % radialSegments;
  28360. var u = modI / radialSegments * 2 * p * Math.PI;
  28361. var p1 = getPos(u);
  28362. var p2 = getPos(u + 0.01);
  28363. var tang = p2.subtract(p1);
  28364. var n = p2.add(p1);
  28365. var bitan = BABYLON.Vector3.Cross(tang, n);
  28366. n = BABYLON.Vector3.Cross(bitan, tang);
  28367. bitan.normalize();
  28368. n.normalize();
  28369. for (j = 0; j < tubularSegments; j++) {
  28370. var modJ = j % tubularSegments;
  28371. var v = modJ / tubularSegments * 2 * Math.PI;
  28372. var cx = -tube * Math.cos(v);
  28373. var cy = tube * Math.sin(v);
  28374. positions.push(p1.x + cx * n.x + cy * bitan.x);
  28375. positions.push(p1.y + cx * n.y + cy * bitan.y);
  28376. positions.push(p1.z + cx * n.z + cy * bitan.z);
  28377. uvs.push(i / radialSegments);
  28378. uvs.push(j / tubularSegments);
  28379. }
  28380. }
  28381. for (i = 0; i < radialSegments; i++) {
  28382. for (j = 0; j < tubularSegments; j++) {
  28383. var jNext = (j + 1) % tubularSegments;
  28384. var a = i * tubularSegments + j;
  28385. var b = (i + 1) * tubularSegments + j;
  28386. var c = (i + 1) * tubularSegments + jNext;
  28387. var d = i * tubularSegments + jNext;
  28388. indices.push(d);
  28389. indices.push(b);
  28390. indices.push(a);
  28391. indices.push(d);
  28392. indices.push(c);
  28393. indices.push(b);
  28394. }
  28395. }
  28396. // Normals
  28397. VertexData.ComputeNormals(positions, indices, normals);
  28398. // Sides
  28399. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28400. // Result
  28401. var vertexData = new VertexData();
  28402. vertexData.indices = indices;
  28403. vertexData.positions = positions;
  28404. vertexData.normals = normals;
  28405. vertexData.uvs = uvs;
  28406. return vertexData;
  28407. };
  28408. // Tools
  28409. /**
  28410. * @param {any} - positions (number[] or Float32Array)
  28411. * @param {any} - indices (number[] or Uint16Array)
  28412. * @param {any} - normals (number[] or Float32Array)
  28413. * options (optional) :
  28414. * facetPositions : optional array of facet positions (vector3)
  28415. * facetNormals : optional array of facet normals (vector3)
  28416. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  28417. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  28418. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  28419. * bbSize : optional bounding box size data, required for facetPartitioning computation
  28420. * bInfo : optional bounding info, required for facetPartitioning computation
  28421. */
  28422. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  28423. // temporary scalar variables
  28424. var index = 0; // facet index
  28425. var p1p2x = 0.0; // p1p2 vector x coordinate
  28426. var p1p2y = 0.0; // p1p2 vector y coordinate
  28427. var p1p2z = 0.0; // p1p2 vector z coordinate
  28428. var p3p2x = 0.0; // p3p2 vector x coordinate
  28429. var p3p2y = 0.0; // p3p2 vector y coordinate
  28430. var p3p2z = 0.0; // p3p2 vector z coordinate
  28431. var faceNormalx = 0.0; // facet normal x coordinate
  28432. var faceNormaly = 0.0; // facet normal y coordinate
  28433. var faceNormalz = 0.0; // facet normal z coordinate
  28434. var length = 0.0; // facet normal length before normalization
  28435. var v1x = 0; // vector1 x index in the positions array
  28436. var v1y = 0; // vector1 y index in the positions array
  28437. var v1z = 0; // vector1 z index in the positions array
  28438. var v2x = 0; // vector2 x index in the positions array
  28439. var v2y = 0; // vector2 y index in the positions array
  28440. var v2z = 0; // vector2 z index in the positions array
  28441. var v3x = 0; // vector3 x index in the positions array
  28442. var v3y = 0; // vector3 y index in the positions array
  28443. var v3z = 0; // vector3 z index in the positions array
  28444. var computeFacetNormals = false;
  28445. var computeFacetPositions = false;
  28446. var computeFacetPartitioning = false;
  28447. var faceNormalSign = 1;
  28448. if (options) {
  28449. computeFacetNormals = (options.facetNormals) ? true : false;
  28450. computeFacetPositions = (options.facetPositions) ? true : false;
  28451. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  28452. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  28453. }
  28454. // facetPartitioning reinit if needed
  28455. if (computeFacetPartitioning) {
  28456. var ox = 0; // X partitioning index for facet position
  28457. var oy = 0; // Y partinioning index for facet position
  28458. var oz = 0; // Z partinioning index for facet position
  28459. var b1x = 0; // X partitioning index for facet v1 vertex
  28460. var b1y = 0; // Y partitioning index for facet v1 vertex
  28461. var b1z = 0; // z partitioning index for facet v1 vertex
  28462. var b2x = 0; // X partitioning index for facet v2 vertex
  28463. var b2y = 0; // Y partitioning index for facet v2 vertex
  28464. var b2z = 0; // Z partitioning index for facet v2 vertex
  28465. var b3x = 0; // X partitioning index for facet v3 vertex
  28466. var b3y = 0; // Y partitioning index for facet v3 vertex
  28467. var b3z = 0; // Z partitioning index for facet v3 vertex
  28468. var block_idx_o = 0; // facet barycenter block index
  28469. var block_idx_v1 = 0; // v1 vertex block index
  28470. var block_idx_v2 = 0; // v2 vertex block index
  28471. var block_idx_v3 = 0; // v3 vertex block index
  28472. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  28473. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  28474. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  28475. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  28476. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  28477. var subSq = options.subDiv.max * options.subDiv.max;
  28478. options.facetPartitioning.length = 0;
  28479. }
  28480. // reset the normals
  28481. for (index = 0; index < positions.length; index++) {
  28482. normals[index] = 0.0;
  28483. }
  28484. // Loop : 1 indice triplet = 1 facet
  28485. var nbFaces = indices.length / 3;
  28486. for (index = 0; index < nbFaces; index++) {
  28487. // get the indexes of the coordinates of each vertex of the facet
  28488. v1x = indices[index * 3] * 3;
  28489. v1y = v1x + 1;
  28490. v1z = v1x + 2;
  28491. v2x = indices[index * 3 + 1] * 3;
  28492. v2y = v2x + 1;
  28493. v2z = v2x + 2;
  28494. v3x = indices[index * 3 + 2] * 3;
  28495. v3y = v3x + 1;
  28496. v3z = v3x + 2;
  28497. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  28498. p1p2y = positions[v1y] - positions[v2y];
  28499. p1p2z = positions[v1z] - positions[v2z];
  28500. p3p2x = positions[v3x] - positions[v2x];
  28501. p3p2y = positions[v3y] - positions[v2y];
  28502. p3p2z = positions[v3z] - positions[v2z];
  28503. // compute the face normal with the cross product
  28504. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  28505. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  28506. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  28507. // normalize this normal and store it in the array facetData
  28508. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28509. length = (length === 0) ? 1.0 : length;
  28510. faceNormalx /= length;
  28511. faceNormaly /= length;
  28512. faceNormalz /= length;
  28513. if (computeFacetNormals) {
  28514. options.facetNormals[index].x = faceNormalx;
  28515. options.facetNormals[index].y = faceNormaly;
  28516. options.facetNormals[index].z = faceNormalz;
  28517. }
  28518. if (computeFacetPositions) {
  28519. // compute and the facet barycenter coordinates in the array facetPositions
  28520. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  28521. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  28522. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  28523. }
  28524. if (computeFacetPartitioning) {
  28525. // store the facet indexes in arrays in the main facetPartitioning array :
  28526. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  28527. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28528. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28529. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28530. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28531. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28532. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28533. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28534. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28535. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28536. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28537. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28538. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28539. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  28540. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  28541. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  28542. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  28543. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  28544. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  28545. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  28546. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  28547. // push each facet index in each block containing the vertex
  28548. options.facetPartitioning[block_idx_v1].push(index);
  28549. if (block_idx_v2 != block_idx_v1) {
  28550. options.facetPartitioning[block_idx_v2].push(index);
  28551. }
  28552. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  28553. options.facetPartitioning[block_idx_v3].push(index);
  28554. }
  28555. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  28556. options.facetPartitioning[block_idx_o].push(index);
  28557. }
  28558. }
  28559. // compute the normals anyway
  28560. normals[v1x] += faceNormalx; // accumulate all the normals per face
  28561. normals[v1y] += faceNormaly;
  28562. normals[v1z] += faceNormalz;
  28563. normals[v2x] += faceNormalx;
  28564. normals[v2y] += faceNormaly;
  28565. normals[v2z] += faceNormalz;
  28566. normals[v3x] += faceNormalx;
  28567. normals[v3y] += faceNormaly;
  28568. normals[v3z] += faceNormalz;
  28569. }
  28570. // last normalization of each normal
  28571. for (index = 0; index < normals.length / 3; index++) {
  28572. faceNormalx = normals[index * 3];
  28573. faceNormaly = normals[index * 3 + 1];
  28574. faceNormalz = normals[index * 3 + 2];
  28575. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28576. length = (length === 0) ? 1.0 : length;
  28577. faceNormalx /= length;
  28578. faceNormaly /= length;
  28579. faceNormalz /= length;
  28580. normals[index * 3] = faceNormalx;
  28581. normals[index * 3 + 1] = faceNormaly;
  28582. normals[index * 3 + 2] = faceNormalz;
  28583. }
  28584. };
  28585. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  28586. var li = indices.length;
  28587. var ln = normals.length;
  28588. var i;
  28589. var n;
  28590. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28591. switch (sideOrientation) {
  28592. case BABYLON.Mesh.FRONTSIDE:
  28593. // nothing changed
  28594. break;
  28595. case BABYLON.Mesh.BACKSIDE:
  28596. var tmp;
  28597. // indices
  28598. for (i = 0; i < li; i += 3) {
  28599. tmp = indices[i];
  28600. indices[i] = indices[i + 2];
  28601. indices[i + 2] = tmp;
  28602. }
  28603. // normals
  28604. for (n = 0; n < ln; n++) {
  28605. normals[n] = -normals[n];
  28606. }
  28607. break;
  28608. case BABYLON.Mesh.DOUBLESIDE:
  28609. // positions
  28610. var lp = positions.length;
  28611. var l = lp / 3;
  28612. for (var p = 0; p < lp; p++) {
  28613. positions[lp + p] = positions[p];
  28614. }
  28615. // indices
  28616. for (i = 0; i < li; i += 3) {
  28617. indices[i + li] = indices[i + 2] + l;
  28618. indices[i + 1 + li] = indices[i + 1] + l;
  28619. indices[i + 2 + li] = indices[i] + l;
  28620. }
  28621. // normals
  28622. for (n = 0; n < ln; n++) {
  28623. normals[ln + n] = -normals[n];
  28624. }
  28625. // uvs
  28626. var lu = uvs.length;
  28627. var u = 0;
  28628. for (u = 0; u < lu; u++) {
  28629. uvs[u + lu] = uvs[u];
  28630. }
  28631. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28632. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28633. u = 0;
  28634. for (i = 0; i < lu / 2; i++) {
  28635. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  28636. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  28637. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  28638. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  28639. u += 2;
  28640. }
  28641. break;
  28642. }
  28643. };
  28644. /**
  28645. * Creates a new VertexData from the imported parameters.
  28646. */
  28647. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  28648. var vertexData = new VertexData();
  28649. // positions
  28650. var positions = parsedVertexData.positions;
  28651. if (positions) {
  28652. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  28653. }
  28654. // normals
  28655. var normals = parsedVertexData.normals;
  28656. if (normals) {
  28657. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  28658. }
  28659. // tangents
  28660. var tangents = parsedVertexData.tangents;
  28661. if (tangents) {
  28662. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  28663. }
  28664. // uvs
  28665. var uvs = parsedVertexData.uvs;
  28666. if (uvs) {
  28667. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  28668. }
  28669. // uv2s
  28670. var uv2s = parsedVertexData.uv2s;
  28671. if (uv2s) {
  28672. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  28673. }
  28674. // uv3s
  28675. var uv3s = parsedVertexData.uv3s;
  28676. if (uv3s) {
  28677. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  28678. }
  28679. // uv4s
  28680. var uv4s = parsedVertexData.uv4s;
  28681. if (uv4s) {
  28682. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  28683. }
  28684. // uv5s
  28685. var uv5s = parsedVertexData.uv5s;
  28686. if (uv5s) {
  28687. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  28688. }
  28689. // uv6s
  28690. var uv6s = parsedVertexData.uv6s;
  28691. if (uv6s) {
  28692. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  28693. }
  28694. // colors
  28695. var colors = parsedVertexData.colors;
  28696. if (colors) {
  28697. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  28698. }
  28699. // matricesIndices
  28700. var matricesIndices = parsedVertexData.matricesIndices;
  28701. if (matricesIndices) {
  28702. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  28703. }
  28704. // matricesWeights
  28705. var matricesWeights = parsedVertexData.matricesWeights;
  28706. if (matricesWeights) {
  28707. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  28708. }
  28709. // indices
  28710. var indices = parsedVertexData.indices;
  28711. if (indices) {
  28712. vertexData.indices = indices;
  28713. }
  28714. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  28715. };
  28716. return VertexData;
  28717. }());
  28718. BABYLON.VertexData = VertexData;
  28719. })(BABYLON || (BABYLON = {}));
  28720. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  28721. var BABYLON;
  28722. (function (BABYLON) {
  28723. var Geometry = (function () {
  28724. function Geometry(id, scene, vertexData, updatable, mesh) {
  28725. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28726. this._totalVertices = 0;
  28727. this._isDisposed = false;
  28728. this.id = id;
  28729. this._engine = scene.getEngine();
  28730. this._meshes = [];
  28731. this._scene = scene;
  28732. //Init vertex buffer cache
  28733. this._vertexBuffers = {};
  28734. this._indices = [];
  28735. this._updatable = updatable;
  28736. // vertexData
  28737. if (vertexData) {
  28738. this.setAllVerticesData(vertexData, updatable);
  28739. }
  28740. else {
  28741. this._totalVertices = 0;
  28742. this._indices = [];
  28743. }
  28744. if (this._engine.getCaps().vertexArrayObject) {
  28745. this._vertexArrayObjects = {};
  28746. }
  28747. // applyToMesh
  28748. if (mesh) {
  28749. if (mesh.getClassName() === "LinesMesh") {
  28750. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  28751. this.updateExtend();
  28752. }
  28753. this.applyToMesh(mesh);
  28754. mesh.computeWorldMatrix(true);
  28755. }
  28756. }
  28757. Object.defineProperty(Geometry.prototype, "boundingBias", {
  28758. /**
  28759. * 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
  28760. * @returns The Bias Vector
  28761. */
  28762. get: function () {
  28763. return this._boundingBias;
  28764. },
  28765. set: function (value) {
  28766. if (this._boundingBias && this._boundingBias.equals(value)) {
  28767. return;
  28768. }
  28769. this._boundingBias = value.clone();
  28770. this.updateBoundingInfo(true, null);
  28771. },
  28772. enumerable: true,
  28773. configurable: true
  28774. });
  28775. Object.defineProperty(Geometry.prototype, "extend", {
  28776. get: function () {
  28777. return this._extend;
  28778. },
  28779. enumerable: true,
  28780. configurable: true
  28781. });
  28782. Geometry.prototype.getScene = function () {
  28783. return this._scene;
  28784. };
  28785. Geometry.prototype.getEngine = function () {
  28786. return this._engine;
  28787. };
  28788. Geometry.prototype.isReady = function () {
  28789. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28790. };
  28791. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  28792. get: function () {
  28793. for (var index = 0; index < this._meshes.length; index++) {
  28794. if (!this._meshes[index].doNotSerialize) {
  28795. return false;
  28796. }
  28797. }
  28798. return true;
  28799. },
  28800. enumerable: true,
  28801. configurable: true
  28802. });
  28803. Geometry.prototype._rebuild = function () {
  28804. if (this._vertexArrayObjects) {
  28805. this._vertexArrayObjects = {};
  28806. }
  28807. // Index buffer
  28808. if (this._meshes.length !== 0 && this._indices) {
  28809. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28810. }
  28811. // Vertex buffers
  28812. for (var key in this._vertexBuffers) {
  28813. var vertexBuffer = this._vertexBuffers[key];
  28814. vertexBuffer._rebuild();
  28815. }
  28816. };
  28817. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28818. vertexData.applyToGeometry(this, updatable);
  28819. this.notifyUpdate();
  28820. };
  28821. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28822. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28823. this.setVerticesBuffer(buffer);
  28824. };
  28825. Geometry.prototype.removeVerticesData = function (kind) {
  28826. if (this._vertexBuffers[kind]) {
  28827. this._vertexBuffers[kind].dispose();
  28828. delete this._vertexBuffers[kind];
  28829. }
  28830. };
  28831. Geometry.prototype.setVerticesBuffer = function (buffer) {
  28832. var kind = buffer.getKind();
  28833. if (this._vertexBuffers[kind]) {
  28834. this._vertexBuffers[kind].dispose();
  28835. }
  28836. this._vertexBuffers[kind] = buffer;
  28837. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28838. var data = buffer.getData();
  28839. var stride = buffer.getStrideSize();
  28840. this._totalVertices = data.length / stride;
  28841. this.updateExtend(data, stride);
  28842. this._resetPointsArrayCache();
  28843. var meshes = this._meshes;
  28844. var numOfMeshes = meshes.length;
  28845. for (var index = 0; index < numOfMeshes; index++) {
  28846. var mesh = meshes[index];
  28847. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28848. mesh._createGlobalSubMesh(false);
  28849. mesh.computeWorldMatrix(true);
  28850. }
  28851. }
  28852. this.notifyUpdate(kind);
  28853. if (this._vertexArrayObjects) {
  28854. this._disposeVertexArrayObjects();
  28855. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  28856. }
  28857. };
  28858. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28859. var vertexBuffer = this.getVertexBuffer(kind);
  28860. if (!vertexBuffer) {
  28861. return;
  28862. }
  28863. vertexBuffer.updateDirectly(data, offset);
  28864. this.notifyUpdate(kind);
  28865. };
  28866. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28867. var vertexBuffer = this.getVertexBuffer(kind);
  28868. if (!vertexBuffer) {
  28869. return;
  28870. }
  28871. vertexBuffer.update(data);
  28872. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28873. var stride = vertexBuffer.getStrideSize();
  28874. this._totalVertices = data.length / stride;
  28875. this.updateBoundingInfo(updateExtends, data);
  28876. }
  28877. this.notifyUpdate(kind);
  28878. };
  28879. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  28880. if (updateExtends) {
  28881. this.updateExtend(data);
  28882. }
  28883. var meshes = this._meshes;
  28884. var numOfMeshes = meshes.length;
  28885. this._resetPointsArrayCache();
  28886. for (var index = 0; index < numOfMeshes; index++) {
  28887. var mesh = meshes[index];
  28888. if (updateExtends) {
  28889. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28890. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28891. var subMesh = mesh.subMeshes[subIndex];
  28892. subMesh.refreshBoundingInfo();
  28893. }
  28894. }
  28895. }
  28896. };
  28897. Geometry.prototype._bind = function (effect, indexToBind) {
  28898. if (indexToBind === void 0) { indexToBind = undefined; }
  28899. if (indexToBind === undefined) {
  28900. indexToBind = this._indexBuffer;
  28901. }
  28902. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  28903. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  28904. return;
  28905. }
  28906. // Using VAO
  28907. if (!this._vertexArrayObjects[effect.key]) {
  28908. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  28909. }
  28910. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  28911. };
  28912. Geometry.prototype.getTotalVertices = function () {
  28913. if (!this.isReady()) {
  28914. return 0;
  28915. }
  28916. return this._totalVertices;
  28917. };
  28918. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28919. var vertexBuffer = this.getVertexBuffer(kind);
  28920. if (!vertexBuffer) {
  28921. return null;
  28922. }
  28923. var orig = vertexBuffer.getData();
  28924. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  28925. return orig;
  28926. }
  28927. else {
  28928. var len = orig.length;
  28929. var copy = [];
  28930. for (var i = 0; i < len; i++) {
  28931. copy.push(orig[i]);
  28932. }
  28933. return copy;
  28934. }
  28935. };
  28936. Geometry.prototype.getVertexBuffer = function (kind) {
  28937. if (!this.isReady()) {
  28938. return null;
  28939. }
  28940. return this._vertexBuffers[kind];
  28941. };
  28942. Geometry.prototype.getVertexBuffers = function () {
  28943. if (!this.isReady()) {
  28944. return null;
  28945. }
  28946. return this._vertexBuffers;
  28947. };
  28948. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28949. if (!this._vertexBuffers) {
  28950. if (this._delayInfo) {
  28951. return this._delayInfo.indexOf(kind) !== -1;
  28952. }
  28953. return false;
  28954. }
  28955. return this._vertexBuffers[kind] !== undefined;
  28956. };
  28957. Geometry.prototype.getVerticesDataKinds = function () {
  28958. var result = [];
  28959. var kind;
  28960. if (!this._vertexBuffers && this._delayInfo) {
  28961. for (kind in this._delayInfo) {
  28962. result.push(kind);
  28963. }
  28964. }
  28965. else {
  28966. for (kind in this._vertexBuffers) {
  28967. result.push(kind);
  28968. }
  28969. }
  28970. return result;
  28971. };
  28972. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28973. if (this._indexBuffer) {
  28974. this._engine._releaseBuffer(this._indexBuffer);
  28975. }
  28976. this._disposeVertexArrayObjects();
  28977. this._indices = indices;
  28978. if (this._meshes.length !== 0 && this._indices) {
  28979. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28980. }
  28981. if (totalVertices !== undefined) {
  28982. this._totalVertices = totalVertices;
  28983. }
  28984. var meshes = this._meshes;
  28985. var numOfMeshes = meshes.length;
  28986. for (var index = 0; index < numOfMeshes; index++) {
  28987. meshes[index]._createGlobalSubMesh(true);
  28988. }
  28989. this.notifyUpdate();
  28990. };
  28991. Geometry.prototype.getTotalIndices = function () {
  28992. if (!this.isReady()) {
  28993. return 0;
  28994. }
  28995. return this._indices.length;
  28996. };
  28997. Geometry.prototype.getIndices = function (copyWhenShared) {
  28998. if (!this.isReady()) {
  28999. return null;
  29000. }
  29001. var orig = this._indices;
  29002. if (!copyWhenShared || this._meshes.length === 1) {
  29003. return orig;
  29004. }
  29005. else {
  29006. var len = orig.length;
  29007. var copy = [];
  29008. for (var i = 0; i < len; i++) {
  29009. copy.push(orig[i]);
  29010. }
  29011. return copy;
  29012. }
  29013. };
  29014. Geometry.prototype.getIndexBuffer = function () {
  29015. if (!this.isReady()) {
  29016. return null;
  29017. }
  29018. return this._indexBuffer;
  29019. };
  29020. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  29021. if (!effect || !this._vertexArrayObjects) {
  29022. return;
  29023. }
  29024. if (this._vertexArrayObjects[effect.key]) {
  29025. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  29026. delete this._vertexArrayObjects[effect.key];
  29027. }
  29028. };
  29029. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  29030. var meshes = this._meshes;
  29031. var index = meshes.indexOf(mesh);
  29032. if (index === -1) {
  29033. return;
  29034. }
  29035. meshes.splice(index, 1);
  29036. mesh._geometry = null;
  29037. if (meshes.length === 0 && shouldDispose) {
  29038. this.dispose();
  29039. }
  29040. };
  29041. Geometry.prototype.applyToMesh = function (mesh) {
  29042. if (mesh._geometry === this) {
  29043. return;
  29044. }
  29045. var previousGeometry = mesh._geometry;
  29046. if (previousGeometry) {
  29047. previousGeometry.releaseForMesh(mesh);
  29048. }
  29049. var meshes = this._meshes;
  29050. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  29051. mesh._geometry = this;
  29052. this._scene.pushGeometry(this);
  29053. meshes.push(mesh);
  29054. if (this.isReady()) {
  29055. this._applyToMesh(mesh);
  29056. }
  29057. else {
  29058. mesh._boundingInfo = this._boundingInfo;
  29059. }
  29060. };
  29061. Geometry.prototype.updateExtend = function (data, stride) {
  29062. if (data === void 0) { data = null; }
  29063. if (!data) {
  29064. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  29065. }
  29066. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  29067. };
  29068. Geometry.prototype._applyToMesh = function (mesh) {
  29069. var numOfMeshes = this._meshes.length;
  29070. // vertexBuffers
  29071. for (var kind in this._vertexBuffers) {
  29072. if (numOfMeshes === 1) {
  29073. this._vertexBuffers[kind].create();
  29074. }
  29075. var buffer = this._vertexBuffers[kind].getBuffer();
  29076. if (buffer)
  29077. buffer.references = numOfMeshes;
  29078. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29079. if (!this._extend) {
  29080. this.updateExtend(this._vertexBuffers[kind].getData());
  29081. }
  29082. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29083. mesh._createGlobalSubMesh(false);
  29084. //bounding info was just created again, world matrix should be applied again.
  29085. mesh._updateBoundingInfo();
  29086. }
  29087. }
  29088. // indexBuffer
  29089. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  29090. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29091. }
  29092. if (this._indexBuffer) {
  29093. this._indexBuffer.references = numOfMeshes;
  29094. }
  29095. };
  29096. Geometry.prototype.notifyUpdate = function (kind) {
  29097. if (this.onGeometryUpdated) {
  29098. this.onGeometryUpdated(this, kind);
  29099. }
  29100. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  29101. var mesh = _a[_i];
  29102. mesh._markSubMeshesAsAttributesDirty();
  29103. }
  29104. };
  29105. Geometry.prototype.load = function (scene, onLoaded) {
  29106. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29107. return;
  29108. }
  29109. if (this.isReady()) {
  29110. if (onLoaded) {
  29111. onLoaded();
  29112. }
  29113. return;
  29114. }
  29115. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29116. this._queueLoad(scene, onLoaded);
  29117. };
  29118. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  29119. var _this = this;
  29120. scene._addPendingData(this);
  29121. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29122. _this._delayLoadingFunction(JSON.parse(data), _this);
  29123. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29124. _this._delayInfo = [];
  29125. scene._removePendingData(_this);
  29126. var meshes = _this._meshes;
  29127. var numOfMeshes = meshes.length;
  29128. for (var index = 0; index < numOfMeshes; index++) {
  29129. _this._applyToMesh(meshes[index]);
  29130. }
  29131. if (onLoaded) {
  29132. onLoaded();
  29133. }
  29134. }, function () { }, scene.database);
  29135. };
  29136. /**
  29137. * Invert the geometry to move from a right handed system to a left handed one.
  29138. */
  29139. Geometry.prototype.toLeftHanded = function () {
  29140. // Flip faces
  29141. var tIndices = this.getIndices(false);
  29142. if (tIndices != null && tIndices.length > 0) {
  29143. for (var i = 0; i < tIndices.length; i += 3) {
  29144. var tTemp = tIndices[i + 0];
  29145. tIndices[i + 0] = tIndices[i + 2];
  29146. tIndices[i + 2] = tTemp;
  29147. }
  29148. this.setIndices(tIndices);
  29149. }
  29150. // Negate position.z
  29151. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  29152. if (tPositions != null && tPositions.length > 0) {
  29153. for (var i = 0; i < tPositions.length; i += 3) {
  29154. tPositions[i + 2] = -tPositions[i + 2];
  29155. }
  29156. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  29157. }
  29158. // Negate normal.z
  29159. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  29160. if (tNormals != null && tNormals.length > 0) {
  29161. for (var i = 0; i < tNormals.length; i += 3) {
  29162. tNormals[i + 2] = -tNormals[i + 2];
  29163. }
  29164. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  29165. }
  29166. };
  29167. // Cache
  29168. Geometry.prototype._resetPointsArrayCache = function () {
  29169. this._positions = null;
  29170. };
  29171. Geometry.prototype._generatePointsArray = function () {
  29172. if (this._positions)
  29173. return true;
  29174. this._positions = [];
  29175. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29176. if (!data) {
  29177. return false;
  29178. }
  29179. for (var index = 0; index < data.length; index += 3) {
  29180. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  29181. }
  29182. return true;
  29183. };
  29184. Geometry.prototype.isDisposed = function () {
  29185. return this._isDisposed;
  29186. };
  29187. Geometry.prototype._disposeVertexArrayObjects = function () {
  29188. if (this._vertexArrayObjects) {
  29189. for (var kind in this._vertexArrayObjects) {
  29190. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  29191. }
  29192. this._vertexArrayObjects = {};
  29193. }
  29194. };
  29195. Geometry.prototype.dispose = function () {
  29196. var meshes = this._meshes;
  29197. var numOfMeshes = meshes.length;
  29198. var index;
  29199. for (index = 0; index < numOfMeshes; index++) {
  29200. this.releaseForMesh(meshes[index]);
  29201. }
  29202. this._meshes = [];
  29203. this._disposeVertexArrayObjects();
  29204. for (var kind in this._vertexBuffers) {
  29205. this._vertexBuffers[kind].dispose();
  29206. }
  29207. this._vertexBuffers = {};
  29208. this._totalVertices = 0;
  29209. if (this._indexBuffer) {
  29210. this._engine._releaseBuffer(this._indexBuffer);
  29211. }
  29212. this._indexBuffer = null;
  29213. this._indices = [];
  29214. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29215. this.delayLoadingFile = null;
  29216. this._delayLoadingFunction = null;
  29217. this._delayInfo = [];
  29218. this._boundingInfo = null;
  29219. this._scene.removeGeometry(this);
  29220. this._isDisposed = true;
  29221. };
  29222. Geometry.prototype.copy = function (id) {
  29223. var vertexData = new BABYLON.VertexData();
  29224. vertexData.indices = [];
  29225. var indices = this.getIndices();
  29226. for (var index = 0; index < indices.length; index++) {
  29227. vertexData.indices.push(indices[index]);
  29228. }
  29229. var updatable = false;
  29230. var stopChecking = false;
  29231. var kind;
  29232. for (kind in this._vertexBuffers) {
  29233. // using slice() to make a copy of the array and not just reference it
  29234. var data = this.getVerticesData(kind);
  29235. if (data instanceof Float32Array) {
  29236. vertexData.set(new Float32Array(data), kind);
  29237. }
  29238. else {
  29239. vertexData.set(data.slice(0), kind);
  29240. }
  29241. if (!stopChecking) {
  29242. updatable = this.getVertexBuffer(kind).isUpdatable();
  29243. stopChecking = !updatable;
  29244. }
  29245. }
  29246. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  29247. geometry.delayLoadState = this.delayLoadState;
  29248. geometry.delayLoadingFile = this.delayLoadingFile;
  29249. geometry._delayLoadingFunction = this._delayLoadingFunction;
  29250. for (kind in this._delayInfo) {
  29251. geometry._delayInfo = geometry._delayInfo || [];
  29252. geometry._delayInfo.push(kind);
  29253. }
  29254. // Bounding info
  29255. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29256. return geometry;
  29257. };
  29258. Geometry.prototype.serialize = function () {
  29259. var serializationObject = {};
  29260. serializationObject.id = this.id;
  29261. serializationObject.updatable = this._updatable;
  29262. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29263. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29264. }
  29265. return serializationObject;
  29266. };
  29267. Geometry.prototype.toNumberArray = function (origin) {
  29268. if (Array.isArray(origin)) {
  29269. return origin;
  29270. }
  29271. else {
  29272. return Array.prototype.slice.call(origin);
  29273. }
  29274. };
  29275. Geometry.prototype.serializeVerticeData = function () {
  29276. var serializationObject = this.serialize();
  29277. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29278. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  29279. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  29280. serializationObject.positions._updatable = true;
  29281. }
  29282. }
  29283. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29284. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  29285. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  29286. serializationObject.normals._updatable = true;
  29287. }
  29288. }
  29289. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29290. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  29291. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  29292. serializationObject.uvs._updatable = true;
  29293. }
  29294. }
  29295. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29296. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  29297. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  29298. serializationObject.uv2s._updatable = true;
  29299. }
  29300. }
  29301. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29302. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  29303. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  29304. serializationObject.uv3s._updatable = true;
  29305. }
  29306. }
  29307. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29308. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  29309. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  29310. serializationObject.uv4s._updatable = true;
  29311. }
  29312. }
  29313. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29314. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  29315. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  29316. serializationObject.uv5s._updatable = true;
  29317. }
  29318. }
  29319. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29320. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  29321. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  29322. serializationObject.uv6s._updatable = true;
  29323. }
  29324. }
  29325. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29326. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  29327. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  29328. serializationObject.colors._updatable = true;
  29329. }
  29330. }
  29331. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29332. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  29333. serializationObject.matricesIndices._isExpanded = true;
  29334. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  29335. serializationObject.matricesIndices._updatable = true;
  29336. }
  29337. }
  29338. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29339. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  29340. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  29341. serializationObject.matricesWeights._updatable = true;
  29342. }
  29343. }
  29344. serializationObject.indices = this.toNumberArray(this.getIndices());
  29345. return serializationObject;
  29346. };
  29347. // Statics
  29348. Geometry.ExtractFromMesh = function (mesh, id) {
  29349. var geometry = mesh._geometry;
  29350. if (!geometry) {
  29351. return null;
  29352. }
  29353. return geometry.copy(id);
  29354. };
  29355. /**
  29356. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  29357. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  29358. * Be aware Math.random() could cause collisions, but:
  29359. * "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"
  29360. */
  29361. Geometry.RandomId = function () {
  29362. return BABYLON.Tools.RandomId();
  29363. };
  29364. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  29365. var scene = mesh.getScene();
  29366. // Geometry
  29367. var geometryId = parsedGeometry.geometryId;
  29368. if (geometryId) {
  29369. var geometry = scene.getGeometryByID(geometryId);
  29370. if (geometry) {
  29371. geometry.applyToMesh(mesh);
  29372. }
  29373. }
  29374. else if (parsedGeometry instanceof ArrayBuffer) {
  29375. var binaryInfo = mesh._binaryInfo;
  29376. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  29377. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  29378. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  29379. }
  29380. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  29381. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  29382. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  29383. }
  29384. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  29385. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  29386. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  29387. }
  29388. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  29389. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  29390. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  29391. }
  29392. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  29393. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  29394. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  29395. }
  29396. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  29397. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  29398. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  29399. }
  29400. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  29401. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  29402. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  29403. }
  29404. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  29405. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  29406. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  29407. }
  29408. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  29409. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  29410. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  29411. }
  29412. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  29413. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  29414. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  29415. }
  29416. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  29417. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  29418. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  29419. }
  29420. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  29421. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  29422. mesh.setIndices(indicesData);
  29423. }
  29424. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  29425. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  29426. mesh.subMeshes = [];
  29427. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  29428. var materialIndex = subMeshesData[(i * 5) + 0];
  29429. var verticesStart = subMeshesData[(i * 5) + 1];
  29430. var verticesCount = subMeshesData[(i * 5) + 2];
  29431. var indexStart = subMeshesData[(i * 5) + 3];
  29432. var indexCount = subMeshesData[(i * 5) + 4];
  29433. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  29434. }
  29435. }
  29436. }
  29437. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  29438. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  29439. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  29440. if (parsedGeometry.uvs) {
  29441. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  29442. }
  29443. if (parsedGeometry.uvs2) {
  29444. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  29445. }
  29446. if (parsedGeometry.uvs3) {
  29447. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  29448. }
  29449. if (parsedGeometry.uvs4) {
  29450. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  29451. }
  29452. if (parsedGeometry.uvs5) {
  29453. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  29454. }
  29455. if (parsedGeometry.uvs6) {
  29456. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  29457. }
  29458. if (parsedGeometry.colors) {
  29459. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  29460. }
  29461. if (parsedGeometry.matricesIndices) {
  29462. if (!parsedGeometry.matricesIndices._isExpanded) {
  29463. var floatIndices = [];
  29464. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  29465. var matricesIndex = parsedGeometry.matricesIndices[i];
  29466. floatIndices.push(matricesIndex & 0x000000FF);
  29467. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29468. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29469. floatIndices.push(matricesIndex >> 24);
  29470. }
  29471. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  29472. }
  29473. else {
  29474. delete parsedGeometry.matricesIndices._isExpanded;
  29475. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  29476. }
  29477. }
  29478. if (parsedGeometry.matricesIndicesExtra) {
  29479. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  29480. var floatIndices = [];
  29481. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  29482. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  29483. floatIndices.push(matricesIndex & 0x000000FF);
  29484. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29485. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29486. floatIndices.push(matricesIndex >> 24);
  29487. }
  29488. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  29489. }
  29490. else {
  29491. delete parsedGeometry.matricesIndices._isExpanded;
  29492. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  29493. }
  29494. }
  29495. if (parsedGeometry.matricesWeights) {
  29496. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeights, parsedGeometry.numBoneInfluencers);
  29497. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  29498. }
  29499. if (parsedGeometry.matricesWeightsExtra) {
  29500. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeightsExtra, parsedGeometry.numBoneInfluencers);
  29501. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  29502. }
  29503. mesh.setIndices(parsedGeometry.indices);
  29504. }
  29505. // SubMeshes
  29506. if (parsedGeometry.subMeshes) {
  29507. mesh.subMeshes = [];
  29508. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  29509. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  29510. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  29511. }
  29512. }
  29513. // Flat shading
  29514. if (mesh._shouldGenerateFlatShading) {
  29515. mesh.convertToFlatShadedMesh();
  29516. delete mesh._shouldGenerateFlatShading;
  29517. }
  29518. // Update
  29519. mesh.computeWorldMatrix(true);
  29520. // Octree
  29521. if (scene['_selectionOctree']) {
  29522. scene['_selectionOctree'].addMesh(mesh);
  29523. }
  29524. };
  29525. Geometry._CleanMatricesWeights = function (matricesWeights, influencers) {
  29526. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  29527. return;
  29528. }
  29529. var size = matricesWeights.length;
  29530. for (var i = 0; i < size; i += influencers) {
  29531. var weight = 0;
  29532. var biggerIndex = i;
  29533. var biggerWeight = 0;
  29534. for (var j = 0; j < influencers - 1; j++) {
  29535. weight += matricesWeights[i + j];
  29536. if (matricesWeights[i + j] > biggerWeight) {
  29537. biggerWeight = matricesWeights[i + j];
  29538. biggerIndex = i + j;
  29539. }
  29540. }
  29541. matricesWeights[biggerIndex] += Math.max(0, 1.0 - weight);
  29542. }
  29543. };
  29544. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  29545. if (scene.getGeometryByID(parsedVertexData.id)) {
  29546. return null; // null since geometry could be something else than a box...
  29547. }
  29548. var geometry = new Geometry(parsedVertexData.id, scene, null, parsedVertexData.updatable);
  29549. if (BABYLON.Tags) {
  29550. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  29551. }
  29552. if (parsedVertexData.delayLoadingFile) {
  29553. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29554. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  29555. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  29556. geometry._delayInfo = [];
  29557. if (parsedVertexData.hasUVs) {
  29558. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29559. }
  29560. if (parsedVertexData.hasUVs2) {
  29561. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29562. }
  29563. if (parsedVertexData.hasUVs3) {
  29564. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29565. }
  29566. if (parsedVertexData.hasUVs4) {
  29567. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29568. }
  29569. if (parsedVertexData.hasUVs5) {
  29570. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29571. }
  29572. if (parsedVertexData.hasUVs6) {
  29573. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29574. }
  29575. if (parsedVertexData.hasColors) {
  29576. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29577. }
  29578. if (parsedVertexData.hasMatricesIndices) {
  29579. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29580. }
  29581. if (parsedVertexData.hasMatricesWeights) {
  29582. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29583. }
  29584. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  29585. }
  29586. else {
  29587. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  29588. }
  29589. scene.pushGeometry(geometry, true);
  29590. return geometry;
  29591. };
  29592. return Geometry;
  29593. }());
  29594. BABYLON.Geometry = Geometry;
  29595. /////// Primitives //////////////////////////////////////////////
  29596. (function (Geometry) {
  29597. var Primitives;
  29598. (function (Primitives) {
  29599. /// Abstract class
  29600. var _Primitive = (function (_super) {
  29601. __extends(_Primitive, _super);
  29602. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  29603. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  29604. _this._canBeRegenerated = _canBeRegenerated;
  29605. _this._beingRegenerated = true;
  29606. _this.regenerate();
  29607. _this._beingRegenerated = false;
  29608. return _this;
  29609. }
  29610. _Primitive.prototype.canBeRegenerated = function () {
  29611. return this._canBeRegenerated;
  29612. };
  29613. _Primitive.prototype.regenerate = function () {
  29614. if (!this._canBeRegenerated) {
  29615. return;
  29616. }
  29617. this._beingRegenerated = true;
  29618. this.setAllVerticesData(this._regenerateVertexData(), false);
  29619. this._beingRegenerated = false;
  29620. };
  29621. _Primitive.prototype.asNewGeometry = function (id) {
  29622. return _super.prototype.copy.call(this, id);
  29623. };
  29624. // overrides
  29625. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  29626. if (!this._beingRegenerated) {
  29627. return;
  29628. }
  29629. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  29630. };
  29631. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  29632. if (!this._beingRegenerated) {
  29633. return;
  29634. }
  29635. _super.prototype.setVerticesData.call(this, kind, data, false);
  29636. };
  29637. // to override
  29638. // protected
  29639. _Primitive.prototype._regenerateVertexData = function () {
  29640. throw new Error("Abstract method");
  29641. };
  29642. _Primitive.prototype.copy = function (id) {
  29643. throw new Error("Must be overriden in sub-classes.");
  29644. };
  29645. _Primitive.prototype.serialize = function () {
  29646. var serializationObject = _super.prototype.serialize.call(this);
  29647. serializationObject.canBeRegenerated = this.canBeRegenerated();
  29648. return serializationObject;
  29649. };
  29650. return _Primitive;
  29651. }(Geometry));
  29652. Primitives._Primitive = _Primitive;
  29653. var Ribbon = (function (_super) {
  29654. __extends(Ribbon, _super);
  29655. // Members
  29656. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  29657. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29658. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29659. _this.pathArray = pathArray;
  29660. _this.closeArray = closeArray;
  29661. _this.closePath = closePath;
  29662. _this.offset = offset;
  29663. _this.side = side;
  29664. return _this;
  29665. }
  29666. Ribbon.prototype._regenerateVertexData = function () {
  29667. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  29668. };
  29669. Ribbon.prototype.copy = function (id) {
  29670. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  29671. };
  29672. return Ribbon;
  29673. }(_Primitive));
  29674. Primitives.Ribbon = Ribbon;
  29675. var Box = (function (_super) {
  29676. __extends(Box, _super);
  29677. // Members
  29678. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  29679. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29680. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29681. _this.size = size;
  29682. _this.side = side;
  29683. return _this;
  29684. }
  29685. Box.prototype._regenerateVertexData = function () {
  29686. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  29687. };
  29688. Box.prototype.copy = function (id) {
  29689. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29690. };
  29691. Box.prototype.serialize = function () {
  29692. var serializationObject = _super.prototype.serialize.call(this);
  29693. serializationObject.size = this.size;
  29694. return serializationObject;
  29695. };
  29696. Box.Parse = function (parsedBox, scene) {
  29697. if (scene.getGeometryByID(parsedBox.id)) {
  29698. return null; // null since geometry could be something else than a box...
  29699. }
  29700. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  29701. if (BABYLON.Tags) {
  29702. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  29703. }
  29704. scene.pushGeometry(box, true);
  29705. return box;
  29706. };
  29707. return Box;
  29708. }(_Primitive));
  29709. Primitives.Box = Box;
  29710. var Sphere = (function (_super) {
  29711. __extends(Sphere, _super);
  29712. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  29713. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29714. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29715. _this.segments = segments;
  29716. _this.diameter = diameter;
  29717. _this.side = side;
  29718. return _this;
  29719. }
  29720. Sphere.prototype._regenerateVertexData = function () {
  29721. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  29722. };
  29723. Sphere.prototype.copy = function (id) {
  29724. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  29725. };
  29726. Sphere.prototype.serialize = function () {
  29727. var serializationObject = _super.prototype.serialize.call(this);
  29728. serializationObject.segments = this.segments;
  29729. serializationObject.diameter = this.diameter;
  29730. return serializationObject;
  29731. };
  29732. Sphere.Parse = function (parsedSphere, scene) {
  29733. if (scene.getGeometryByID(parsedSphere.id)) {
  29734. return null; // null since geometry could be something else than a sphere...
  29735. }
  29736. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  29737. if (BABYLON.Tags) {
  29738. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  29739. }
  29740. scene.pushGeometry(sphere, true);
  29741. return sphere;
  29742. };
  29743. return Sphere;
  29744. }(_Primitive));
  29745. Primitives.Sphere = Sphere;
  29746. var Disc = (function (_super) {
  29747. __extends(Disc, _super);
  29748. // Members
  29749. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  29750. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29751. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29752. _this.radius = radius;
  29753. _this.tessellation = tessellation;
  29754. _this.side = side;
  29755. return _this;
  29756. }
  29757. Disc.prototype._regenerateVertexData = function () {
  29758. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  29759. };
  29760. Disc.prototype.copy = function (id) {
  29761. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  29762. };
  29763. return Disc;
  29764. }(_Primitive));
  29765. Primitives.Disc = Disc;
  29766. var Cylinder = (function (_super) {
  29767. __extends(Cylinder, _super);
  29768. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  29769. if (subdivisions === void 0) { subdivisions = 1; }
  29770. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29771. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29772. _this.height = height;
  29773. _this.diameterTop = diameterTop;
  29774. _this.diameterBottom = diameterBottom;
  29775. _this.tessellation = tessellation;
  29776. _this.subdivisions = subdivisions;
  29777. _this.side = side;
  29778. return _this;
  29779. }
  29780. Cylinder.prototype._regenerateVertexData = function () {
  29781. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  29782. };
  29783. Cylinder.prototype.copy = function (id) {
  29784. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  29785. };
  29786. Cylinder.prototype.serialize = function () {
  29787. var serializationObject = _super.prototype.serialize.call(this);
  29788. serializationObject.height = this.height;
  29789. serializationObject.diameterTop = this.diameterTop;
  29790. serializationObject.diameterBottom = this.diameterBottom;
  29791. serializationObject.tessellation = this.tessellation;
  29792. return serializationObject;
  29793. };
  29794. Cylinder.Parse = function (parsedCylinder, scene) {
  29795. if (scene.getGeometryByID(parsedCylinder.id)) {
  29796. return null; // null since geometry could be something else than a cylinder...
  29797. }
  29798. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  29799. if (BABYLON.Tags) {
  29800. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  29801. }
  29802. scene.pushGeometry(cylinder, true);
  29803. return cylinder;
  29804. };
  29805. return Cylinder;
  29806. }(_Primitive));
  29807. Primitives.Cylinder = Cylinder;
  29808. var Torus = (function (_super) {
  29809. __extends(Torus, _super);
  29810. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  29811. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29812. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29813. _this.diameter = diameter;
  29814. _this.thickness = thickness;
  29815. _this.tessellation = tessellation;
  29816. _this.side = side;
  29817. return _this;
  29818. }
  29819. Torus.prototype._regenerateVertexData = function () {
  29820. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  29821. };
  29822. Torus.prototype.copy = function (id) {
  29823. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  29824. };
  29825. Torus.prototype.serialize = function () {
  29826. var serializationObject = _super.prototype.serialize.call(this);
  29827. serializationObject.diameter = this.diameter;
  29828. serializationObject.thickness = this.thickness;
  29829. serializationObject.tessellation = this.tessellation;
  29830. return serializationObject;
  29831. };
  29832. Torus.Parse = function (parsedTorus, scene) {
  29833. if (scene.getGeometryByID(parsedTorus.id)) {
  29834. return null; // null since geometry could be something else than a torus...
  29835. }
  29836. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  29837. if (BABYLON.Tags) {
  29838. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  29839. }
  29840. scene.pushGeometry(torus, true);
  29841. return torus;
  29842. };
  29843. return Torus;
  29844. }(_Primitive));
  29845. Primitives.Torus = Torus;
  29846. var Ground = (function (_super) {
  29847. __extends(Ground, _super);
  29848. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  29849. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29850. _this.width = width;
  29851. _this.height = height;
  29852. _this.subdivisions = subdivisions;
  29853. return _this;
  29854. }
  29855. Ground.prototype._regenerateVertexData = function () {
  29856. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  29857. };
  29858. Ground.prototype.copy = function (id) {
  29859. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  29860. };
  29861. Ground.prototype.serialize = function () {
  29862. var serializationObject = _super.prototype.serialize.call(this);
  29863. serializationObject.width = this.width;
  29864. serializationObject.height = this.height;
  29865. serializationObject.subdivisions = this.subdivisions;
  29866. return serializationObject;
  29867. };
  29868. Ground.Parse = function (parsedGround, scene) {
  29869. if (scene.getGeometryByID(parsedGround.id)) {
  29870. return null; // null since geometry could be something else than a ground...
  29871. }
  29872. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  29873. if (BABYLON.Tags) {
  29874. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  29875. }
  29876. scene.pushGeometry(ground, true);
  29877. return ground;
  29878. };
  29879. return Ground;
  29880. }(_Primitive));
  29881. Primitives.Ground = Ground;
  29882. var TiledGround = (function (_super) {
  29883. __extends(TiledGround, _super);
  29884. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  29885. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29886. _this.xmin = xmin;
  29887. _this.zmin = zmin;
  29888. _this.xmax = xmax;
  29889. _this.zmax = zmax;
  29890. _this.subdivisions = subdivisions;
  29891. _this.precision = precision;
  29892. return _this;
  29893. }
  29894. TiledGround.prototype._regenerateVertexData = function () {
  29895. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  29896. };
  29897. TiledGround.prototype.copy = function (id) {
  29898. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  29899. };
  29900. return TiledGround;
  29901. }(_Primitive));
  29902. Primitives.TiledGround = TiledGround;
  29903. var Plane = (function (_super) {
  29904. __extends(Plane, _super);
  29905. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  29906. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29907. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29908. _this.size = size;
  29909. _this.side = side;
  29910. return _this;
  29911. }
  29912. Plane.prototype._regenerateVertexData = function () {
  29913. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  29914. };
  29915. Plane.prototype.copy = function (id) {
  29916. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29917. };
  29918. Plane.prototype.serialize = function () {
  29919. var serializationObject = _super.prototype.serialize.call(this);
  29920. serializationObject.size = this.size;
  29921. return serializationObject;
  29922. };
  29923. Plane.Parse = function (parsedPlane, scene) {
  29924. if (scene.getGeometryByID(parsedPlane.id)) {
  29925. return null; // null since geometry could be something else than a ground...
  29926. }
  29927. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  29928. if (BABYLON.Tags) {
  29929. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  29930. }
  29931. scene.pushGeometry(plane, true);
  29932. return plane;
  29933. };
  29934. return Plane;
  29935. }(_Primitive));
  29936. Primitives.Plane = Plane;
  29937. var TorusKnot = (function (_super) {
  29938. __extends(TorusKnot, _super);
  29939. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  29940. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29941. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29942. _this.radius = radius;
  29943. _this.tube = tube;
  29944. _this.radialSegments = radialSegments;
  29945. _this.tubularSegments = tubularSegments;
  29946. _this.p = p;
  29947. _this.q = q;
  29948. _this.side = side;
  29949. return _this;
  29950. }
  29951. TorusKnot.prototype._regenerateVertexData = function () {
  29952. 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 });
  29953. };
  29954. TorusKnot.prototype.copy = function (id) {
  29955. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  29956. };
  29957. TorusKnot.prototype.serialize = function () {
  29958. var serializationObject = _super.prototype.serialize.call(this);
  29959. serializationObject.radius = this.radius;
  29960. serializationObject.tube = this.tube;
  29961. serializationObject.radialSegments = this.radialSegments;
  29962. serializationObject.tubularSegments = this.tubularSegments;
  29963. serializationObject.p = this.p;
  29964. serializationObject.q = this.q;
  29965. return serializationObject;
  29966. };
  29967. ;
  29968. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  29969. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  29970. return null; // null since geometry could be something else than a ground...
  29971. }
  29972. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  29973. if (BABYLON.Tags) {
  29974. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  29975. }
  29976. scene.pushGeometry(torusKnot, true);
  29977. return torusKnot;
  29978. };
  29979. return TorusKnot;
  29980. }(_Primitive));
  29981. Primitives.TorusKnot = TorusKnot;
  29982. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  29983. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  29984. })(BABYLON || (BABYLON = {}));
  29985. //# sourceMappingURL=babylon.geometry.js.map
  29986. var BABYLON;
  29987. (function (BABYLON) {
  29988. var PostProcessManager = (function () {
  29989. function PostProcessManager(scene) {
  29990. this._vertexBuffers = {};
  29991. this._scene = scene;
  29992. }
  29993. PostProcessManager.prototype._prepareBuffers = function () {
  29994. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29995. return;
  29996. }
  29997. // VBO
  29998. var vertices = [];
  29999. vertices.push(1, 1);
  30000. vertices.push(-1, 1);
  30001. vertices.push(-1, -1);
  30002. vertices.push(1, -1);
  30003. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  30004. this._buildIndexBuffer();
  30005. };
  30006. PostProcessManager.prototype._buildIndexBuffer = function () {
  30007. // Indices
  30008. var indices = [];
  30009. indices.push(0);
  30010. indices.push(1);
  30011. indices.push(2);
  30012. indices.push(0);
  30013. indices.push(2);
  30014. indices.push(3);
  30015. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  30016. };
  30017. PostProcessManager.prototype._rebuild = function () {
  30018. if (!this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  30019. return;
  30020. }
  30021. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  30022. this._buildIndexBuffer();
  30023. };
  30024. // Methods
  30025. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  30026. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  30027. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30028. return false;
  30029. }
  30030. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  30031. return true;
  30032. };
  30033. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  30034. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  30035. var engine = this._scene.getEngine();
  30036. for (var index = 0; index < postProcesses.length; index++) {
  30037. if (index < postProcesses.length - 1) {
  30038. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30039. }
  30040. else {
  30041. if (targetTexture) {
  30042. engine.bindFramebuffer(targetTexture, 0, null, null, forceFullscreenViewport);
  30043. }
  30044. else {
  30045. engine.restoreDefaultFramebuffer();
  30046. }
  30047. }
  30048. var pp = postProcesses[index];
  30049. var effect = pp.apply();
  30050. if (effect) {
  30051. pp.onBeforeRenderObservable.notifyObservers(effect);
  30052. // VBOs
  30053. this._prepareBuffers();
  30054. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30055. // Draw order
  30056. engine.draw(true, 0, 6);
  30057. pp.onAfterRenderObservable.notifyObservers(effect);
  30058. }
  30059. }
  30060. // Restore depth buffer
  30061. engine.setDepthBuffer(true);
  30062. engine.setDepthWrite(true);
  30063. };
  30064. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  30065. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  30066. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  30067. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30068. return;
  30069. }
  30070. var engine = this._scene.getEngine();
  30071. for (var index = 0, len = postProcesses.length; index < len; index++) {
  30072. if (index < len - 1) {
  30073. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30074. }
  30075. else {
  30076. if (targetTexture) {
  30077. engine.bindFramebuffer(targetTexture, faceIndex, null, null, forceFullscreenViewport);
  30078. }
  30079. else {
  30080. engine.restoreDefaultFramebuffer();
  30081. }
  30082. }
  30083. if (doNotPresent) {
  30084. break;
  30085. }
  30086. var pp = postProcesses[index];
  30087. var effect = pp.apply();
  30088. if (effect) {
  30089. pp.onBeforeRenderObservable.notifyObservers(effect);
  30090. // VBOs
  30091. this._prepareBuffers();
  30092. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30093. // Draw order
  30094. engine.draw(true, 0, 6);
  30095. pp.onAfterRenderObservable.notifyObservers(effect);
  30096. }
  30097. }
  30098. // Restore states
  30099. engine.setDepthBuffer(true);
  30100. engine.setDepthWrite(true);
  30101. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  30102. };
  30103. PostProcessManager.prototype.dispose = function () {
  30104. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  30105. if (buffer) {
  30106. buffer.dispose();
  30107. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  30108. }
  30109. if (this._indexBuffer) {
  30110. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  30111. this._indexBuffer = null;
  30112. }
  30113. };
  30114. return PostProcessManager;
  30115. }());
  30116. BABYLON.PostProcessManager = PostProcessManager;
  30117. })(BABYLON || (BABYLON = {}));
  30118. //# sourceMappingURL=babylon.postProcessManager.js.map
  30119. var BABYLON;
  30120. (function (BABYLON) {
  30121. /**
  30122. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  30123. */
  30124. var PerformanceMonitor = (function () {
  30125. /**
  30126. * constructor
  30127. * @param frameSampleSize The number of samples required to saturate the sliding window
  30128. */
  30129. function PerformanceMonitor(frameSampleSize) {
  30130. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  30131. this._enabled = true;
  30132. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  30133. }
  30134. /**
  30135. * Samples current frame
  30136. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  30137. */
  30138. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  30139. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  30140. if (!this._enabled)
  30141. return;
  30142. if (this._lastFrameTimeMs != null) {
  30143. var dt = timeMs - this._lastFrameTimeMs;
  30144. this._rollingFrameTime.add(dt);
  30145. }
  30146. this._lastFrameTimeMs = timeMs;
  30147. };
  30148. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  30149. /**
  30150. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  30151. * @return Average frame time in milliseconds
  30152. */
  30153. get: function () {
  30154. return this._rollingFrameTime.average;
  30155. },
  30156. enumerable: true,
  30157. configurable: true
  30158. });
  30159. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  30160. /**
  30161. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  30162. * @return Frame time variance in milliseconds squared
  30163. */
  30164. get: function () {
  30165. return this._rollingFrameTime.variance;
  30166. },
  30167. enumerable: true,
  30168. configurable: true
  30169. });
  30170. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  30171. /**
  30172. * Returns the frame time of the most recent frame
  30173. * @return Frame time in milliseconds
  30174. */
  30175. get: function () {
  30176. return this._rollingFrameTime.history(0);
  30177. },
  30178. enumerable: true,
  30179. configurable: true
  30180. });
  30181. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  30182. /**
  30183. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  30184. * @return Framerate in frames per second
  30185. */
  30186. get: function () {
  30187. return 1000.0 / this._rollingFrameTime.average;
  30188. },
  30189. enumerable: true,
  30190. configurable: true
  30191. });
  30192. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  30193. /**
  30194. * Returns the average framerate in frames per second using the most recent frame time
  30195. * @return Framerate in frames per second
  30196. */
  30197. get: function () {
  30198. return 1000.0 / this._rollingFrameTime.history(0);
  30199. },
  30200. enumerable: true,
  30201. configurable: true
  30202. });
  30203. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  30204. /**
  30205. * Returns true if enough samples have been taken to completely fill the sliding window
  30206. * @return true if saturated
  30207. */
  30208. get: function () {
  30209. return this._rollingFrameTime.isSaturated();
  30210. },
  30211. enumerable: true,
  30212. configurable: true
  30213. });
  30214. /**
  30215. * Enables contributions to the sliding window sample set
  30216. */
  30217. PerformanceMonitor.prototype.enable = function () {
  30218. this._enabled = true;
  30219. };
  30220. /**
  30221. * Disables contributions to the sliding window sample set
  30222. * Samples will not be interpolated over the disabled period
  30223. */
  30224. PerformanceMonitor.prototype.disable = function () {
  30225. this._enabled = false;
  30226. //clear last sample to avoid interpolating over the disabled period when next enabled
  30227. this._lastFrameTimeMs = null;
  30228. this._lastChangeTimeMs = null;
  30229. };
  30230. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  30231. /**
  30232. * Returns true if sampling is enabled
  30233. * @return true if enabled
  30234. */
  30235. get: function () {
  30236. return this._enabled;
  30237. },
  30238. enumerable: true,
  30239. configurable: true
  30240. });
  30241. /**
  30242. * Resets performance monitor
  30243. */
  30244. PerformanceMonitor.prototype.reset = function () {
  30245. //clear last sample to avoid interpolating over the disabled period when next enabled
  30246. this._lastFrameTimeMs = null;
  30247. this._lastChangeTimeMs = null;
  30248. //wipe record
  30249. this._rollingFrameTime.reset();
  30250. };
  30251. return PerformanceMonitor;
  30252. }());
  30253. BABYLON.PerformanceMonitor = PerformanceMonitor;
  30254. /**
  30255. * RollingAverage
  30256. *
  30257. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  30258. */
  30259. var RollingAverage = (function () {
  30260. /**
  30261. * constructor
  30262. * @param length The number of samples required to saturate the sliding window
  30263. */
  30264. function RollingAverage(length) {
  30265. this._samples = new Array(length);
  30266. this.reset();
  30267. }
  30268. /**
  30269. * Adds a sample to the sample set
  30270. * @param v The sample value
  30271. */
  30272. RollingAverage.prototype.add = function (v) {
  30273. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  30274. var delta;
  30275. //we need to check if we've already wrapped round
  30276. if (this.isSaturated()) {
  30277. //remove bottom of stack from mean
  30278. var bottomValue = this._samples[this._pos];
  30279. delta = bottomValue - this.average;
  30280. this.average -= delta / (this._sampleCount - 1);
  30281. this._m2 -= delta * (bottomValue - this.average);
  30282. }
  30283. else {
  30284. this._sampleCount++;
  30285. }
  30286. //add new value to mean
  30287. delta = v - this.average;
  30288. this.average += delta / (this._sampleCount);
  30289. this._m2 += delta * (v - this.average);
  30290. //set the new variance
  30291. this.variance = this._m2 / (this._sampleCount - 1);
  30292. this._samples[this._pos] = v;
  30293. this._pos++;
  30294. this._pos %= this._samples.length; //positive wrap around
  30295. };
  30296. /**
  30297. * Returns previously added values or null if outside of history or outside the sliding window domain
  30298. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  30299. * @return Value previously recorded with add() or null if outside of range
  30300. */
  30301. RollingAverage.prototype.history = function (i) {
  30302. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  30303. return null;
  30304. }
  30305. var i0 = this._wrapPosition(this._pos - 1.0);
  30306. return this._samples[this._wrapPosition(i0 - i)];
  30307. };
  30308. /**
  30309. * Returns true if enough samples have been taken to completely fill the sliding window
  30310. * @return true if sample-set saturated
  30311. */
  30312. RollingAverage.prototype.isSaturated = function () {
  30313. return this._sampleCount >= this._samples.length;
  30314. };
  30315. /**
  30316. * Resets the rolling average (equivalent to 0 samples taken so far)
  30317. */
  30318. RollingAverage.prototype.reset = function () {
  30319. this.average = 0;
  30320. this.variance = 0;
  30321. this._sampleCount = 0;
  30322. this._pos = 0;
  30323. this._m2 = 0;
  30324. };
  30325. /**
  30326. * Wraps a value around the sample range boundaries
  30327. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  30328. * @return Wrapped position in sample range
  30329. */
  30330. RollingAverage.prototype._wrapPosition = function (i) {
  30331. var max = this._samples.length;
  30332. return ((i % max) + max) % max;
  30333. };
  30334. return RollingAverage;
  30335. }());
  30336. BABYLON.RollingAverage = RollingAverage;
  30337. })(BABYLON || (BABYLON = {}));
  30338. //# sourceMappingURL=babylon.performanceMonitor.js.map
  30339. var BABYLON;
  30340. (function (BABYLON) {
  30341. var StandardMaterialDefines = (function (_super) {
  30342. __extends(StandardMaterialDefines, _super);
  30343. function StandardMaterialDefines() {
  30344. var _this = _super.call(this) || this;
  30345. _this.MAINUV1 = false;
  30346. _this.MAINUV2 = false;
  30347. _this.DIFFUSE = false;
  30348. _this.DIFFUSEDIRECTUV = 0;
  30349. _this.AMBIENT = false;
  30350. _this.AMBIENTDIRECTUV = 0;
  30351. _this.OPACITY = false;
  30352. _this.OPACITYDIRECTUV = 0;
  30353. _this.OPACITYRGB = false;
  30354. _this.REFLECTION = false;
  30355. _this.EMISSIVE = false;
  30356. _this.EMISSIVEDIRECTUV = 0;
  30357. _this.SPECULAR = false;
  30358. _this.SPECULARDIRECTUV = 0;
  30359. _this.BUMP = false;
  30360. _this.BUMPDIRECTUV = 0;
  30361. _this.PARALLAX = false;
  30362. _this.PARALLAXOCCLUSION = false;
  30363. _this.SPECULAROVERALPHA = false;
  30364. _this.CLIPPLANE = false;
  30365. _this.ALPHATEST = false;
  30366. _this.DEPTHPREPASS = false;
  30367. _this.ALPHAFROMDIFFUSE = false;
  30368. _this.POINTSIZE = false;
  30369. _this.FOG = false;
  30370. _this.SPECULARTERM = false;
  30371. _this.DIFFUSEFRESNEL = false;
  30372. _this.OPACITYFRESNEL = false;
  30373. _this.REFLECTIONFRESNEL = false;
  30374. _this.REFRACTIONFRESNEL = false;
  30375. _this.EMISSIVEFRESNEL = false;
  30376. _this.FRESNEL = false;
  30377. _this.NORMAL = false;
  30378. _this.UV1 = false;
  30379. _this.UV2 = false;
  30380. _this.VERTEXCOLOR = false;
  30381. _this.VERTEXALPHA = false;
  30382. _this.NUM_BONE_INFLUENCERS = 0;
  30383. _this.BonesPerMesh = 0;
  30384. _this.INSTANCES = false;
  30385. _this.GLOSSINESS = false;
  30386. _this.ROUGHNESS = false;
  30387. _this.EMISSIVEASILLUMINATION = false;
  30388. _this.LINKEMISSIVEWITHDIFFUSE = false;
  30389. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  30390. _this.LIGHTMAP = false;
  30391. _this.LIGHTMAPDIRECTUV = 0;
  30392. _this.USELIGHTMAPASSHADOWMAP = false;
  30393. _this.REFLECTIONMAP_3D = false;
  30394. _this.REFLECTIONMAP_SPHERICAL = false;
  30395. _this.REFLECTIONMAP_PLANAR = false;
  30396. _this.REFLECTIONMAP_CUBIC = false;
  30397. _this.REFLECTIONMAP_PROJECTION = false;
  30398. _this.REFLECTIONMAP_SKYBOX = false;
  30399. _this.REFLECTIONMAP_EXPLICIT = false;
  30400. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  30401. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  30402. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  30403. _this.INVERTCUBICMAP = false;
  30404. _this.LOGARITHMICDEPTH = false;
  30405. _this.REFRACTION = false;
  30406. _this.REFRACTIONMAP_3D = false;
  30407. _this.REFLECTIONOVERALPHA = false;
  30408. _this.TWOSIDEDLIGHTING = false;
  30409. _this.SHADOWFLOAT = false;
  30410. _this.MORPHTARGETS = false;
  30411. _this.MORPHTARGETS_NORMAL = false;
  30412. _this.MORPHTARGETS_TANGENT = false;
  30413. _this.NUM_MORPH_INFLUENCERS = 0;
  30414. _this.USERIGHTHANDEDSYSTEM = false;
  30415. _this.IMAGEPROCESSING = false;
  30416. _this.VIGNETTE = false;
  30417. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  30418. _this.VIGNETTEBLENDMODEOPAQUE = false;
  30419. _this.TONEMAPPING = false;
  30420. _this.CONTRAST = false;
  30421. _this.COLORCURVES = false;
  30422. _this.COLORGRADING = false;
  30423. _this.SAMPLER3DGREENDEPTH = false;
  30424. _this.SAMPLER3DBGRMAP = false;
  30425. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  30426. _this.EXPOSURE = false;
  30427. _this.rebuild();
  30428. return _this;
  30429. }
  30430. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  30431. var modes = [
  30432. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  30433. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  30434. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  30435. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  30436. ];
  30437. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  30438. var mode = modes_1[_i];
  30439. this[mode] = (mode === modeToEnable);
  30440. }
  30441. };
  30442. return StandardMaterialDefines;
  30443. }(BABYLON.MaterialDefines));
  30444. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  30445. var StandardMaterial = (function (_super) {
  30446. __extends(StandardMaterial, _super);
  30447. function StandardMaterial(name, scene) {
  30448. var _this = _super.call(this, name, scene) || this;
  30449. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  30450. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  30451. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  30452. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  30453. _this.specularPower = 64;
  30454. _this._useAlphaFromDiffuseTexture = false;
  30455. _this._useEmissiveAsIllumination = false;
  30456. _this._linkEmissiveWithDiffuse = false;
  30457. _this._useSpecularOverAlpha = false;
  30458. _this._useReflectionOverAlpha = false;
  30459. _this._disableLighting = false;
  30460. _this._useParallax = false;
  30461. _this._useParallaxOcclusion = false;
  30462. _this.parallaxScaleBias = 0.05;
  30463. _this._roughness = 0;
  30464. _this.indexOfRefraction = 0.98;
  30465. _this.invertRefractionY = true;
  30466. _this._useLightmapAsShadowmap = false;
  30467. _this._useReflectionFresnelFromSpecular = false;
  30468. _this._useGlossinessFromSpecularMapAlpha = false;
  30469. _this._maxSimultaneousLights = 4;
  30470. /**
  30471. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30472. */
  30473. _this._invertNormalMapX = false;
  30474. /**
  30475. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30476. */
  30477. _this._invertNormalMapY = false;
  30478. /**
  30479. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30480. */
  30481. _this._twoSidedLighting = false;
  30482. _this._renderTargets = new BABYLON.SmartArray(16);
  30483. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  30484. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  30485. // Setup the default processing configuration to the scene.
  30486. _this._attachImageProcessingConfiguration(null);
  30487. _this.getRenderTargetTextures = function () {
  30488. _this._renderTargets.reset();
  30489. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  30490. _this._renderTargets.push(_this._reflectionTexture);
  30491. }
  30492. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  30493. _this._renderTargets.push(_this._refractionTexture);
  30494. }
  30495. return _this._renderTargets;
  30496. };
  30497. return _this;
  30498. }
  30499. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  30500. /**
  30501. * Gets the image processing configuration used either in this material.
  30502. */
  30503. get: function () {
  30504. return this._imageProcessingConfiguration;
  30505. },
  30506. /**
  30507. * Sets the Default image processing configuration used either in the this material.
  30508. *
  30509. * If sets to null, the scene one is in use.
  30510. */
  30511. set: function (value) {
  30512. this._attachImageProcessingConfiguration(value);
  30513. // Ensure the effect will be rebuilt.
  30514. this._markAllSubMeshesAsTexturesDirty();
  30515. },
  30516. enumerable: true,
  30517. configurable: true
  30518. });
  30519. /**
  30520. * Attaches a new image processing configuration to the Standard Material.
  30521. * @param configuration
  30522. */
  30523. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  30524. var _this = this;
  30525. if (configuration === this._imageProcessingConfiguration) {
  30526. return;
  30527. }
  30528. // Detaches observer.
  30529. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  30530. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  30531. }
  30532. // Pick the scene configuration if needed.
  30533. if (!configuration) {
  30534. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  30535. }
  30536. else {
  30537. this._imageProcessingConfiguration = configuration;
  30538. }
  30539. // Attaches observer.
  30540. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  30541. _this._markAllSubMeshesAsImageProcessingDirty();
  30542. });
  30543. };
  30544. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  30545. /**
  30546. * Gets wether the color curves effect is enabled.
  30547. */
  30548. get: function () {
  30549. return this.imageProcessingConfiguration.colorCurvesEnabled;
  30550. },
  30551. /**
  30552. * Sets wether the color curves effect is enabled.
  30553. */
  30554. set: function (value) {
  30555. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  30556. },
  30557. enumerable: true,
  30558. configurable: true
  30559. });
  30560. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  30561. /**
  30562. * Gets wether the color grading effect is enabled.
  30563. */
  30564. get: function () {
  30565. return this.imageProcessingConfiguration.colorGradingEnabled;
  30566. },
  30567. /**
  30568. * Gets wether the color grading effect is enabled.
  30569. */
  30570. set: function (value) {
  30571. this.imageProcessingConfiguration.colorGradingEnabled = value;
  30572. },
  30573. enumerable: true,
  30574. configurable: true
  30575. });
  30576. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  30577. /**
  30578. * Gets wether tonemapping is enabled or not.
  30579. */
  30580. get: function () {
  30581. return this._imageProcessingConfiguration.toneMappingEnabled;
  30582. },
  30583. /**
  30584. * Sets wether tonemapping is enabled or not
  30585. */
  30586. set: function (value) {
  30587. this._imageProcessingConfiguration.toneMappingEnabled = value;
  30588. },
  30589. enumerable: true,
  30590. configurable: true
  30591. });
  30592. ;
  30593. ;
  30594. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  30595. /**
  30596. * The camera exposure used on this material.
  30597. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  30598. * This corresponds to a photographic exposure.
  30599. */
  30600. get: function () {
  30601. return this._imageProcessingConfiguration.exposure;
  30602. },
  30603. /**
  30604. * The camera exposure used on this material.
  30605. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  30606. * This corresponds to a photographic exposure.
  30607. */
  30608. set: function (value) {
  30609. this._imageProcessingConfiguration.exposure = value;
  30610. },
  30611. enumerable: true,
  30612. configurable: true
  30613. });
  30614. ;
  30615. ;
  30616. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  30617. /**
  30618. * Gets The camera contrast used on this material.
  30619. */
  30620. get: function () {
  30621. return this._imageProcessingConfiguration.contrast;
  30622. },
  30623. /**
  30624. * Sets The camera contrast used on this material.
  30625. */
  30626. set: function (value) {
  30627. this._imageProcessingConfiguration.contrast = value;
  30628. },
  30629. enumerable: true,
  30630. configurable: true
  30631. });
  30632. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  30633. /**
  30634. * Gets the Color Grading 2D Lookup Texture.
  30635. */
  30636. get: function () {
  30637. return this._imageProcessingConfiguration.colorGradingTexture;
  30638. },
  30639. /**
  30640. * Sets the Color Grading 2D Lookup Texture.
  30641. */
  30642. set: function (value) {
  30643. this._imageProcessingConfiguration.colorGradingTexture = value;
  30644. },
  30645. enumerable: true,
  30646. configurable: true
  30647. });
  30648. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  30649. /**
  30650. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  30651. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  30652. * 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;
  30653. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  30654. */
  30655. get: function () {
  30656. return this._imageProcessingConfiguration.colorCurves;
  30657. },
  30658. /**
  30659. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  30660. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  30661. * 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;
  30662. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  30663. */
  30664. set: function (value) {
  30665. this._imageProcessingConfiguration.colorCurves = value;
  30666. },
  30667. enumerable: true,
  30668. configurable: true
  30669. });
  30670. StandardMaterial.prototype.getClassName = function () {
  30671. return "StandardMaterial";
  30672. };
  30673. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  30674. get: function () {
  30675. return this._useLogarithmicDepth;
  30676. },
  30677. set: function (value) {
  30678. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  30679. this._markAllSubMeshesAsMiscDirty();
  30680. },
  30681. enumerable: true,
  30682. configurable: true
  30683. });
  30684. StandardMaterial.prototype.needAlphaBlending = function () {
  30685. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  30686. };
  30687. StandardMaterial.prototype.needAlphaTesting = function () {
  30688. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  30689. };
  30690. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  30691. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  30692. };
  30693. StandardMaterial.prototype.getAlphaTestTexture = function () {
  30694. return this._diffuseTexture;
  30695. };
  30696. /**
  30697. * Child classes can use it to update shaders
  30698. */
  30699. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30700. if (this.isFrozen) {
  30701. if (this._wasPreviouslyReady && subMesh.effect) {
  30702. return true;
  30703. }
  30704. }
  30705. if (!subMesh._materialDefines) {
  30706. subMesh._materialDefines = new StandardMaterialDefines();
  30707. }
  30708. var scene = this.getScene();
  30709. var defines = subMesh._materialDefines;
  30710. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  30711. if (defines._renderId === scene.getRenderId()) {
  30712. return true;
  30713. }
  30714. }
  30715. var engine = scene.getEngine();
  30716. // Lights
  30717. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  30718. // Textures
  30719. if (defines._areTexturesDirty) {
  30720. defines._needUVs = false;
  30721. defines.MAINUV1 = false;
  30722. defines.MAINUV2 = false;
  30723. if (scene.texturesEnabled) {
  30724. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30725. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  30726. return false;
  30727. }
  30728. else {
  30729. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  30730. }
  30731. }
  30732. else {
  30733. defines.DIFFUSE = false;
  30734. }
  30735. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30736. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  30737. return false;
  30738. }
  30739. else {
  30740. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  30741. }
  30742. }
  30743. else {
  30744. defines.AMBIENT = false;
  30745. }
  30746. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30747. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  30748. return false;
  30749. }
  30750. else {
  30751. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  30752. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  30753. }
  30754. }
  30755. else {
  30756. defines.OPACITY = false;
  30757. }
  30758. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30759. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  30760. return false;
  30761. }
  30762. else {
  30763. defines._needNormals = true;
  30764. defines.REFLECTION = true;
  30765. defines.ROUGHNESS = (this._roughness > 0);
  30766. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  30767. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  30768. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  30769. switch (this._reflectionTexture.coordinatesMode) {
  30770. case BABYLON.Texture.CUBIC_MODE:
  30771. case BABYLON.Texture.INVCUBIC_MODE:
  30772. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  30773. break;
  30774. case BABYLON.Texture.EXPLICIT_MODE:
  30775. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  30776. break;
  30777. case BABYLON.Texture.PLANAR_MODE:
  30778. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  30779. break;
  30780. case BABYLON.Texture.PROJECTION_MODE:
  30781. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  30782. break;
  30783. case BABYLON.Texture.SKYBOX_MODE:
  30784. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  30785. break;
  30786. case BABYLON.Texture.SPHERICAL_MODE:
  30787. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  30788. break;
  30789. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  30790. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  30791. break;
  30792. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  30793. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  30794. break;
  30795. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  30796. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  30797. break;
  30798. }
  30799. }
  30800. }
  30801. else {
  30802. defines.REFLECTION = false;
  30803. }
  30804. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30805. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  30806. return false;
  30807. }
  30808. else {
  30809. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  30810. }
  30811. }
  30812. else {
  30813. defines.EMISSIVE = false;
  30814. }
  30815. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30816. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  30817. return false;
  30818. }
  30819. else {
  30820. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  30821. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  30822. }
  30823. }
  30824. else {
  30825. defines.LIGHTMAP = false;
  30826. }
  30827. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30828. if (!this._specularTexture.isReadyOrNotBlocking()) {
  30829. return false;
  30830. }
  30831. else {
  30832. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  30833. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  30834. }
  30835. }
  30836. else {
  30837. defines.SPECULAR = false;
  30838. }
  30839. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  30840. // Bump texure can not be not blocking.
  30841. if (!this._bumpTexture.isReady()) {
  30842. return false;
  30843. }
  30844. else {
  30845. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  30846. defines.PARALLAX = this._useParallax;
  30847. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  30848. }
  30849. }
  30850. else {
  30851. defines.BUMP = false;
  30852. }
  30853. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30854. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  30855. return false;
  30856. }
  30857. else {
  30858. defines._needUVs = true;
  30859. defines.REFRACTION = true;
  30860. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  30861. }
  30862. }
  30863. else {
  30864. defines.REFRACTION = false;
  30865. }
  30866. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  30867. }
  30868. else {
  30869. defines.DIFFUSE = false;
  30870. defines.AMBIENT = false;
  30871. defines.OPACITY = false;
  30872. defines.REFLECTION = false;
  30873. defines.EMISSIVE = false;
  30874. defines.LIGHTMAP = false;
  30875. defines.BUMP = false;
  30876. defines.REFRACTION = false;
  30877. }
  30878. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  30879. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  30880. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  30881. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  30882. }
  30883. if (defines._areImageProcessingDirty) {
  30884. if (!this._imageProcessingConfiguration.isReady()) {
  30885. return false;
  30886. }
  30887. this._imageProcessingConfiguration.prepareDefines(defines);
  30888. }
  30889. if (defines._areFresnelDirty) {
  30890. if (StandardMaterial.FresnelEnabled) {
  30891. // Fresnel
  30892. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  30893. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  30894. this._reflectionFresnelParameters) {
  30895. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  30896. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  30897. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  30898. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  30899. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  30900. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  30901. defines._needNormals = true;
  30902. defines.FRESNEL = true;
  30903. }
  30904. }
  30905. else {
  30906. defines.FRESNEL = false;
  30907. }
  30908. }
  30909. // Misc.
  30910. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  30911. // Attribs
  30912. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  30913. // Values that need to be evaluated on every frame
  30914. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  30915. // Get correct effect
  30916. if (defines.isDirty) {
  30917. defines.markAsProcessed();
  30918. scene.resetCachedMaterial();
  30919. // Fallbacks
  30920. var fallbacks = new BABYLON.EffectFallbacks();
  30921. if (defines.REFLECTION) {
  30922. fallbacks.addFallback(0, "REFLECTION");
  30923. }
  30924. if (defines.SPECULAR) {
  30925. fallbacks.addFallback(0, "SPECULAR");
  30926. }
  30927. if (defines.BUMP) {
  30928. fallbacks.addFallback(0, "BUMP");
  30929. }
  30930. if (defines.PARALLAX) {
  30931. fallbacks.addFallback(1, "PARALLAX");
  30932. }
  30933. if (defines.PARALLAXOCCLUSION) {
  30934. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  30935. }
  30936. if (defines.SPECULAROVERALPHA) {
  30937. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  30938. }
  30939. if (defines.FOG) {
  30940. fallbacks.addFallback(1, "FOG");
  30941. }
  30942. if (defines.POINTSIZE) {
  30943. fallbacks.addFallback(0, "POINTSIZE");
  30944. }
  30945. if (defines.LOGARITHMICDEPTH) {
  30946. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  30947. }
  30948. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  30949. if (defines.SPECULARTERM) {
  30950. fallbacks.addFallback(0, "SPECULARTERM");
  30951. }
  30952. if (defines.DIFFUSEFRESNEL) {
  30953. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  30954. }
  30955. if (defines.OPACITYFRESNEL) {
  30956. fallbacks.addFallback(2, "OPACITYFRESNEL");
  30957. }
  30958. if (defines.REFLECTIONFRESNEL) {
  30959. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  30960. }
  30961. if (defines.EMISSIVEFRESNEL) {
  30962. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  30963. }
  30964. if (defines.FRESNEL) {
  30965. fallbacks.addFallback(4, "FRESNEL");
  30966. }
  30967. //Attributes
  30968. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30969. if (defines.NORMAL) {
  30970. attribs.push(BABYLON.VertexBuffer.NormalKind);
  30971. }
  30972. if (defines.UV1) {
  30973. attribs.push(BABYLON.VertexBuffer.UVKind);
  30974. }
  30975. if (defines.UV2) {
  30976. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30977. }
  30978. if (defines.VERTEXCOLOR) {
  30979. attribs.push(BABYLON.VertexBuffer.ColorKind);
  30980. }
  30981. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  30982. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  30983. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  30984. var shaderName = "default";
  30985. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  30986. "vFogInfos", "vFogColor", "pointSize",
  30987. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  30988. "mBones",
  30989. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  30990. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  30991. "logarithmicDepthConstant", "vNormalReoderParams"
  30992. ];
  30993. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  30994. var uniformBuffers = ["Material", "Scene"];
  30995. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  30996. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  30997. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  30998. uniformsNames: uniforms,
  30999. uniformBuffersNames: uniformBuffers,
  31000. samplers: samplers,
  31001. defines: defines,
  31002. maxSimultaneousLights: this._maxSimultaneousLights
  31003. });
  31004. if (this.customShaderNameResolve) {
  31005. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  31006. }
  31007. var join = defines.toString();
  31008. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  31009. attributes: attribs,
  31010. uniformsNames: uniforms,
  31011. uniformBuffersNames: uniformBuffers,
  31012. samplers: samplers,
  31013. defines: join,
  31014. fallbacks: fallbacks,
  31015. onCompiled: this.onCompiled,
  31016. onError: this.onError,
  31017. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  31018. }, engine), defines);
  31019. this.buildUniformLayout();
  31020. }
  31021. if (!subMesh.effect.isReady()) {
  31022. return false;
  31023. }
  31024. defines._renderId = scene.getRenderId();
  31025. this._wasPreviouslyReady = true;
  31026. return true;
  31027. };
  31028. StandardMaterial.prototype.buildUniformLayout = function () {
  31029. // Order is important !
  31030. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  31031. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  31032. this._uniformBuffer.addUniform("opacityParts", 4);
  31033. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  31034. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  31035. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  31036. this._uniformBuffer.addUniform("refractionRightColor", 4);
  31037. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  31038. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  31039. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  31040. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  31041. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  31042. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  31043. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  31044. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  31045. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  31046. this._uniformBuffer.addUniform("vBumpInfos", 3);
  31047. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  31048. this._uniformBuffer.addUniform("ambientMatrix", 16);
  31049. this._uniformBuffer.addUniform("opacityMatrix", 16);
  31050. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  31051. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  31052. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  31053. this._uniformBuffer.addUniform("specularMatrix", 16);
  31054. this._uniformBuffer.addUniform("bumpMatrix", 16);
  31055. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  31056. this._uniformBuffer.addUniform("refractionMatrix", 16);
  31057. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  31058. this._uniformBuffer.addUniform("vSpecularColor", 4);
  31059. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  31060. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  31061. this._uniformBuffer.addUniform("pointSize", 1);
  31062. this._uniformBuffer.create();
  31063. };
  31064. StandardMaterial.prototype.unbind = function () {
  31065. if (this._activeEffect) {
  31066. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  31067. this._activeEffect.setTexture("reflection2DSampler", null);
  31068. }
  31069. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  31070. this._activeEffect.setTexture("refraction2DSampler", null);
  31071. }
  31072. }
  31073. _super.prototype.unbind.call(this);
  31074. };
  31075. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31076. var scene = this.getScene();
  31077. var defines = subMesh._materialDefines;
  31078. if (!defines) {
  31079. return;
  31080. }
  31081. var effect = subMesh.effect;
  31082. this._activeEffect = effect;
  31083. // Matrices
  31084. this.bindOnlyWorldMatrix(world);
  31085. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  31086. // Bones
  31087. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  31088. if (mustRebind) {
  31089. this._uniformBuffer.bindToEffect(effect, "Material");
  31090. this.bindViewProjection(effect);
  31091. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  31092. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  31093. // Fresnel
  31094. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  31095. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  31096. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  31097. }
  31098. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  31099. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  31100. }
  31101. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  31102. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  31103. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  31104. }
  31105. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  31106. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  31107. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  31108. }
  31109. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  31110. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  31111. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  31112. }
  31113. }
  31114. // Textures
  31115. if (scene.texturesEnabled) {
  31116. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  31117. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  31118. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  31119. }
  31120. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  31121. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  31122. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  31123. }
  31124. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  31125. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  31126. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  31127. }
  31128. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  31129. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  31130. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  31131. }
  31132. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  31133. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  31134. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  31135. }
  31136. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  31137. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  31138. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  31139. }
  31140. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  31141. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  31142. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  31143. }
  31144. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  31145. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  31146. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  31147. if (scene._mirroredCameraPosition) {
  31148. 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);
  31149. }
  31150. else {
  31151. 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);
  31152. }
  31153. }
  31154. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  31155. var depth = 1.0;
  31156. if (!this._refractionTexture.isCube) {
  31157. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  31158. if (this._refractionTexture.depth) {
  31159. depth = this._refractionTexture.depth;
  31160. }
  31161. }
  31162. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  31163. }
  31164. }
  31165. // Point size
  31166. if (this.pointsCloud) {
  31167. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  31168. }
  31169. if (defines.SPECULARTERM) {
  31170. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  31171. }
  31172. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  31173. // Diffuse
  31174. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  31175. }
  31176. // Textures
  31177. if (scene.texturesEnabled) {
  31178. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  31179. effect.setTexture("diffuseSampler", this._diffuseTexture);
  31180. }
  31181. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  31182. effect.setTexture("ambientSampler", this._ambientTexture);
  31183. }
  31184. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  31185. effect.setTexture("opacitySampler", this._opacityTexture);
  31186. }
  31187. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  31188. if (this._reflectionTexture.isCube) {
  31189. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  31190. }
  31191. else {
  31192. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  31193. }
  31194. }
  31195. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  31196. effect.setTexture("emissiveSampler", this._emissiveTexture);
  31197. }
  31198. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  31199. effect.setTexture("lightmapSampler", this._lightmapTexture);
  31200. }
  31201. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  31202. effect.setTexture("specularSampler", this._specularTexture);
  31203. }
  31204. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  31205. effect.setTexture("bumpSampler", this._bumpTexture);
  31206. }
  31207. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  31208. var depth = 1.0;
  31209. if (this._refractionTexture.isCube) {
  31210. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  31211. }
  31212. else {
  31213. effect.setTexture("refraction2DSampler", this._refractionTexture);
  31214. }
  31215. }
  31216. }
  31217. // Clip plane
  31218. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  31219. // Colors
  31220. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  31221. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  31222. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  31223. }
  31224. if (mustRebind || !this.isFrozen) {
  31225. // Lights
  31226. if (scene.lightsEnabled && !this._disableLighting) {
  31227. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  31228. }
  31229. // View
  31230. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  31231. this.bindView(effect);
  31232. }
  31233. // Fog
  31234. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  31235. // Morph targets
  31236. if (defines.NUM_MORPH_INFLUENCERS) {
  31237. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  31238. }
  31239. // Log. depth
  31240. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  31241. // image processing
  31242. this._imageProcessingConfiguration.bind(this._activeEffect);
  31243. }
  31244. this._uniformBuffer.update();
  31245. this._afterBind(mesh, this._activeEffect);
  31246. };
  31247. StandardMaterial.prototype.getAnimatables = function () {
  31248. var results = [];
  31249. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  31250. results.push(this._diffuseTexture);
  31251. }
  31252. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  31253. results.push(this._ambientTexture);
  31254. }
  31255. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  31256. results.push(this._opacityTexture);
  31257. }
  31258. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  31259. results.push(this._reflectionTexture);
  31260. }
  31261. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  31262. results.push(this._emissiveTexture);
  31263. }
  31264. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  31265. results.push(this._specularTexture);
  31266. }
  31267. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  31268. results.push(this._bumpTexture);
  31269. }
  31270. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  31271. results.push(this._lightmapTexture);
  31272. }
  31273. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  31274. results.push(this._refractionTexture);
  31275. }
  31276. return results;
  31277. };
  31278. StandardMaterial.prototype.getActiveTextures = function () {
  31279. var activeTextures = _super.prototype.getActiveTextures.call(this);
  31280. if (this._diffuseTexture) {
  31281. activeTextures.push(this._diffuseTexture);
  31282. }
  31283. if (this._ambientTexture) {
  31284. activeTextures.push(this._ambientTexture);
  31285. }
  31286. if (this._opacityTexture) {
  31287. activeTextures.push(this._opacityTexture);
  31288. }
  31289. if (this._reflectionTexture) {
  31290. activeTextures.push(this._reflectionTexture);
  31291. }
  31292. if (this._emissiveTexture) {
  31293. activeTextures.push(this._emissiveTexture);
  31294. }
  31295. if (this._specularTexture) {
  31296. activeTextures.push(this._specularTexture);
  31297. }
  31298. if (this._bumpTexture) {
  31299. activeTextures.push(this._bumpTexture);
  31300. }
  31301. if (this._lightmapTexture) {
  31302. activeTextures.push(this._lightmapTexture);
  31303. }
  31304. if (this._refractionTexture) {
  31305. activeTextures.push(this._refractionTexture);
  31306. }
  31307. return activeTextures;
  31308. };
  31309. StandardMaterial.prototype.hasTexture = function (texture) {
  31310. if (_super.prototype.hasTexture.call(this, texture)) {
  31311. return true;
  31312. }
  31313. if (this._diffuseTexture === texture) {
  31314. return true;
  31315. }
  31316. if (this._ambientTexture === texture) {
  31317. return true;
  31318. }
  31319. if (this._opacityTexture === texture) {
  31320. return true;
  31321. }
  31322. if (this._reflectionTexture === texture) {
  31323. return true;
  31324. }
  31325. if (this._emissiveTexture === texture) {
  31326. return true;
  31327. }
  31328. if (this._specularTexture === texture) {
  31329. return true;
  31330. }
  31331. if (this._bumpTexture === texture) {
  31332. return true;
  31333. }
  31334. if (this._lightmapTexture === texture) {
  31335. return true;
  31336. }
  31337. if (this._refractionTexture === texture) {
  31338. return true;
  31339. }
  31340. return false;
  31341. };
  31342. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31343. if (forceDisposeTextures) {
  31344. if (this._diffuseTexture) {
  31345. this._diffuseTexture.dispose();
  31346. }
  31347. if (this._ambientTexture) {
  31348. this._ambientTexture.dispose();
  31349. }
  31350. if (this._opacityTexture) {
  31351. this._opacityTexture.dispose();
  31352. }
  31353. if (this._reflectionTexture) {
  31354. this._reflectionTexture.dispose();
  31355. }
  31356. if (this._emissiveTexture) {
  31357. this._emissiveTexture.dispose();
  31358. }
  31359. if (this._specularTexture) {
  31360. this._specularTexture.dispose();
  31361. }
  31362. if (this._bumpTexture) {
  31363. this._bumpTexture.dispose();
  31364. }
  31365. if (this._lightmapTexture) {
  31366. this._lightmapTexture.dispose();
  31367. }
  31368. if (this._refractionTexture) {
  31369. this._refractionTexture.dispose();
  31370. }
  31371. }
  31372. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  31373. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  31374. }
  31375. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  31376. };
  31377. StandardMaterial.prototype.clone = function (name) {
  31378. var _this = this;
  31379. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  31380. result.name = name;
  31381. result.id = name;
  31382. return result;
  31383. };
  31384. StandardMaterial.prototype.serialize = function () {
  31385. return BABYLON.SerializationHelper.Serialize(this);
  31386. };
  31387. // Statics
  31388. StandardMaterial.Parse = function (source, scene, rootUrl) {
  31389. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  31390. };
  31391. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  31392. get: function () {
  31393. return StandardMaterial._DiffuseTextureEnabled;
  31394. },
  31395. set: function (value) {
  31396. if (StandardMaterial._DiffuseTextureEnabled === value) {
  31397. return;
  31398. }
  31399. StandardMaterial._DiffuseTextureEnabled = value;
  31400. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31401. },
  31402. enumerable: true,
  31403. configurable: true
  31404. });
  31405. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  31406. get: function () {
  31407. return StandardMaterial._AmbientTextureEnabled;
  31408. },
  31409. set: function (value) {
  31410. if (StandardMaterial._AmbientTextureEnabled === value) {
  31411. return;
  31412. }
  31413. StandardMaterial._AmbientTextureEnabled = value;
  31414. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31415. },
  31416. enumerable: true,
  31417. configurable: true
  31418. });
  31419. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  31420. get: function () {
  31421. return StandardMaterial._OpacityTextureEnabled;
  31422. },
  31423. set: function (value) {
  31424. if (StandardMaterial._OpacityTextureEnabled === value) {
  31425. return;
  31426. }
  31427. StandardMaterial._OpacityTextureEnabled = value;
  31428. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31429. },
  31430. enumerable: true,
  31431. configurable: true
  31432. });
  31433. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  31434. get: function () {
  31435. return StandardMaterial._ReflectionTextureEnabled;
  31436. },
  31437. set: function (value) {
  31438. if (StandardMaterial._ReflectionTextureEnabled === value) {
  31439. return;
  31440. }
  31441. StandardMaterial._ReflectionTextureEnabled = value;
  31442. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31443. },
  31444. enumerable: true,
  31445. configurable: true
  31446. });
  31447. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  31448. get: function () {
  31449. return StandardMaterial._EmissiveTextureEnabled;
  31450. },
  31451. set: function (value) {
  31452. if (StandardMaterial._EmissiveTextureEnabled === value) {
  31453. return;
  31454. }
  31455. StandardMaterial._EmissiveTextureEnabled = value;
  31456. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31457. },
  31458. enumerable: true,
  31459. configurable: true
  31460. });
  31461. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  31462. get: function () {
  31463. return StandardMaterial._SpecularTextureEnabled;
  31464. },
  31465. set: function (value) {
  31466. if (StandardMaterial._SpecularTextureEnabled === value) {
  31467. return;
  31468. }
  31469. StandardMaterial._SpecularTextureEnabled = value;
  31470. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31471. },
  31472. enumerable: true,
  31473. configurable: true
  31474. });
  31475. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  31476. get: function () {
  31477. return StandardMaterial._BumpTextureEnabled;
  31478. },
  31479. set: function (value) {
  31480. if (StandardMaterial._BumpTextureEnabled === value) {
  31481. return;
  31482. }
  31483. StandardMaterial._BumpTextureEnabled = value;
  31484. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31485. },
  31486. enumerable: true,
  31487. configurable: true
  31488. });
  31489. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  31490. get: function () {
  31491. return StandardMaterial._LightmapTextureEnabled;
  31492. },
  31493. set: function (value) {
  31494. if (StandardMaterial._LightmapTextureEnabled === value) {
  31495. return;
  31496. }
  31497. StandardMaterial._LightmapTextureEnabled = value;
  31498. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31499. },
  31500. enumerable: true,
  31501. configurable: true
  31502. });
  31503. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  31504. get: function () {
  31505. return StandardMaterial._RefractionTextureEnabled;
  31506. },
  31507. set: function (value) {
  31508. if (StandardMaterial._RefractionTextureEnabled === value) {
  31509. return;
  31510. }
  31511. StandardMaterial._RefractionTextureEnabled = value;
  31512. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31513. },
  31514. enumerable: true,
  31515. configurable: true
  31516. });
  31517. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  31518. get: function () {
  31519. return StandardMaterial._ColorGradingTextureEnabled;
  31520. },
  31521. set: function (value) {
  31522. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  31523. return;
  31524. }
  31525. StandardMaterial._ColorGradingTextureEnabled = value;
  31526. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31527. },
  31528. enumerable: true,
  31529. configurable: true
  31530. });
  31531. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  31532. get: function () {
  31533. return StandardMaterial._FresnelEnabled;
  31534. },
  31535. set: function (value) {
  31536. if (StandardMaterial._FresnelEnabled === value) {
  31537. return;
  31538. }
  31539. StandardMaterial._FresnelEnabled = value;
  31540. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  31541. },
  31542. enumerable: true,
  31543. configurable: true
  31544. });
  31545. // Flags used to enable or disable a type of texture for all Standard Materials
  31546. StandardMaterial._DiffuseTextureEnabled = true;
  31547. StandardMaterial._AmbientTextureEnabled = true;
  31548. StandardMaterial._OpacityTextureEnabled = true;
  31549. StandardMaterial._ReflectionTextureEnabled = true;
  31550. StandardMaterial._EmissiveTextureEnabled = true;
  31551. StandardMaterial._SpecularTextureEnabled = true;
  31552. StandardMaterial._BumpTextureEnabled = true;
  31553. StandardMaterial._LightmapTextureEnabled = true;
  31554. StandardMaterial._RefractionTextureEnabled = true;
  31555. StandardMaterial._ColorGradingTextureEnabled = true;
  31556. StandardMaterial._FresnelEnabled = true;
  31557. __decorate([
  31558. BABYLON.serializeAsTexture("diffuseTexture")
  31559. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  31560. __decorate([
  31561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31562. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  31563. __decorate([
  31564. BABYLON.serializeAsTexture("ambientTexture")
  31565. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  31566. __decorate([
  31567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31568. ], StandardMaterial.prototype, "ambientTexture", void 0);
  31569. __decorate([
  31570. BABYLON.serializeAsTexture("opacityTexture")
  31571. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  31572. __decorate([
  31573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31574. ], StandardMaterial.prototype, "opacityTexture", void 0);
  31575. __decorate([
  31576. BABYLON.serializeAsTexture("reflectionTexture")
  31577. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  31578. __decorate([
  31579. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31580. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  31581. __decorate([
  31582. BABYLON.serializeAsTexture("emissiveTexture")
  31583. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  31584. __decorate([
  31585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31586. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  31587. __decorate([
  31588. BABYLON.serializeAsTexture("specularTexture")
  31589. ], StandardMaterial.prototype, "_specularTexture", void 0);
  31590. __decorate([
  31591. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31592. ], StandardMaterial.prototype, "specularTexture", void 0);
  31593. __decorate([
  31594. BABYLON.serializeAsTexture("bumpTexture")
  31595. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  31596. __decorate([
  31597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31598. ], StandardMaterial.prototype, "bumpTexture", void 0);
  31599. __decorate([
  31600. BABYLON.serializeAsTexture("lightmapTexture")
  31601. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  31602. __decorate([
  31603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31604. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  31605. __decorate([
  31606. BABYLON.serializeAsTexture("refractionTexture")
  31607. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  31608. __decorate([
  31609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31610. ], StandardMaterial.prototype, "refractionTexture", void 0);
  31611. __decorate([
  31612. BABYLON.serializeAsColor3("ambient")
  31613. ], StandardMaterial.prototype, "ambientColor", void 0);
  31614. __decorate([
  31615. BABYLON.serializeAsColor3("diffuse")
  31616. ], StandardMaterial.prototype, "diffuseColor", void 0);
  31617. __decorate([
  31618. BABYLON.serializeAsColor3("specular")
  31619. ], StandardMaterial.prototype, "specularColor", void 0);
  31620. __decorate([
  31621. BABYLON.serializeAsColor3("emissive")
  31622. ], StandardMaterial.prototype, "emissiveColor", void 0);
  31623. __decorate([
  31624. BABYLON.serialize()
  31625. ], StandardMaterial.prototype, "specularPower", void 0);
  31626. __decorate([
  31627. BABYLON.serialize("useAlphaFromDiffuseTexture")
  31628. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  31629. __decorate([
  31630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31631. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  31632. __decorate([
  31633. BABYLON.serialize("useEmissiveAsIllumination")
  31634. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  31635. __decorate([
  31636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31637. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  31638. __decorate([
  31639. BABYLON.serialize("linkEmissiveWithDiffuse")
  31640. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  31641. __decorate([
  31642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31643. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  31644. __decorate([
  31645. BABYLON.serialize("useSpecularOverAlpha")
  31646. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  31647. __decorate([
  31648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31649. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  31650. __decorate([
  31651. BABYLON.serialize("useReflectionOverAlpha")
  31652. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  31653. __decorate([
  31654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31655. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  31656. __decorate([
  31657. BABYLON.serialize("disableLighting")
  31658. ], StandardMaterial.prototype, "_disableLighting", void 0);
  31659. __decorate([
  31660. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31661. ], StandardMaterial.prototype, "disableLighting", void 0);
  31662. __decorate([
  31663. BABYLON.serialize("useParallax")
  31664. ], StandardMaterial.prototype, "_useParallax", void 0);
  31665. __decorate([
  31666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31667. ], StandardMaterial.prototype, "useParallax", void 0);
  31668. __decorate([
  31669. BABYLON.serialize("useParallaxOcclusion")
  31670. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  31671. __decorate([
  31672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31673. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  31674. __decorate([
  31675. BABYLON.serialize()
  31676. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  31677. __decorate([
  31678. BABYLON.serialize("roughness")
  31679. ], StandardMaterial.prototype, "_roughness", void 0);
  31680. __decorate([
  31681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31682. ], StandardMaterial.prototype, "roughness", void 0);
  31683. __decorate([
  31684. BABYLON.serialize()
  31685. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  31686. __decorate([
  31687. BABYLON.serialize()
  31688. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  31689. __decorate([
  31690. BABYLON.serialize("useLightmapAsShadowmap")
  31691. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  31692. __decorate([
  31693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31694. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  31695. __decorate([
  31696. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  31697. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  31698. __decorate([
  31699. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31700. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  31701. __decorate([
  31702. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  31703. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  31704. __decorate([
  31705. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31706. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  31707. __decorate([
  31708. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  31709. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  31710. __decorate([
  31711. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31712. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  31713. __decorate([
  31714. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  31715. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  31716. __decorate([
  31717. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31718. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  31719. __decorate([
  31720. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  31721. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  31722. __decorate([
  31723. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31724. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  31725. __decorate([
  31726. BABYLON.serialize("useReflectionFresnelFromSpecular")
  31727. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  31728. __decorate([
  31729. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31730. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  31731. __decorate([
  31732. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  31733. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  31734. __decorate([
  31735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31736. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  31737. __decorate([
  31738. BABYLON.serialize("maxSimultaneousLights")
  31739. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  31740. __decorate([
  31741. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31742. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  31743. __decorate([
  31744. BABYLON.serialize("invertNormalMapX")
  31745. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  31746. __decorate([
  31747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31748. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  31749. __decorate([
  31750. BABYLON.serialize("invertNormalMapY")
  31751. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  31752. __decorate([
  31753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31754. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  31755. __decorate([
  31756. BABYLON.serialize("twoSidedLighting")
  31757. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  31758. __decorate([
  31759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31760. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  31761. __decorate([
  31762. BABYLON.serialize()
  31763. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  31764. return StandardMaterial;
  31765. }(BABYLON.PushMaterial));
  31766. BABYLON.StandardMaterial = StandardMaterial;
  31767. })(BABYLON || (BABYLON = {}));
  31768. //# sourceMappingURL=babylon.standardMaterial.js.map
  31769. var BABYLON;
  31770. (function (BABYLON) {
  31771. var PBRMaterialDefines = (function (_super) {
  31772. __extends(PBRMaterialDefines, _super);
  31773. function PBRMaterialDefines() {
  31774. var _this = _super.call(this) || this;
  31775. _this.PBR = true;
  31776. _this.MAINUV1 = false;
  31777. _this.MAINUV2 = false;
  31778. _this.UV1 = false;
  31779. _this.UV2 = false;
  31780. _this.ALBEDO = false;
  31781. _this.ALBEDODIRECTUV = 0;
  31782. _this.VERTEXCOLOR = false;
  31783. _this.AMBIENT = false;
  31784. _this.AMBIENTDIRECTUV = 0;
  31785. _this.AMBIENTINGRAYSCALE = false;
  31786. _this.OPACITY = false;
  31787. _this.VERTEXALPHA = false;
  31788. _this.OPACITYDIRECTUV = 0;
  31789. _this.OPACITYRGB = false;
  31790. _this.ALPHATEST = false;
  31791. _this.DEPTHPREPASS = false;
  31792. _this.ALPHABLEND = false;
  31793. _this.ALPHAFROMALBEDO = false;
  31794. _this.ALPHATESTVALUE = 0.5;
  31795. _this.SPECULAROVERALPHA = false;
  31796. _this.RADIANCEOVERALPHA = false;
  31797. _this.ALPHAFRESNEL = false;
  31798. _this.PREMULTIPLYALPHA = false;
  31799. _this.EMISSIVE = false;
  31800. _this.EMISSIVEDIRECTUV = 0;
  31801. _this.REFLECTIVITY = false;
  31802. _this.REFLECTIVITYDIRECTUV = 0;
  31803. _this.SPECULARTERM = false;
  31804. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  31805. _this.MICROSURFACEAUTOMATIC = false;
  31806. _this.LODBASEDMICROSFURACE = false;
  31807. _this.MICROSURFACEMAP = false;
  31808. _this.MICROSURFACEMAPDIRECTUV = 0;
  31809. _this.METALLICWORKFLOW = false;
  31810. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  31811. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  31812. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  31813. _this.AOSTOREINMETALMAPRED = false;
  31814. _this.ENVIRONMENTBRDF = false;
  31815. _this.NORMAL = false;
  31816. _this.TANGENT = false;
  31817. _this.BUMP = false;
  31818. _this.BUMPDIRECTUV = 0;
  31819. _this.PARALLAX = false;
  31820. _this.PARALLAXOCCLUSION = false;
  31821. _this.NORMALXYSCALE = true;
  31822. _this.LIGHTMAP = false;
  31823. _this.LIGHTMAPDIRECTUV = 0;
  31824. _this.USELIGHTMAPASSHADOWMAP = false;
  31825. _this.REFLECTION = false;
  31826. _this.REFLECTIONMAP_3D = false;
  31827. _this.REFLECTIONMAP_SPHERICAL = false;
  31828. _this.REFLECTIONMAP_PLANAR = false;
  31829. _this.REFLECTIONMAP_CUBIC = false;
  31830. _this.REFLECTIONMAP_PROJECTION = false;
  31831. _this.REFLECTIONMAP_SKYBOX = false;
  31832. _this.REFLECTIONMAP_EXPLICIT = false;
  31833. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  31834. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  31835. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  31836. _this.INVERTCUBICMAP = false;
  31837. _this.USESPHERICALFROMREFLECTIONMAP = false;
  31838. _this.USESPHERICALINFRAGMENT = false;
  31839. _this.REFLECTIONMAP_OPPOSITEZ = false;
  31840. _this.LODINREFLECTIONALPHA = false;
  31841. _this.GAMMAREFLECTION = false;
  31842. _this.REFRACTION = false;
  31843. _this.REFRACTIONMAP_3D = false;
  31844. _this.REFRACTIONMAP_OPPOSITEZ = false;
  31845. _this.LODINREFRACTIONALPHA = false;
  31846. _this.GAMMAREFRACTION = false;
  31847. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  31848. _this.INSTANCES = false;
  31849. _this.NUM_BONE_INFLUENCERS = 0;
  31850. _this.BonesPerMesh = 0;
  31851. _this.MORPHTARGETS = false;
  31852. _this.MORPHTARGETS_NORMAL = false;
  31853. _this.MORPHTARGETS_TANGENT = false;
  31854. _this.NUM_MORPH_INFLUENCERS = 0;
  31855. _this.IMAGEPROCESSING = false;
  31856. _this.VIGNETTE = false;
  31857. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  31858. _this.VIGNETTEBLENDMODEOPAQUE = false;
  31859. _this.TONEMAPPING = false;
  31860. _this.CONTRAST = false;
  31861. _this.COLORCURVES = false;
  31862. _this.COLORGRADING = false;
  31863. _this.SAMPLER3DGREENDEPTH = false;
  31864. _this.SAMPLER3DBGRMAP = false;
  31865. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  31866. _this.EXPOSURE = false;
  31867. _this.USEPHYSICALLIGHTFALLOFF = false;
  31868. _this.TWOSIDEDLIGHTING = false;
  31869. _this.SHADOWFLOAT = false;
  31870. _this.USERIGHTHANDEDSYSTEM = false;
  31871. _this.CLIPPLANE = false;
  31872. _this.POINTSIZE = false;
  31873. _this.FOG = false;
  31874. _this.LOGARITHMICDEPTH = false;
  31875. _this.FORCENORMALFORWARD = false;
  31876. _this.rebuild();
  31877. return _this;
  31878. }
  31879. PBRMaterialDefines.prototype.reset = function () {
  31880. _super.prototype.reset.call(this);
  31881. this.ALPHATESTVALUE = 0.5;
  31882. this.PBR = true;
  31883. };
  31884. return PBRMaterialDefines;
  31885. }(BABYLON.MaterialDefines));
  31886. /**
  31887. * The Physically based material base class of BJS.
  31888. *
  31889. * This offers the main features of a standard PBR material.
  31890. * For more information, please refer to the documentation :
  31891. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  31892. */
  31893. var PBRBaseMaterial = (function (_super) {
  31894. __extends(PBRBaseMaterial, _super);
  31895. /**
  31896. * Instantiates a new PBRMaterial instance.
  31897. *
  31898. * @param name The material name
  31899. * @param scene The scene the material will be use in.
  31900. */
  31901. function PBRBaseMaterial(name, scene) {
  31902. var _this = _super.call(this, name, scene) || this;
  31903. /**
  31904. * Intensity of the direct lights e.g. the four lights available in your scene.
  31905. * This impacts both the direct diffuse and specular highlights.
  31906. */
  31907. _this._directIntensity = 1.0;
  31908. /**
  31909. * Intensity of the emissive part of the material.
  31910. * This helps controlling the emissive effect without modifying the emissive color.
  31911. */
  31912. _this._emissiveIntensity = 1.0;
  31913. /**
  31914. * Intensity of the environment e.g. how much the environment will light the object
  31915. * either through harmonics for rough material or through the refelction for shiny ones.
  31916. */
  31917. _this._environmentIntensity = 1.0;
  31918. /**
  31919. * This is a special control allowing the reduction of the specular highlights coming from the
  31920. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  31921. */
  31922. _this._specularIntensity = 1.0;
  31923. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  31924. /**
  31925. * Debug Control allowing disabling the bump map on this material.
  31926. */
  31927. _this._disableBumpMap = false;
  31928. /**
  31929. * AKA Occlusion Texture Intensity in other nomenclature.
  31930. */
  31931. _this._ambientTextureStrength = 1.0;
  31932. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  31933. /**
  31934. * AKA Diffuse Color in other nomenclature.
  31935. */
  31936. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  31937. /**
  31938. * AKA Specular Color in other nomenclature.
  31939. */
  31940. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  31941. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  31942. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  31943. /**
  31944. * AKA Glossiness in other nomenclature.
  31945. */
  31946. _this._microSurface = 0.9;
  31947. /**
  31948. * source material index of refraction (IOR)' / 'destination material IOR.
  31949. */
  31950. _this._indexOfRefraction = 0.66;
  31951. /**
  31952. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  31953. */
  31954. _this._invertRefractionY = false;
  31955. /**
  31956. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  31957. * Materials half opaque for instance using refraction could benefit from this control.
  31958. */
  31959. _this._linkRefractionWithTransparency = false;
  31960. _this._useLightmapAsShadowmap = false;
  31961. /**
  31962. * Specifies that the alpha is coming form the albedo channel alpha channel.
  31963. */
  31964. _this._useAlphaFromAlbedoTexture = false;
  31965. /**
  31966. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  31967. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  31968. */
  31969. _this._useSpecularOverAlpha = true;
  31970. /**
  31971. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  31972. */
  31973. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  31974. /**
  31975. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  31976. */
  31977. _this._useRoughnessFromMetallicTextureAlpha = true;
  31978. /**
  31979. * Specifies if the metallic texture contains the roughness information in its green channel.
  31980. */
  31981. _this._useRoughnessFromMetallicTextureGreen = false;
  31982. /**
  31983. * Specifies if the metallic texture contains the metallness information in its blue channel.
  31984. */
  31985. _this._useMetallnessFromMetallicTextureBlue = false;
  31986. /**
  31987. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  31988. */
  31989. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  31990. /**
  31991. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  31992. */
  31993. _this._useAmbientInGrayScale = false;
  31994. /**
  31995. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  31996. * The material will try to infer what glossiness each pixel should be.
  31997. */
  31998. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  31999. /**
  32000. * BJS is using an harcoded light falloff based on a manually sets up range.
  32001. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  32002. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  32003. */
  32004. _this._usePhysicalLightFalloff = true;
  32005. /**
  32006. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  32007. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  32008. */
  32009. _this._useRadianceOverAlpha = true;
  32010. /**
  32011. * Allows using the bump map in parallax mode.
  32012. */
  32013. _this._useParallax = false;
  32014. /**
  32015. * Allows using the bump map in parallax occlusion mode.
  32016. */
  32017. _this._useParallaxOcclusion = false;
  32018. /**
  32019. * Controls the scale bias of the parallax mode.
  32020. */
  32021. _this._parallaxScaleBias = 0.05;
  32022. /**
  32023. * If sets to true, disables all the lights affecting the material.
  32024. */
  32025. _this._disableLighting = false;
  32026. /**
  32027. * Number of Simultaneous lights allowed on the material.
  32028. */
  32029. _this._maxSimultaneousLights = 4;
  32030. /**
  32031. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  32032. */
  32033. _this._invertNormalMapX = false;
  32034. /**
  32035. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  32036. */
  32037. _this._invertNormalMapY = false;
  32038. /**
  32039. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  32040. */
  32041. _this._twoSidedLighting = false;
  32042. /**
  32043. * Defines the alpha limits in alpha test mode.
  32044. */
  32045. _this._alphaCutOff = 0.4;
  32046. /**
  32047. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  32048. */
  32049. _this._forceAlphaTest = false;
  32050. /**
  32051. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  32052. * in your scene composition.
  32053. */
  32054. _this._preMultiplyAlpha = false;
  32055. /**
  32056. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  32057. * And/Or occlude the blended part.
  32058. */
  32059. _this._useAlphaFresnel = false;
  32060. /**
  32061. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  32062. * from cos thetav and roughness:
  32063. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  32064. */
  32065. _this._environmentBRDFTexture = null;
  32066. /**
  32067. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  32068. */
  32069. _this._forceIrradianceInFragment = false;
  32070. /**
  32071. * Force normal to face away from face.
  32072. * (Temporary internal fix to remove before 3.1)
  32073. */
  32074. _this._forceNormalForward = false;
  32075. _this._renderTargets = new BABYLON.SmartArray(16);
  32076. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  32077. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  32078. _this._tempColor = new BABYLON.Color3();
  32079. // Setup the default processing configuration to the scene.
  32080. _this._attachImageProcessingConfiguration(null);
  32081. _this.getRenderTargetTextures = function () {
  32082. _this._renderTargets.reset();
  32083. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  32084. _this._renderTargets.push(_this._reflectionTexture);
  32085. }
  32086. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  32087. _this._renderTargets.push(_this._refractionTexture);
  32088. }
  32089. return _this._renderTargets;
  32090. };
  32091. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  32092. return _this;
  32093. }
  32094. /**
  32095. * Attaches a new image processing configuration to the PBR Material.
  32096. * @param configuration
  32097. */
  32098. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  32099. var _this = this;
  32100. if (configuration === this._imageProcessingConfiguration) {
  32101. return;
  32102. }
  32103. // Detaches observer.
  32104. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  32105. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  32106. }
  32107. // Pick the scene configuration if needed.
  32108. if (!configuration) {
  32109. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  32110. }
  32111. else {
  32112. this._imageProcessingConfiguration = configuration;
  32113. }
  32114. // Attaches observer.
  32115. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  32116. _this._markAllSubMeshesAsImageProcessingDirty();
  32117. });
  32118. };
  32119. PBRBaseMaterial.prototype.getClassName = function () {
  32120. return "PBRBaseMaterial";
  32121. };
  32122. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  32123. get: function () {
  32124. return this._useLogarithmicDepth;
  32125. },
  32126. set: function (value) {
  32127. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  32128. },
  32129. enumerable: true,
  32130. configurable: true
  32131. });
  32132. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  32133. if (this._linkRefractionWithTransparency) {
  32134. return false;
  32135. }
  32136. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  32137. };
  32138. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  32139. if (this._forceAlphaTest) {
  32140. return true;
  32141. }
  32142. if (this._linkRefractionWithTransparency) {
  32143. return false;
  32144. }
  32145. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  32146. };
  32147. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  32148. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  32149. };
  32150. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  32151. return this._albedoTexture;
  32152. };
  32153. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  32154. if (this.isFrozen) {
  32155. if (this._wasPreviouslyReady) {
  32156. return true;
  32157. }
  32158. }
  32159. if (!subMesh._materialDefines) {
  32160. subMesh._materialDefines = new PBRMaterialDefines();
  32161. }
  32162. var scene = this.getScene();
  32163. var defines = subMesh._materialDefines;
  32164. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  32165. if (defines._renderId === scene.getRenderId()) {
  32166. return true;
  32167. }
  32168. }
  32169. var engine = scene.getEngine();
  32170. // Lights
  32171. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  32172. defines._needNormals = true;
  32173. // Textures
  32174. if (defines._areTexturesDirty) {
  32175. defines._needUVs = false;
  32176. if (scene.texturesEnabled) {
  32177. if (scene.getEngine().getCaps().textureLOD) {
  32178. defines.LODBASEDMICROSFURACE = true;
  32179. }
  32180. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32181. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  32182. return false;
  32183. }
  32184. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  32185. }
  32186. else {
  32187. defines.ALBEDO = false;
  32188. }
  32189. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  32190. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  32191. return false;
  32192. }
  32193. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  32194. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  32195. }
  32196. else {
  32197. defines.AMBIENT = false;
  32198. }
  32199. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  32200. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  32201. return false;
  32202. }
  32203. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  32204. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  32205. }
  32206. else {
  32207. defines.OPACITY = false;
  32208. }
  32209. var reflectionTexture = this._getReflectionTexture();
  32210. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32211. if (!reflectionTexture.isReadyOrNotBlocking()) {
  32212. return false;
  32213. }
  32214. defines.REFLECTION = true;
  32215. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  32216. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  32217. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  32218. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  32219. defines.INVERTCUBICMAP = true;
  32220. }
  32221. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  32222. switch (reflectionTexture.coordinatesMode) {
  32223. case BABYLON.Texture.CUBIC_MODE:
  32224. case BABYLON.Texture.INVCUBIC_MODE:
  32225. defines.REFLECTIONMAP_CUBIC = true;
  32226. break;
  32227. case BABYLON.Texture.EXPLICIT_MODE:
  32228. defines.REFLECTIONMAP_EXPLICIT = true;
  32229. break;
  32230. case BABYLON.Texture.PLANAR_MODE:
  32231. defines.REFLECTIONMAP_PLANAR = true;
  32232. break;
  32233. case BABYLON.Texture.PROJECTION_MODE:
  32234. defines.REFLECTIONMAP_PROJECTION = true;
  32235. break;
  32236. case BABYLON.Texture.SKYBOX_MODE:
  32237. defines.REFLECTIONMAP_SKYBOX = true;
  32238. break;
  32239. case BABYLON.Texture.SPHERICAL_MODE:
  32240. defines.REFLECTIONMAP_SPHERICAL = true;
  32241. break;
  32242. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  32243. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  32244. break;
  32245. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  32246. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  32247. break;
  32248. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  32249. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  32250. break;
  32251. }
  32252. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  32253. if (reflectionTexture.sphericalPolynomial) {
  32254. defines.USESPHERICALFROMREFLECTIONMAP = true;
  32255. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  32256. defines.USESPHERICALINFRAGMENT = true;
  32257. }
  32258. }
  32259. }
  32260. }
  32261. else {
  32262. defines.REFLECTION = false;
  32263. defines.REFLECTIONMAP_3D = false;
  32264. defines.REFLECTIONMAP_SPHERICAL = false;
  32265. defines.REFLECTIONMAP_PLANAR = false;
  32266. defines.REFLECTIONMAP_CUBIC = false;
  32267. defines.REFLECTIONMAP_PROJECTION = false;
  32268. defines.REFLECTIONMAP_SKYBOX = false;
  32269. defines.REFLECTIONMAP_EXPLICIT = false;
  32270. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  32271. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  32272. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  32273. defines.INVERTCUBICMAP = false;
  32274. defines.USESPHERICALFROMREFLECTIONMAP = false;
  32275. defines.USESPHERICALINFRAGMENT = false;
  32276. defines.REFLECTIONMAP_OPPOSITEZ = false;
  32277. defines.LODINREFLECTIONALPHA = false;
  32278. defines.GAMMAREFLECTION = false;
  32279. }
  32280. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  32281. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  32282. return false;
  32283. }
  32284. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  32285. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  32286. }
  32287. else {
  32288. defines.LIGHTMAP = false;
  32289. }
  32290. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  32291. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  32292. return false;
  32293. }
  32294. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  32295. }
  32296. else {
  32297. defines.EMISSIVE = false;
  32298. }
  32299. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  32300. if (this._metallicTexture) {
  32301. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  32302. return false;
  32303. }
  32304. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  32305. defines.METALLICWORKFLOW = true;
  32306. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  32307. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  32308. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  32309. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  32310. }
  32311. else if (this._reflectivityTexture) {
  32312. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  32313. return false;
  32314. }
  32315. defines.METALLICWORKFLOW = false;
  32316. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  32317. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  32318. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  32319. }
  32320. else {
  32321. defines.METALLICWORKFLOW = false;
  32322. defines.REFLECTIVITY = false;
  32323. }
  32324. if (this._microSurfaceTexture) {
  32325. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  32326. return false;
  32327. }
  32328. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  32329. }
  32330. else {
  32331. defines.MICROSURFACEMAP = false;
  32332. }
  32333. }
  32334. else {
  32335. defines.REFLECTIVITY = false;
  32336. defines.MICROSURFACEMAP = false;
  32337. }
  32338. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  32339. // Bump texure can not be none blocking.
  32340. if (!this._bumpTexture.isReady()) {
  32341. return false;
  32342. }
  32343. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  32344. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32345. defines.PARALLAX = true;
  32346. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  32347. }
  32348. else {
  32349. defines.PARALLAX = false;
  32350. }
  32351. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  32352. }
  32353. else {
  32354. defines.BUMP = false;
  32355. }
  32356. var refractionTexture = this._getRefractionTexture();
  32357. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32358. if (!refractionTexture.isReadyOrNotBlocking()) {
  32359. return false;
  32360. }
  32361. defines.REFRACTION = true;
  32362. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  32363. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  32364. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  32365. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  32366. if (this._linkRefractionWithTransparency) {
  32367. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  32368. }
  32369. }
  32370. else {
  32371. defines.REFRACTION = false;
  32372. }
  32373. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32374. // This is blocking.
  32375. if (!this._environmentBRDFTexture.isReady()) {
  32376. return false;
  32377. }
  32378. defines.ENVIRONMENTBRDF = true;
  32379. }
  32380. if (this._shouldUseAlphaFromAlbedoTexture()) {
  32381. defines.ALPHAFROMALBEDO = true;
  32382. }
  32383. }
  32384. if (this._useSpecularOverAlpha) {
  32385. defines.SPECULAROVERALPHA = true;
  32386. }
  32387. if (this._usePhysicalLightFalloff) {
  32388. defines.USEPHYSICALLIGHTFALLOFF = true;
  32389. }
  32390. if (this._useRadianceOverAlpha) {
  32391. defines.RADIANCEOVERALPHA = true;
  32392. }
  32393. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  32394. defines.METALLICWORKFLOW = true;
  32395. }
  32396. if (!this.backFaceCulling && this._twoSidedLighting) {
  32397. defines.TWOSIDEDLIGHTING = true;
  32398. }
  32399. defines.ALPHATESTVALUE = this._alphaCutOff;
  32400. defines.PREMULTIPLYALPHA = this._preMultiplyAlpha;
  32401. defines.ALPHABLEND = this.needAlphaBlending();
  32402. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  32403. }
  32404. if (defines._areImageProcessingDirty) {
  32405. if (!this._imageProcessingConfiguration.isReady()) {
  32406. return false;
  32407. }
  32408. this._imageProcessingConfiguration.prepareDefines(defines);
  32409. }
  32410. defines.FORCENORMALFORWARD = this._forceNormalForward;
  32411. // Misc.
  32412. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  32413. // Values that need to be evaluated on every frame
  32414. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  32415. // Attribs
  32416. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  32417. if (mesh) {
  32418. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32419. mesh.createNormals(true);
  32420. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  32421. }
  32422. }
  32423. }
  32424. // Get correct effect
  32425. if (defines.isDirty) {
  32426. defines.markAsProcessed();
  32427. scene.resetCachedMaterial();
  32428. // Fallbacks
  32429. var fallbacks = new BABYLON.EffectFallbacks();
  32430. if (defines.ENVIRONMENTBRDF) {
  32431. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  32432. }
  32433. if (defines.REFLECTION) {
  32434. fallbacks.addFallback(0, "REFLECTION");
  32435. }
  32436. if (defines.REFRACTION) {
  32437. fallbacks.addFallback(0, "REFRACTION");
  32438. }
  32439. if (defines.REFLECTIVITY) {
  32440. fallbacks.addFallback(0, "REFLECTIVITY");
  32441. }
  32442. if (defines.BUMP) {
  32443. fallbacks.addFallback(0, "BUMP");
  32444. }
  32445. if (defines.PARALLAX) {
  32446. fallbacks.addFallback(1, "PARALLAX");
  32447. }
  32448. if (defines.PARALLAXOCCLUSION) {
  32449. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  32450. }
  32451. if (defines.SPECULAROVERALPHA) {
  32452. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  32453. }
  32454. if (defines.FOG) {
  32455. fallbacks.addFallback(1, "FOG");
  32456. }
  32457. if (defines.POINTSIZE) {
  32458. fallbacks.addFallback(0, "POINTSIZE");
  32459. }
  32460. if (defines.LOGARITHMICDEPTH) {
  32461. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  32462. }
  32463. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  32464. if (defines.SPECULARTERM) {
  32465. fallbacks.addFallback(0, "SPECULARTERM");
  32466. }
  32467. if (defines.NUM_BONE_INFLUENCERS > 0) {
  32468. fallbacks.addCPUSkinningFallback(0, mesh);
  32469. }
  32470. //Attributes
  32471. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32472. if (defines.NORMAL) {
  32473. attribs.push(BABYLON.VertexBuffer.NormalKind);
  32474. }
  32475. if (defines.TANGENT) {
  32476. attribs.push(BABYLON.VertexBuffer.TangentKind);
  32477. }
  32478. if (defines.UV1) {
  32479. attribs.push(BABYLON.VertexBuffer.UVKind);
  32480. }
  32481. if (defines.UV2) {
  32482. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32483. }
  32484. if (defines.VERTEXCOLOR) {
  32485. attribs.push(BABYLON.VertexBuffer.ColorKind);
  32486. }
  32487. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  32488. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  32489. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  32490. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  32491. "vFogInfos", "vFogColor", "pointSize",
  32492. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  32493. "mBones",
  32494. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  32495. "vLightingIntensity",
  32496. "logarithmicDepthConstant",
  32497. "vSphericalX", "vSphericalY", "vSphericalZ",
  32498. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  32499. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  32500. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  32501. "vNormalReoderParams"
  32502. ];
  32503. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  32504. "bumpSampler", "lightmapSampler", "opacitySampler",
  32505. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  32506. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  32507. "microSurfaceSampler", "environmentBrdfSampler"];
  32508. var uniformBuffers = ["Material", "Scene"];
  32509. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  32510. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  32511. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  32512. uniformsNames: uniforms,
  32513. uniformBuffersNames: uniformBuffers,
  32514. samplers: samplers,
  32515. defines: defines,
  32516. maxSimultaneousLights: this._maxSimultaneousLights
  32517. });
  32518. var onCompiled = function (effect) {
  32519. if (this.onCompiled) {
  32520. this.onCompiled(effect);
  32521. }
  32522. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  32523. }.bind(this);
  32524. var join = defines.toString();
  32525. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  32526. attributes: attribs,
  32527. uniformsNames: uniforms,
  32528. uniformBuffersNames: uniformBuffers,
  32529. samplers: samplers,
  32530. defines: join,
  32531. fallbacks: fallbacks,
  32532. onCompiled: onCompiled,
  32533. onError: this.onError,
  32534. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  32535. }, engine), defines);
  32536. this.buildUniformLayout();
  32537. }
  32538. if (!subMesh.effect.isReady()) {
  32539. return false;
  32540. }
  32541. defines._renderId = scene.getRenderId();
  32542. this._wasPreviouslyReady = true;
  32543. return true;
  32544. };
  32545. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  32546. // Order is important !
  32547. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  32548. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  32549. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  32550. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  32551. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  32552. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  32553. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  32554. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  32555. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  32556. this._uniformBuffer.addUniform("vBumpInfos", 3);
  32557. this._uniformBuffer.addUniform("albedoMatrix", 16);
  32558. this._uniformBuffer.addUniform("ambientMatrix", 16);
  32559. this._uniformBuffer.addUniform("opacityMatrix", 16);
  32560. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  32561. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  32562. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  32563. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  32564. this._uniformBuffer.addUniform("bumpMatrix", 16);
  32565. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  32566. this._uniformBuffer.addUniform("refractionMatrix", 16);
  32567. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  32568. this._uniformBuffer.addUniform("vReflectionColor", 3);
  32569. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  32570. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  32571. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  32572. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  32573. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  32574. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  32575. this._uniformBuffer.addUniform("pointSize", 1);
  32576. this._uniformBuffer.create();
  32577. };
  32578. PBRBaseMaterial.prototype.unbind = function () {
  32579. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  32580. this._uniformBuffer.setTexture("reflectionSampler", null);
  32581. }
  32582. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  32583. this._uniformBuffer.setTexture("refractionSampler", null);
  32584. }
  32585. _super.prototype.unbind.call(this);
  32586. };
  32587. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  32588. this._activeEffect.setMatrix("world", world);
  32589. };
  32590. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  32591. var scene = this.getScene();
  32592. var defines = subMesh._materialDefines;
  32593. if (!defines) {
  32594. return;
  32595. }
  32596. var effect = subMesh.effect;
  32597. this._activeEffect = effect;
  32598. // Matrices
  32599. this.bindOnlyWorldMatrix(world);
  32600. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  32601. // Bones
  32602. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  32603. if (mustRebind) {
  32604. this._uniformBuffer.bindToEffect(effect, "Material");
  32605. this.bindViewProjection(effect);
  32606. var reflectionTexture = this._getReflectionTexture();
  32607. var refractionTexture = this._getRefractionTexture();
  32608. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  32609. // Texture uniforms
  32610. if (scene.texturesEnabled) {
  32611. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32612. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  32613. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  32614. }
  32615. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  32616. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  32617. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  32618. }
  32619. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  32620. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  32621. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  32622. }
  32623. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32624. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  32625. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  32626. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  32627. var polynomials = reflectionTexture.sphericalPolynomial;
  32628. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  32629. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  32630. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  32631. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  32632. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  32633. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  32634. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  32635. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  32636. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  32637. }
  32638. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  32639. }
  32640. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  32641. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  32642. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  32643. }
  32644. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  32645. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  32646. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  32647. }
  32648. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  32649. if (this._metallicTexture) {
  32650. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  32651. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  32652. }
  32653. else if (this._reflectivityTexture) {
  32654. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  32655. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  32656. }
  32657. if (this._microSurfaceTexture) {
  32658. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  32659. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  32660. }
  32661. }
  32662. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  32663. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  32664. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  32665. if (scene._mirroredCameraPosition) {
  32666. 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);
  32667. }
  32668. else {
  32669. 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);
  32670. }
  32671. }
  32672. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32673. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  32674. var depth = 1.0;
  32675. if (!refractionTexture.isCube) {
  32676. if (refractionTexture.depth) {
  32677. depth = refractionTexture.depth;
  32678. }
  32679. }
  32680. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  32681. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  32682. }
  32683. }
  32684. // Point size
  32685. if (this.pointsCloud) {
  32686. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  32687. }
  32688. // Colors
  32689. if (defines.METALLICWORKFLOW) {
  32690. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  32691. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  32692. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  32693. }
  32694. else {
  32695. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  32696. }
  32697. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  32698. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  32699. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  32700. // Misc
  32701. this._lightingInfos.x = this._directIntensity;
  32702. this._lightingInfos.y = this._emissiveIntensity;
  32703. this._lightingInfos.z = this._environmentIntensity;
  32704. this._lightingInfos.w = this._specularIntensity;
  32705. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  32706. }
  32707. // Textures
  32708. if (scene.texturesEnabled) {
  32709. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32710. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  32711. }
  32712. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  32713. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  32714. }
  32715. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  32716. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  32717. }
  32718. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32719. if (defines.LODBASEDMICROSFURACE) {
  32720. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  32721. }
  32722. else {
  32723. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  32724. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  32725. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  32726. }
  32727. }
  32728. if (defines.ENVIRONMENTBRDF) {
  32729. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  32730. }
  32731. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32732. if (defines.LODBASEDMICROSFURACE) {
  32733. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  32734. }
  32735. else {
  32736. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  32737. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  32738. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  32739. }
  32740. }
  32741. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  32742. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  32743. }
  32744. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  32745. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  32746. }
  32747. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  32748. if (this._metallicTexture) {
  32749. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  32750. }
  32751. else if (this._reflectivityTexture) {
  32752. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  32753. }
  32754. if (this._microSurfaceTexture) {
  32755. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  32756. }
  32757. }
  32758. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  32759. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  32760. }
  32761. }
  32762. // Clip plane
  32763. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  32764. // Colors
  32765. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  32766. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  32767. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, scene._mirroredCameraPosition ? -1 : 1);
  32768. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  32769. }
  32770. if (mustRebind || !this.isFrozen) {
  32771. // Lights
  32772. if (scene.lightsEnabled && !this._disableLighting) {
  32773. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  32774. }
  32775. // View
  32776. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  32777. this.bindView(effect);
  32778. }
  32779. // Fog
  32780. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  32781. // Morph targets
  32782. if (defines.NUM_MORPH_INFLUENCERS) {
  32783. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  32784. }
  32785. // image processing
  32786. this._imageProcessingConfiguration.bind(this._activeEffect);
  32787. // Log. depth
  32788. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  32789. }
  32790. this._uniformBuffer.update();
  32791. this._afterBind(mesh);
  32792. scene = null;
  32793. };
  32794. PBRBaseMaterial.prototype.getAnimatables = function () {
  32795. var results = [];
  32796. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  32797. results.push(this._albedoTexture);
  32798. }
  32799. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  32800. results.push(this._ambientTexture);
  32801. }
  32802. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  32803. results.push(this._opacityTexture);
  32804. }
  32805. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  32806. results.push(this._reflectionTexture);
  32807. }
  32808. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  32809. results.push(this._emissiveTexture);
  32810. }
  32811. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  32812. results.push(this._metallicTexture);
  32813. }
  32814. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  32815. results.push(this._reflectivityTexture);
  32816. }
  32817. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  32818. results.push(this._bumpTexture);
  32819. }
  32820. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  32821. results.push(this._lightmapTexture);
  32822. }
  32823. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  32824. results.push(this._refractionTexture);
  32825. }
  32826. return results;
  32827. };
  32828. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  32829. if (this._reflectionTexture) {
  32830. return this._reflectionTexture;
  32831. }
  32832. return this.getScene().environmentTexture;
  32833. };
  32834. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  32835. if (this._refractionTexture) {
  32836. return this._refractionTexture;
  32837. }
  32838. if (this._linkRefractionWithTransparency) {
  32839. return this.getScene().environmentTexture;
  32840. }
  32841. return null;
  32842. };
  32843. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32844. if (forceDisposeTextures) {
  32845. if (this._albedoTexture) {
  32846. this._albedoTexture.dispose();
  32847. }
  32848. if (this._ambientTexture) {
  32849. this._ambientTexture.dispose();
  32850. }
  32851. if (this._opacityTexture) {
  32852. this._opacityTexture.dispose();
  32853. }
  32854. if (this._reflectionTexture) {
  32855. this._reflectionTexture.dispose();
  32856. }
  32857. if (this._environmentBRDFTexture) {
  32858. this._environmentBRDFTexture.dispose();
  32859. }
  32860. if (this._emissiveTexture) {
  32861. this._emissiveTexture.dispose();
  32862. }
  32863. if (this._metallicTexture) {
  32864. this._metallicTexture.dispose();
  32865. }
  32866. if (this._reflectivityTexture) {
  32867. this._reflectivityTexture.dispose();
  32868. }
  32869. if (this._bumpTexture) {
  32870. this._bumpTexture.dispose();
  32871. }
  32872. if (this._lightmapTexture) {
  32873. this._lightmapTexture.dispose();
  32874. }
  32875. if (this._refractionTexture) {
  32876. this._refractionTexture.dispose();
  32877. }
  32878. }
  32879. this._renderTargets.dispose();
  32880. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  32881. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  32882. }
  32883. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  32884. };
  32885. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  32886. __decorate([
  32887. BABYLON.serializeAsImageProcessingConfiguration()
  32888. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  32889. __decorate([
  32890. BABYLON.serialize()
  32891. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  32892. return PBRBaseMaterial;
  32893. }(BABYLON.PushMaterial));
  32894. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  32895. })(BABYLON || (BABYLON = {}));
  32896. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  32897. var BABYLON;
  32898. (function (BABYLON) {
  32899. var Internals;
  32900. (function (Internals) {
  32901. /**
  32902. * The Physically based simple base material of BJS.
  32903. *
  32904. * This enables better naming and convention enforcements on top of the pbrMaterial.
  32905. * It is used as the base class for both the specGloss and metalRough conventions.
  32906. */
  32907. var PBRBaseSimpleMaterial = (function (_super) {
  32908. __extends(PBRBaseSimpleMaterial, _super);
  32909. /**
  32910. * Instantiates a new PBRMaterial instance.
  32911. *
  32912. * @param name The material name
  32913. * @param scene The scene the material will be use in.
  32914. */
  32915. function PBRBaseSimpleMaterial(name, scene) {
  32916. var _this = _super.call(this, name, scene) || this;
  32917. /**
  32918. * Number of Simultaneous lights allowed on the material.
  32919. */
  32920. _this.maxSimultaneousLights = 4;
  32921. /**
  32922. * If sets to true, disables all the lights affecting the material.
  32923. */
  32924. _this.disableLighting = false;
  32925. /**
  32926. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  32927. */
  32928. _this.invertNormalMapX = false;
  32929. /**
  32930. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  32931. */
  32932. _this.invertNormalMapY = false;
  32933. /**
  32934. * Emissivie color used to self-illuminate the model.
  32935. */
  32936. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  32937. /**
  32938. * Occlusion Channel Strenght.
  32939. */
  32940. _this.occlusionStrength = 1.0;
  32941. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  32942. _this._useAmbientInGrayScale = true;
  32943. return _this;
  32944. }
  32945. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  32946. /**
  32947. * Gets the current transparency mode.
  32948. */
  32949. get: function () {
  32950. return this._transparencyMode;
  32951. },
  32952. /**
  32953. * Sets the transparency mode of the material.
  32954. */
  32955. set: function (value) {
  32956. if (this._transparencyMode === value) {
  32957. return;
  32958. }
  32959. this._transparencyMode = value;
  32960. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  32961. this._forceAlphaTest = true;
  32962. }
  32963. else {
  32964. this._forceAlphaTest = false;
  32965. }
  32966. this._markAllSubMeshesAsTexturesDirty();
  32967. },
  32968. enumerable: true,
  32969. configurable: true
  32970. });
  32971. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  32972. /**
  32973. * Gets the current double sided mode.
  32974. */
  32975. get: function () {
  32976. return this._twoSidedLighting;
  32977. },
  32978. /**
  32979. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  32980. */
  32981. set: function (value) {
  32982. if (this._twoSidedLighting === value) {
  32983. return;
  32984. }
  32985. this._twoSidedLighting = value;
  32986. this.backFaceCulling = !value;
  32987. this._markAllSubMeshesAsTexturesDirty();
  32988. },
  32989. enumerable: true,
  32990. configurable: true
  32991. });
  32992. /**
  32993. * Specifies wether or not the alpha value of the albedo texture should be used.
  32994. */
  32995. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  32996. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  32997. };
  32998. /**
  32999. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  33000. */
  33001. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  33002. if (this._linkRefractionWithTransparency) {
  33003. return false;
  33004. }
  33005. return (this.alpha < 1.0) ||
  33006. (this._shouldUseAlphaFromAlbedoTexture() &&
  33007. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  33008. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  33009. };
  33010. /**
  33011. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  33012. */
  33013. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  33014. if (this._linkRefractionWithTransparency) {
  33015. return false;
  33016. }
  33017. return this._shouldUseAlphaFromAlbedoTexture() &&
  33018. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  33019. };
  33020. /**
  33021. * Return the active textures of the material.
  33022. */
  33023. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  33024. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33025. if (this.environmentTexture) {
  33026. activeTextures.push(this.environmentTexture);
  33027. }
  33028. if (this.normalTexture) {
  33029. activeTextures.push(this.normalTexture);
  33030. }
  33031. if (this.emissiveTexture) {
  33032. activeTextures.push(this.emissiveTexture);
  33033. }
  33034. if (this.occlusionTexture) {
  33035. activeTextures.push(this.occlusionTexture);
  33036. }
  33037. return activeTextures;
  33038. };
  33039. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  33040. return "PBRBaseSimpleMaterial";
  33041. };
  33042. __decorate([
  33043. BABYLON.serialize(),
  33044. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33045. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  33046. __decorate([
  33047. BABYLON.serialize(),
  33048. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33049. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  33050. __decorate([
  33051. BABYLON.serializeAsTexture(),
  33052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  33053. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  33054. __decorate([
  33055. BABYLON.serialize(),
  33056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33057. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  33058. __decorate([
  33059. BABYLON.serialize(),
  33060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33061. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  33062. __decorate([
  33063. BABYLON.serializeAsTexture(),
  33064. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  33065. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  33066. __decorate([
  33067. BABYLON.serializeAsColor3("emissive"),
  33068. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33069. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  33070. __decorate([
  33071. BABYLON.serializeAsTexture(),
  33072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33073. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  33074. __decorate([
  33075. BABYLON.serialize(),
  33076. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  33077. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  33078. __decorate([
  33079. BABYLON.serializeAsTexture(),
  33080. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  33081. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  33082. __decorate([
  33083. BABYLON.serialize(),
  33084. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  33085. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  33086. __decorate([
  33087. BABYLON.serialize()
  33088. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  33089. __decorate([
  33090. BABYLON.serialize()
  33091. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  33092. return PBRBaseSimpleMaterial;
  33093. }(BABYLON.PBRBaseMaterial));
  33094. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  33095. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33096. })(BABYLON || (BABYLON = {}));
  33097. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  33098. var BABYLON;
  33099. (function (BABYLON) {
  33100. /**
  33101. * The Physically based material of BJS.
  33102. *
  33103. * This offers the main features of a standard PBR material.
  33104. * For more information, please refer to the documentation :
  33105. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  33106. */
  33107. var PBRMaterial = (function (_super) {
  33108. __extends(PBRMaterial, _super);
  33109. /**
  33110. * Instantiates a new PBRMaterial instance.
  33111. *
  33112. * @param name The material name
  33113. * @param scene The scene the material will be use in.
  33114. */
  33115. function PBRMaterial(name, scene) {
  33116. var _this = _super.call(this, name, scene) || this;
  33117. /**
  33118. * Intensity of the direct lights e.g. the four lights available in your scene.
  33119. * This impacts both the direct diffuse and specular highlights.
  33120. */
  33121. _this.directIntensity = 1.0;
  33122. /**
  33123. * Intensity of the emissive part of the material.
  33124. * This helps controlling the emissive effect without modifying the emissive color.
  33125. */
  33126. _this.emissiveIntensity = 1.0;
  33127. /**
  33128. * Intensity of the environment e.g. how much the environment will light the object
  33129. * either through harmonics for rough material or through the refelction for shiny ones.
  33130. */
  33131. _this.environmentIntensity = 1.0;
  33132. /**
  33133. * This is a special control allowing the reduction of the specular highlights coming from the
  33134. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  33135. */
  33136. _this.specularIntensity = 1.0;
  33137. /**
  33138. * Debug Control allowing disabling the bump map on this material.
  33139. */
  33140. _this.disableBumpMap = false;
  33141. /**
  33142. * AKA Occlusion Texture Intensity in other nomenclature.
  33143. */
  33144. _this.ambientTextureStrength = 1.0;
  33145. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  33146. /**
  33147. * AKA Diffuse Color in other nomenclature.
  33148. */
  33149. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  33150. /**
  33151. * AKA Specular Color in other nomenclature.
  33152. */
  33153. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  33154. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  33155. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  33156. /**
  33157. * AKA Glossiness in other nomenclature.
  33158. */
  33159. _this.microSurface = 1.0;
  33160. /**
  33161. * source material index of refraction (IOR)' / 'destination material IOR.
  33162. */
  33163. _this.indexOfRefraction = 0.66;
  33164. /**
  33165. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  33166. */
  33167. _this.invertRefractionY = false;
  33168. /**
  33169. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  33170. * Materials half opaque for instance using refraction could benefit from this control.
  33171. */
  33172. _this.linkRefractionWithTransparency = false;
  33173. _this.useLightmapAsShadowmap = false;
  33174. /**
  33175. * Specifies that the alpha is coming form the albedo channel alpha channel.
  33176. */
  33177. _this.useAlphaFromAlbedoTexture = false;
  33178. /**
  33179. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  33180. */
  33181. _this.forceAlphaTest = false;
  33182. /**
  33183. * Defines the alpha limits in alpha test mode.
  33184. */
  33185. _this.alphaCutOff = 0.4;
  33186. /**
  33187. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  33188. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  33189. */
  33190. _this.useSpecularOverAlpha = true;
  33191. /**
  33192. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  33193. */
  33194. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  33195. /**
  33196. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  33197. */
  33198. _this.useRoughnessFromMetallicTextureAlpha = true;
  33199. /**
  33200. * Specifies if the metallic texture contains the roughness information in its green channel.
  33201. */
  33202. _this.useRoughnessFromMetallicTextureGreen = false;
  33203. /**
  33204. * Specifies if the metallic texture contains the metallness information in its blue channel.
  33205. */
  33206. _this.useMetallnessFromMetallicTextureBlue = false;
  33207. /**
  33208. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  33209. */
  33210. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  33211. /**
  33212. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  33213. */
  33214. _this.useAmbientInGrayScale = false;
  33215. /**
  33216. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  33217. * The material will try to infer what glossiness each pixel should be.
  33218. */
  33219. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  33220. /**
  33221. * BJS is using an harcoded light falloff based on a manually sets up range.
  33222. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  33223. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  33224. */
  33225. _this.usePhysicalLightFalloff = true;
  33226. /**
  33227. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  33228. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  33229. */
  33230. _this.useRadianceOverAlpha = true;
  33231. /**
  33232. * Allows using the bump map in parallax mode.
  33233. */
  33234. _this.useParallax = false;
  33235. /**
  33236. * Allows using the bump map in parallax occlusion mode.
  33237. */
  33238. _this.useParallaxOcclusion = false;
  33239. /**
  33240. * Controls the scale bias of the parallax mode.
  33241. */
  33242. _this.parallaxScaleBias = 0.05;
  33243. /**
  33244. * If sets to true, disables all the lights affecting the material.
  33245. */
  33246. _this.disableLighting = false;
  33247. /**
  33248. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  33249. */
  33250. _this.forceIrradianceInFragment = false;
  33251. /**
  33252. * Number of Simultaneous lights allowed on the material.
  33253. */
  33254. _this.maxSimultaneousLights = 4;
  33255. /**
  33256. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  33257. */
  33258. _this.invertNormalMapX = false;
  33259. /**
  33260. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  33261. */
  33262. _this.invertNormalMapY = false;
  33263. /**
  33264. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33265. */
  33266. _this.twoSidedLighting = false;
  33267. /**
  33268. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  33269. * in your scene composition.
  33270. */
  33271. _this.preMultiplyAlpha = false;
  33272. /**
  33273. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  33274. * And/Or occlude the blended part.
  33275. */
  33276. _this.useAlphaFresnel = false;
  33277. /**
  33278. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  33279. * And/Or occlude the blended part.
  33280. */
  33281. _this.environmentBRDFTexture = null;
  33282. /**
  33283. * Force normal to face away from face.
  33284. * (Temporary internal fix to remove before 3.1)
  33285. */
  33286. _this.forceNormalForward = false;
  33287. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  33288. return _this;
  33289. }
  33290. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  33291. /**
  33292. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  33293. */
  33294. get: function () {
  33295. return this._PBRMATERIAL_OPAQUE;
  33296. },
  33297. enumerable: true,
  33298. configurable: true
  33299. });
  33300. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  33301. /**
  33302. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  33303. */
  33304. get: function () {
  33305. return this._PBRMATERIAL_ALPHATEST;
  33306. },
  33307. enumerable: true,
  33308. configurable: true
  33309. });
  33310. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  33311. /**
  33312. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  33313. */
  33314. get: function () {
  33315. return this._PBRMATERIAL_ALPHABLEND;
  33316. },
  33317. enumerable: true,
  33318. configurable: true
  33319. });
  33320. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  33321. /**
  33322. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  33323. * They are also discarded below the alpha cutoff threshold to improve performances.
  33324. */
  33325. get: function () {
  33326. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  33327. },
  33328. enumerable: true,
  33329. configurable: true
  33330. });
  33331. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  33332. /**
  33333. * Gets the image processing configuration used either in this material.
  33334. */
  33335. get: function () {
  33336. return this._imageProcessingConfiguration;
  33337. },
  33338. /**
  33339. * Sets the Default image processing configuration used either in the this material.
  33340. *
  33341. * If sets to null, the scene one is in use.
  33342. */
  33343. set: function (value) {
  33344. this._attachImageProcessingConfiguration(value);
  33345. // Ensure the effect will be rebuilt.
  33346. this._markAllSubMeshesAsTexturesDirty();
  33347. },
  33348. enumerable: true,
  33349. configurable: true
  33350. });
  33351. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  33352. /**
  33353. * Gets wether the color curves effect is enabled.
  33354. */
  33355. get: function () {
  33356. return this.imageProcessingConfiguration.colorCurvesEnabled;
  33357. },
  33358. /**
  33359. * Sets wether the color curves effect is enabled.
  33360. */
  33361. set: function (value) {
  33362. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  33363. },
  33364. enumerable: true,
  33365. configurable: true
  33366. });
  33367. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  33368. /**
  33369. * Gets wether the color grading effect is enabled.
  33370. */
  33371. get: function () {
  33372. return this.imageProcessingConfiguration.colorGradingEnabled;
  33373. },
  33374. /**
  33375. * Gets wether the color grading effect is enabled.
  33376. */
  33377. set: function (value) {
  33378. this.imageProcessingConfiguration.colorGradingEnabled = value;
  33379. },
  33380. enumerable: true,
  33381. configurable: true
  33382. });
  33383. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  33384. /**
  33385. * Gets wether tonemapping is enabled or not.
  33386. */
  33387. get: function () {
  33388. return this._imageProcessingConfiguration.toneMappingEnabled;
  33389. },
  33390. /**
  33391. * Sets wether tonemapping is enabled or not
  33392. */
  33393. set: function (value) {
  33394. this._imageProcessingConfiguration.toneMappingEnabled = value;
  33395. },
  33396. enumerable: true,
  33397. configurable: true
  33398. });
  33399. ;
  33400. ;
  33401. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  33402. /**
  33403. * The camera exposure used on this material.
  33404. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33405. * This corresponds to a photographic exposure.
  33406. */
  33407. get: function () {
  33408. return this._imageProcessingConfiguration.exposure;
  33409. },
  33410. /**
  33411. * The camera exposure used on this material.
  33412. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33413. * This corresponds to a photographic exposure.
  33414. */
  33415. set: function (value) {
  33416. this._imageProcessingConfiguration.exposure = value;
  33417. },
  33418. enumerable: true,
  33419. configurable: true
  33420. });
  33421. ;
  33422. ;
  33423. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  33424. /**
  33425. * Gets The camera contrast used on this material.
  33426. */
  33427. get: function () {
  33428. return this._imageProcessingConfiguration.contrast;
  33429. },
  33430. /**
  33431. * Sets The camera contrast used on this material.
  33432. */
  33433. set: function (value) {
  33434. this._imageProcessingConfiguration.contrast = value;
  33435. },
  33436. enumerable: true,
  33437. configurable: true
  33438. });
  33439. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  33440. /**
  33441. * Gets the Color Grading 2D Lookup Texture.
  33442. */
  33443. get: function () {
  33444. return this._imageProcessingConfiguration.colorGradingTexture;
  33445. },
  33446. /**
  33447. * Sets the Color Grading 2D Lookup Texture.
  33448. */
  33449. set: function (value) {
  33450. this._imageProcessingConfiguration.colorGradingTexture = value;
  33451. },
  33452. enumerable: true,
  33453. configurable: true
  33454. });
  33455. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  33456. /**
  33457. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33458. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33459. * 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;
  33460. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33461. */
  33462. get: function () {
  33463. return this._imageProcessingConfiguration.colorCurves;
  33464. },
  33465. /**
  33466. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33467. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33468. * 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;
  33469. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33470. */
  33471. set: function (value) {
  33472. this._imageProcessingConfiguration.colorCurves = value;
  33473. },
  33474. enumerable: true,
  33475. configurable: true
  33476. });
  33477. PBRMaterial.prototype.getClassName = function () {
  33478. return "PBRMaterial";
  33479. };
  33480. PBRMaterial.prototype.getActiveTextures = function () {
  33481. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33482. if (this._albedoTexture) {
  33483. activeTextures.push(this._albedoTexture);
  33484. }
  33485. if (this._ambientTexture) {
  33486. activeTextures.push(this._ambientTexture);
  33487. }
  33488. if (this._opacityTexture) {
  33489. activeTextures.push(this._opacityTexture);
  33490. }
  33491. if (this._reflectionTexture) {
  33492. activeTextures.push(this._reflectionTexture);
  33493. }
  33494. if (this._emissiveTexture) {
  33495. activeTextures.push(this._emissiveTexture);
  33496. }
  33497. if (this._reflectivityTexture) {
  33498. activeTextures.push(this._reflectivityTexture);
  33499. }
  33500. if (this._metallicTexture) {
  33501. activeTextures.push(this._metallicTexture);
  33502. }
  33503. if (this._microSurfaceTexture) {
  33504. activeTextures.push(this._microSurfaceTexture);
  33505. }
  33506. if (this._bumpTexture) {
  33507. activeTextures.push(this._bumpTexture);
  33508. }
  33509. if (this._lightmapTexture) {
  33510. activeTextures.push(this._lightmapTexture);
  33511. }
  33512. if (this._refractionTexture) {
  33513. activeTextures.push(this._refractionTexture);
  33514. }
  33515. return activeTextures;
  33516. };
  33517. PBRMaterial.prototype.hasTexture = function (texture) {
  33518. if (_super.prototype.hasTexture.call(this, texture)) {
  33519. return true;
  33520. }
  33521. if (this._albedoTexture === texture) {
  33522. return true;
  33523. }
  33524. if (this._ambientTexture === texture) {
  33525. return true;
  33526. }
  33527. if (this._opacityTexture === texture) {
  33528. return true;
  33529. }
  33530. if (this._reflectionTexture === texture) {
  33531. return true;
  33532. }
  33533. if (this._reflectivityTexture === texture) {
  33534. return true;
  33535. }
  33536. if (this._metallicTexture === texture) {
  33537. return true;
  33538. }
  33539. if (this._microSurfaceTexture === texture) {
  33540. return true;
  33541. }
  33542. if (this._bumpTexture === texture) {
  33543. return true;
  33544. }
  33545. if (this._lightmapTexture === texture) {
  33546. return true;
  33547. }
  33548. if (this._refractionTexture === texture) {
  33549. return true;
  33550. }
  33551. return false;
  33552. };
  33553. PBRMaterial.prototype.clone = function (name) {
  33554. var _this = this;
  33555. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  33556. };
  33557. PBRMaterial.prototype.serialize = function () {
  33558. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  33559. serializationObject.customType = "BABYLON.PBRMaterial";
  33560. return serializationObject;
  33561. };
  33562. // Statics
  33563. PBRMaterial.Parse = function (source, scene, rootUrl) {
  33564. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  33565. };
  33566. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  33567. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  33568. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  33569. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  33570. __decorate([
  33571. BABYLON.serialize(),
  33572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33573. ], PBRMaterial.prototype, "directIntensity", void 0);
  33574. __decorate([
  33575. BABYLON.serialize(),
  33576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33577. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  33578. __decorate([
  33579. BABYLON.serialize(),
  33580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33581. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  33582. __decorate([
  33583. BABYLON.serialize(),
  33584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33585. ], PBRMaterial.prototype, "specularIntensity", void 0);
  33586. __decorate([
  33587. BABYLON.serialize(),
  33588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33589. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  33590. __decorate([
  33591. BABYLON.serializeAsTexture(),
  33592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33593. ], PBRMaterial.prototype, "albedoTexture", void 0);
  33594. __decorate([
  33595. BABYLON.serializeAsTexture(),
  33596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33597. ], PBRMaterial.prototype, "ambientTexture", void 0);
  33598. __decorate([
  33599. BABYLON.serialize(),
  33600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33601. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  33602. __decorate([
  33603. BABYLON.serializeAsTexture(),
  33604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33605. ], PBRMaterial.prototype, "opacityTexture", void 0);
  33606. __decorate([
  33607. BABYLON.serializeAsTexture(),
  33608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33609. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  33610. __decorate([
  33611. BABYLON.serializeAsTexture(),
  33612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33613. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  33614. __decorate([
  33615. BABYLON.serializeAsTexture(),
  33616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33617. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  33618. __decorate([
  33619. BABYLON.serializeAsTexture(),
  33620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33621. ], PBRMaterial.prototype, "metallicTexture", void 0);
  33622. __decorate([
  33623. BABYLON.serialize(),
  33624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33625. ], PBRMaterial.prototype, "metallic", void 0);
  33626. __decorate([
  33627. BABYLON.serialize(),
  33628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33629. ], PBRMaterial.prototype, "roughness", void 0);
  33630. __decorate([
  33631. BABYLON.serializeAsTexture(),
  33632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33633. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  33634. __decorate([
  33635. BABYLON.serializeAsTexture(),
  33636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33637. ], PBRMaterial.prototype, "bumpTexture", void 0);
  33638. __decorate([
  33639. BABYLON.serializeAsTexture(),
  33640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  33641. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  33642. __decorate([
  33643. BABYLON.serializeAsTexture(),
  33644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33645. ], PBRMaterial.prototype, "refractionTexture", void 0);
  33646. __decorate([
  33647. BABYLON.serializeAsColor3("ambient"),
  33648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33649. ], PBRMaterial.prototype, "ambientColor", void 0);
  33650. __decorate([
  33651. BABYLON.serializeAsColor3("albedo"),
  33652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33653. ], PBRMaterial.prototype, "albedoColor", void 0);
  33654. __decorate([
  33655. BABYLON.serializeAsColor3("reflectivity"),
  33656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33657. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  33658. __decorate([
  33659. BABYLON.serializeAsColor3("reflection"),
  33660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33661. ], PBRMaterial.prototype, "reflectionColor", void 0);
  33662. __decorate([
  33663. BABYLON.serializeAsColor3("emissive"),
  33664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33665. ], PBRMaterial.prototype, "emissiveColor", void 0);
  33666. __decorate([
  33667. BABYLON.serialize(),
  33668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33669. ], PBRMaterial.prototype, "microSurface", void 0);
  33670. __decorate([
  33671. BABYLON.serialize(),
  33672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33673. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  33674. __decorate([
  33675. BABYLON.serialize(),
  33676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33677. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  33678. __decorate([
  33679. BABYLON.serialize(),
  33680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33681. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  33682. __decorate([
  33683. BABYLON.serialize(),
  33684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33685. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  33686. __decorate([
  33687. BABYLON.serialize(),
  33688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33689. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  33690. __decorate([
  33691. BABYLON.serialize(),
  33692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33693. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  33694. __decorate([
  33695. BABYLON.serialize(),
  33696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33697. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  33698. __decorate([
  33699. BABYLON.serialize(),
  33700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33701. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  33702. __decorate([
  33703. BABYLON.serialize(),
  33704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33705. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  33706. __decorate([
  33707. BABYLON.serialize(),
  33708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33709. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  33710. __decorate([
  33711. BABYLON.serialize(),
  33712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33713. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  33714. __decorate([
  33715. BABYLON.serialize(),
  33716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33717. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  33718. __decorate([
  33719. BABYLON.serialize(),
  33720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33721. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  33722. __decorate([
  33723. BABYLON.serialize(),
  33724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33725. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  33726. __decorate([
  33727. BABYLON.serialize(),
  33728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33729. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  33730. __decorate([
  33731. BABYLON.serialize(),
  33732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33733. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  33734. __decorate([
  33735. BABYLON.serialize(),
  33736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33737. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  33738. __decorate([
  33739. BABYLON.serialize(),
  33740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33741. ], PBRMaterial.prototype, "useParallax", void 0);
  33742. __decorate([
  33743. BABYLON.serialize(),
  33744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33745. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  33746. __decorate([
  33747. BABYLON.serialize(),
  33748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33749. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  33750. __decorate([
  33751. BABYLON.serialize(),
  33752. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33753. ], PBRMaterial.prototype, "disableLighting", void 0);
  33754. __decorate([
  33755. BABYLON.serialize(),
  33756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33757. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  33758. __decorate([
  33759. BABYLON.serialize(),
  33760. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33761. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  33762. __decorate([
  33763. BABYLON.serialize(),
  33764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33765. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  33766. __decorate([
  33767. BABYLON.serialize(),
  33768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33769. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  33770. __decorate([
  33771. BABYLON.serialize(),
  33772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33773. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  33774. __decorate([
  33775. BABYLON.serialize(),
  33776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33777. ], PBRMaterial.prototype, "preMultiplyAlpha", void 0);
  33778. __decorate([
  33779. BABYLON.serialize(),
  33780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33781. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  33782. __decorate([
  33783. BABYLON.serializeAsTexture(),
  33784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33785. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  33786. __decorate([
  33787. BABYLON.serialize(),
  33788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33789. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  33790. return PBRMaterial;
  33791. }(BABYLON.PBRBaseMaterial));
  33792. BABYLON.PBRMaterial = PBRMaterial;
  33793. })(BABYLON || (BABYLON = {}));
  33794. //# sourceMappingURL=babylon.pbrMaterial.js.map
  33795. var BABYLON;
  33796. (function (BABYLON) {
  33797. /**
  33798. * The PBR material of BJS following the metal roughness convention.
  33799. *
  33800. * This fits to the PBR convention in the GLTF definition:
  33801. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  33802. */
  33803. var PBRMetallicRoughnessMaterial = (function (_super) {
  33804. __extends(PBRMetallicRoughnessMaterial, _super);
  33805. /**
  33806. * Instantiates a new PBRMetalRoughnessMaterial instance.
  33807. *
  33808. * @param name The material name
  33809. * @param scene The scene the material will be use in.
  33810. */
  33811. function PBRMetallicRoughnessMaterial(name, scene) {
  33812. var _this = _super.call(this, name, scene) || this;
  33813. _this._useRoughnessFromMetallicTextureAlpha = false;
  33814. _this._useRoughnessFromMetallicTextureGreen = true;
  33815. _this._useMetallnessFromMetallicTextureBlue = true;
  33816. return _this;
  33817. }
  33818. /**
  33819. * Return the currrent class name of the material.
  33820. */
  33821. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  33822. return "PBRMetallicRoughnessMaterial";
  33823. };
  33824. /**
  33825. * Return the active textures of the material.
  33826. */
  33827. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  33828. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33829. if (this.baseTexture) {
  33830. activeTextures.push(this.baseTexture);
  33831. }
  33832. if (this.metallicRoughnessTexture) {
  33833. activeTextures.push(this.metallicRoughnessTexture);
  33834. }
  33835. return activeTextures;
  33836. };
  33837. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  33838. if (_super.prototype.hasTexture.call(this, texture)) {
  33839. return true;
  33840. }
  33841. if (this.baseTexture === texture) {
  33842. return true;
  33843. }
  33844. if (this.metallicRoughnessTexture === texture) {
  33845. return true;
  33846. }
  33847. return false;
  33848. };
  33849. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  33850. var _this = this;
  33851. return BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  33852. };
  33853. /**
  33854. * Serialize the material to a parsable JSON object.
  33855. */
  33856. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  33857. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  33858. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  33859. return serializationObject;
  33860. };
  33861. /**
  33862. * Parses a JSON object correponding to the serialize function.
  33863. */
  33864. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  33865. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  33866. };
  33867. __decorate([
  33868. BABYLON.serializeAsColor3(),
  33869. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  33870. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  33871. __decorate([
  33872. BABYLON.serializeAsTexture(),
  33873. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  33874. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  33875. __decorate([
  33876. BABYLON.serialize(),
  33877. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33878. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  33879. __decorate([
  33880. BABYLON.serialize(),
  33881. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33882. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  33883. __decorate([
  33884. BABYLON.serializeAsTexture(),
  33885. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  33886. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  33887. return PBRMetallicRoughnessMaterial;
  33888. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  33889. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  33890. })(BABYLON || (BABYLON = {}));
  33891. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  33892. var BABYLON;
  33893. (function (BABYLON) {
  33894. /**
  33895. * The PBR material of BJS following the specular glossiness convention.
  33896. *
  33897. * This fits to the PBR convention in the GLTF definition:
  33898. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  33899. */
  33900. var PBRSpecularGlossinessMaterial = (function (_super) {
  33901. __extends(PBRSpecularGlossinessMaterial, _super);
  33902. /**
  33903. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  33904. *
  33905. * @param name The material name
  33906. * @param scene The scene the material will be use in.
  33907. */
  33908. function PBRSpecularGlossinessMaterial(name, scene) {
  33909. var _this = _super.call(this, name, scene) || this;
  33910. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  33911. return _this;
  33912. }
  33913. /**
  33914. * Return the currrent class name of the material.
  33915. */
  33916. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  33917. return "PBRSpecularGlossinessMaterial";
  33918. };
  33919. /**
  33920. * Return the active textures of the material.
  33921. */
  33922. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  33923. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33924. if (this.diffuseTexture) {
  33925. activeTextures.push(this.diffuseTexture);
  33926. }
  33927. if (this.specularGlossinessTexture) {
  33928. activeTextures.push(this.specularGlossinessTexture);
  33929. }
  33930. return activeTextures;
  33931. };
  33932. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  33933. if (_super.prototype.hasTexture.call(this, texture)) {
  33934. return true;
  33935. }
  33936. if (this.diffuseTexture === texture) {
  33937. return true;
  33938. }
  33939. if (this.specularGlossinessTexture === texture) {
  33940. return true;
  33941. }
  33942. return false;
  33943. };
  33944. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  33945. var _this = this;
  33946. return BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  33947. };
  33948. /**
  33949. * Serialize the material to a parsable JSON object.
  33950. */
  33951. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  33952. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  33953. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  33954. return serializationObject;
  33955. };
  33956. /**
  33957. * Parses a JSON object correponding to the serialize function.
  33958. */
  33959. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  33960. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  33961. };
  33962. __decorate([
  33963. BABYLON.serializeAsColor3("diffuse"),
  33964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  33965. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  33966. __decorate([
  33967. BABYLON.serializeAsTexture(),
  33968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  33969. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  33970. __decorate([
  33971. BABYLON.serializeAsColor3("specular"),
  33972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  33973. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  33974. __decorate([
  33975. BABYLON.serialize(),
  33976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  33977. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  33978. __decorate([
  33979. BABYLON.serializeAsTexture(),
  33980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  33981. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  33982. return PBRSpecularGlossinessMaterial;
  33983. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  33984. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  33985. })(BABYLON || (BABYLON = {}));
  33986. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  33987. var BABYLON;
  33988. (function (BABYLON) {
  33989. BABYLON.CameraInputTypes = {};
  33990. var CameraInputsManager = (function () {
  33991. function CameraInputsManager(camera) {
  33992. this.attached = {};
  33993. this.camera = camera;
  33994. this.checkInputs = function () { };
  33995. }
  33996. CameraInputsManager.prototype.add = function (input) {
  33997. var type = input.getSimpleName();
  33998. if (this.attached[type]) {
  33999. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  34000. return;
  34001. }
  34002. this.attached[type] = input;
  34003. input.camera = this.camera;
  34004. //for checkInputs, we are dynamically creating a function
  34005. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  34006. if (input.checkInputs) {
  34007. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  34008. }
  34009. if (this.attachedElement) {
  34010. input.attachControl(this.attachedElement);
  34011. }
  34012. };
  34013. CameraInputsManager.prototype.remove = function (inputToRemove) {
  34014. for (var cam in this.attached) {
  34015. var input = this.attached[cam];
  34016. if (input === inputToRemove) {
  34017. input.detachControl(this.attachedElement);
  34018. input.camera = null;
  34019. delete this.attached[cam];
  34020. this.rebuildInputCheck();
  34021. }
  34022. }
  34023. };
  34024. CameraInputsManager.prototype.removeByType = function (inputType) {
  34025. for (var cam in this.attached) {
  34026. var input = this.attached[cam];
  34027. if (input.getClassName() === inputType) {
  34028. input.detachControl(this.attachedElement);
  34029. input.camera = null;
  34030. delete this.attached[cam];
  34031. this.rebuildInputCheck();
  34032. }
  34033. }
  34034. };
  34035. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  34036. var current = this.checkInputs;
  34037. return function () {
  34038. current();
  34039. fn();
  34040. };
  34041. };
  34042. CameraInputsManager.prototype.attachInput = function (input) {
  34043. input.attachControl(this.attachedElement, this.noPreventDefault);
  34044. };
  34045. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  34046. if (this.attachedElement) {
  34047. return;
  34048. }
  34049. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  34050. this.attachedElement = element;
  34051. this.noPreventDefault = noPreventDefault;
  34052. for (var cam in this.attached) {
  34053. var input = this.attached[cam];
  34054. this.attached[cam].attachControl(element, noPreventDefault);
  34055. }
  34056. };
  34057. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  34058. if (disconnect === void 0) { disconnect = false; }
  34059. if (this.attachedElement !== element) {
  34060. return;
  34061. }
  34062. for (var cam in this.attached) {
  34063. var input = this.attached[cam];
  34064. this.attached[cam].detachControl(element);
  34065. if (disconnect) {
  34066. this.attached[cam].camera = null;
  34067. }
  34068. }
  34069. this.attachedElement = null;
  34070. };
  34071. CameraInputsManager.prototype.rebuildInputCheck = function () {
  34072. this.checkInputs = function () { };
  34073. for (var cam in this.attached) {
  34074. var input = this.attached[cam];
  34075. if (input.checkInputs) {
  34076. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  34077. }
  34078. }
  34079. };
  34080. CameraInputsManager.prototype.clear = function () {
  34081. if (this.attachedElement) {
  34082. this.detachElement(this.attachedElement, true);
  34083. }
  34084. this.attached = {};
  34085. this.attachedElement = null;
  34086. this.checkInputs = function () { };
  34087. };
  34088. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  34089. var inputs = {};
  34090. for (var cam in this.attached) {
  34091. var input = this.attached[cam];
  34092. var res = BABYLON.SerializationHelper.Serialize(input);
  34093. inputs[input.getClassName()] = res;
  34094. }
  34095. serializedCamera.inputsmgr = inputs;
  34096. };
  34097. CameraInputsManager.prototype.parse = function (parsedCamera) {
  34098. var parsedInputs = parsedCamera.inputsmgr;
  34099. if (parsedInputs) {
  34100. this.clear();
  34101. for (var n in parsedInputs) {
  34102. var construct = BABYLON.CameraInputTypes[n];
  34103. if (construct) {
  34104. var parsedinput = parsedInputs[n];
  34105. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  34106. this.add(input);
  34107. }
  34108. }
  34109. }
  34110. else {
  34111. //2016-03-08 this part is for managing backward compatibility
  34112. for (var n in this.attached) {
  34113. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  34114. if (construct) {
  34115. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  34116. this.remove(this.attached[n]);
  34117. this.add(input);
  34118. }
  34119. }
  34120. }
  34121. };
  34122. return CameraInputsManager;
  34123. }());
  34124. BABYLON.CameraInputsManager = CameraInputsManager;
  34125. })(BABYLON || (BABYLON = {}));
  34126. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  34127. var BABYLON;
  34128. (function (BABYLON) {
  34129. var FreeCameraMouseInput = (function () {
  34130. function FreeCameraMouseInput(touchEnabled) {
  34131. if (touchEnabled === void 0) { touchEnabled = true; }
  34132. this.touchEnabled = touchEnabled;
  34133. this.buttons = [0, 1, 2];
  34134. this.angularSensibility = 2000.0;
  34135. }
  34136. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  34137. var _this = this;
  34138. var engine = this.camera.getEngine();
  34139. if (!this._pointerInput) {
  34140. this._pointerInput = function (p, s) {
  34141. var evt = p.event;
  34142. if (!_this.touchEnabled && evt.pointerType === "touch") {
  34143. return;
  34144. }
  34145. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  34146. return;
  34147. }
  34148. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  34149. try {
  34150. evt.srcElement.setPointerCapture(evt.pointerId);
  34151. }
  34152. catch (e) {
  34153. //Nothing to do with the error. Execution will continue.
  34154. }
  34155. _this.previousPosition = {
  34156. x: evt.clientX,
  34157. y: evt.clientY
  34158. };
  34159. if (!noPreventDefault) {
  34160. evt.preventDefault();
  34161. element.focus();
  34162. }
  34163. }
  34164. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  34165. try {
  34166. evt.srcElement.releasePointerCapture(evt.pointerId);
  34167. }
  34168. catch (e) {
  34169. //Nothing to do with the error.
  34170. }
  34171. _this.previousPosition = null;
  34172. if (!noPreventDefault) {
  34173. evt.preventDefault();
  34174. }
  34175. }
  34176. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  34177. if (!_this.previousPosition || engine.isPointerLock) {
  34178. return;
  34179. }
  34180. var offsetX = evt.clientX - _this.previousPosition.x;
  34181. var offsetY = evt.clientY - _this.previousPosition.y;
  34182. if (_this.camera.getScene().useRightHandedSystem) {
  34183. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  34184. }
  34185. else {
  34186. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  34187. }
  34188. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  34189. _this.previousPosition = {
  34190. x: evt.clientX,
  34191. y: evt.clientY
  34192. };
  34193. if (!noPreventDefault) {
  34194. evt.preventDefault();
  34195. }
  34196. }
  34197. };
  34198. }
  34199. this._onMouseMove = function (evt) {
  34200. if (!engine.isPointerLock) {
  34201. return;
  34202. }
  34203. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  34204. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  34205. if (_this.camera.getScene().useRightHandedSystem) {
  34206. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  34207. }
  34208. else {
  34209. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  34210. }
  34211. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  34212. _this.previousPosition = null;
  34213. if (!noPreventDefault) {
  34214. evt.preventDefault();
  34215. }
  34216. };
  34217. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  34218. element.addEventListener("mousemove", this._onMouseMove, false);
  34219. };
  34220. FreeCameraMouseInput.prototype.detachControl = function (element) {
  34221. if (this._observer && element) {
  34222. this.camera.getScene().onPointerObservable.remove(this._observer);
  34223. element.removeEventListener("mousemove", this._onMouseMove);
  34224. this._observer = null;
  34225. this._onMouseMove = null;
  34226. this.previousPosition = null;
  34227. }
  34228. };
  34229. FreeCameraMouseInput.prototype.getClassName = function () {
  34230. return "FreeCameraMouseInput";
  34231. };
  34232. FreeCameraMouseInput.prototype.getSimpleName = function () {
  34233. return "mouse";
  34234. };
  34235. __decorate([
  34236. BABYLON.serialize()
  34237. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  34238. __decorate([
  34239. BABYLON.serialize()
  34240. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  34241. return FreeCameraMouseInput;
  34242. }());
  34243. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  34244. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  34245. })(BABYLON || (BABYLON = {}));
  34246. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  34247. var BABYLON;
  34248. (function (BABYLON) {
  34249. var FreeCameraKeyboardMoveInput = (function () {
  34250. function FreeCameraKeyboardMoveInput() {
  34251. this._keys = [];
  34252. this.keysUp = [38];
  34253. this.keysDown = [40];
  34254. this.keysLeft = [37];
  34255. this.keysRight = [39];
  34256. }
  34257. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  34258. var _this = this;
  34259. if (this._onCanvasBlurObserver) {
  34260. return;
  34261. }
  34262. this._scene = this.camera.getScene();
  34263. this._engine = this._scene.getEngine();
  34264. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  34265. _this._keys = [];
  34266. });
  34267. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  34268. var evt = info.event;
  34269. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  34270. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34271. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34272. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34273. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  34274. var index = _this._keys.indexOf(evt.keyCode);
  34275. if (index === -1) {
  34276. _this._keys.push(evt.keyCode);
  34277. }
  34278. if (!noPreventDefault) {
  34279. evt.preventDefault();
  34280. }
  34281. }
  34282. }
  34283. else {
  34284. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34285. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34286. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34287. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  34288. var index = _this._keys.indexOf(evt.keyCode);
  34289. if (index >= 0) {
  34290. _this._keys.splice(index, 1);
  34291. }
  34292. if (!noPreventDefault) {
  34293. evt.preventDefault();
  34294. }
  34295. }
  34296. }
  34297. });
  34298. };
  34299. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  34300. if (this._scene) {
  34301. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  34302. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  34303. this._onKeyboardObserver = null;
  34304. this._onCanvasBlurObserver = null;
  34305. }
  34306. this._keys = [];
  34307. };
  34308. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  34309. if (this._onKeyboardObserver) {
  34310. var camera = this.camera;
  34311. // Keyboard
  34312. for (var index = 0; index < this._keys.length; index++) {
  34313. var keyCode = this._keys[index];
  34314. var speed = camera._computeLocalCameraSpeed();
  34315. if (this.keysLeft.indexOf(keyCode) !== -1) {
  34316. camera._localDirection.copyFromFloats(-speed, 0, 0);
  34317. }
  34318. else if (this.keysUp.indexOf(keyCode) !== -1) {
  34319. camera._localDirection.copyFromFloats(0, 0, speed);
  34320. }
  34321. else if (this.keysRight.indexOf(keyCode) !== -1) {
  34322. camera._localDirection.copyFromFloats(speed, 0, 0);
  34323. }
  34324. else if (this.keysDown.indexOf(keyCode) !== -1) {
  34325. camera._localDirection.copyFromFloats(0, 0, -speed);
  34326. }
  34327. if (camera.getScene().useRightHandedSystem) {
  34328. camera._localDirection.z *= -1;
  34329. }
  34330. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  34331. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  34332. camera.cameraDirection.addInPlace(camera._transformedDirection);
  34333. }
  34334. }
  34335. };
  34336. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  34337. return "FreeCameraKeyboardMoveInput";
  34338. };
  34339. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  34340. this._keys = [];
  34341. };
  34342. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  34343. return "keyboard";
  34344. };
  34345. __decorate([
  34346. BABYLON.serialize()
  34347. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  34348. __decorate([
  34349. BABYLON.serialize()
  34350. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  34351. __decorate([
  34352. BABYLON.serialize()
  34353. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  34354. __decorate([
  34355. BABYLON.serialize()
  34356. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  34357. return FreeCameraKeyboardMoveInput;
  34358. }());
  34359. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  34360. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  34361. })(BABYLON || (BABYLON = {}));
  34362. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  34363. var BABYLON;
  34364. (function (BABYLON) {
  34365. var FreeCameraInputsManager = (function (_super) {
  34366. __extends(FreeCameraInputsManager, _super);
  34367. function FreeCameraInputsManager(camera) {
  34368. return _super.call(this, camera) || this;
  34369. }
  34370. FreeCameraInputsManager.prototype.addKeyboard = function () {
  34371. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  34372. return this;
  34373. };
  34374. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  34375. if (touchEnabled === void 0) { touchEnabled = true; }
  34376. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  34377. return this;
  34378. };
  34379. FreeCameraInputsManager.prototype.addGamepad = function () {
  34380. this.add(new BABYLON.FreeCameraGamepadInput());
  34381. return this;
  34382. };
  34383. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  34384. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  34385. return this;
  34386. };
  34387. FreeCameraInputsManager.prototype.addTouch = function () {
  34388. this.add(new BABYLON.FreeCameraTouchInput());
  34389. return this;
  34390. };
  34391. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  34392. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  34393. return this;
  34394. };
  34395. return FreeCameraInputsManager;
  34396. }(BABYLON.CameraInputsManager));
  34397. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  34398. })(BABYLON || (BABYLON = {}));
  34399. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  34400. /// <reference path="babylon.camera.ts" />
  34401. var BABYLON;
  34402. (function (BABYLON) {
  34403. var TargetCamera = (function (_super) {
  34404. __extends(TargetCamera, _super);
  34405. function TargetCamera(name, position, scene) {
  34406. var _this = _super.call(this, name, position, scene) || this;
  34407. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  34408. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  34409. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  34410. _this.speed = 2.0;
  34411. _this.noRotationConstraint = false;
  34412. _this.lockedTarget = null;
  34413. _this._currentTarget = BABYLON.Vector3.Zero();
  34414. _this._viewMatrix = BABYLON.Matrix.Zero();
  34415. _this._camMatrix = BABYLON.Matrix.Zero();
  34416. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  34417. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  34418. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  34419. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  34420. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  34421. _this._lookAtTemp = BABYLON.Matrix.Zero();
  34422. _this._tempMatrix = BABYLON.Matrix.Zero();
  34423. return _this;
  34424. }
  34425. TargetCamera.prototype.getFrontPosition = function (distance) {
  34426. var direction = this.getTarget().subtract(this.position);
  34427. direction.normalize();
  34428. direction.scaleInPlace(distance);
  34429. return this.globalPosition.add(direction);
  34430. };
  34431. TargetCamera.prototype._getLockedTargetPosition = function () {
  34432. if (!this.lockedTarget) {
  34433. return null;
  34434. }
  34435. if (this.lockedTarget.absolutePosition) {
  34436. this.lockedTarget.computeWorldMatrix();
  34437. }
  34438. return this.lockedTarget.absolutePosition || this.lockedTarget;
  34439. };
  34440. TargetCamera.prototype.storeState = function () {
  34441. this._storedPosition = this.position.clone();
  34442. this._storedRotation = this.rotation.clone();
  34443. if (this.rotationQuaternion) {
  34444. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  34445. }
  34446. return _super.prototype.storeState.call(this);
  34447. };
  34448. /**
  34449. * Restored camera state. You must call storeState() first
  34450. */
  34451. TargetCamera.prototype._restoreStateValues = function () {
  34452. if (!_super.prototype._restoreStateValues.call(this)) {
  34453. return false;
  34454. }
  34455. this.position = this._storedPosition.clone();
  34456. this.rotation = this._storedRotation.clone();
  34457. if (this.rotationQuaternion) {
  34458. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  34459. }
  34460. this.cameraDirection.copyFromFloats(0, 0, 0);
  34461. this.cameraRotation.copyFromFloats(0, 0);
  34462. return true;
  34463. };
  34464. // Cache
  34465. TargetCamera.prototype._initCache = function () {
  34466. _super.prototype._initCache.call(this);
  34467. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34468. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34469. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34470. };
  34471. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  34472. if (!ignoreParentClass) {
  34473. _super.prototype._updateCache.call(this);
  34474. }
  34475. var lockedTargetPosition = this._getLockedTargetPosition();
  34476. if (!lockedTargetPosition) {
  34477. this._cache.lockedTarget = null;
  34478. }
  34479. else {
  34480. if (!this._cache.lockedTarget) {
  34481. this._cache.lockedTarget = lockedTargetPosition.clone();
  34482. }
  34483. else {
  34484. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  34485. }
  34486. }
  34487. this._cache.rotation.copyFrom(this.rotation);
  34488. if (this.rotationQuaternion)
  34489. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34490. };
  34491. // Synchronized
  34492. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  34493. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  34494. return false;
  34495. }
  34496. var lockedTargetPosition = this._getLockedTargetPosition();
  34497. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  34498. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  34499. };
  34500. // Methods
  34501. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  34502. var engine = this.getEngine();
  34503. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  34504. };
  34505. // Target
  34506. TargetCamera.prototype.setTarget = function (target) {
  34507. this.upVector.normalize();
  34508. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  34509. this._camMatrix.invert();
  34510. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  34511. var vDir = target.subtract(this.position);
  34512. if (vDir.x >= 0.0) {
  34513. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  34514. }
  34515. else {
  34516. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  34517. }
  34518. this.rotation.z = 0;
  34519. if (isNaN(this.rotation.x)) {
  34520. this.rotation.x = 0;
  34521. }
  34522. if (isNaN(this.rotation.y)) {
  34523. this.rotation.y = 0;
  34524. }
  34525. if (isNaN(this.rotation.z)) {
  34526. this.rotation.z = 0;
  34527. }
  34528. if (this.rotationQuaternion) {
  34529. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  34530. }
  34531. };
  34532. /**
  34533. * Return the current target position of the camera. This value is expressed in local space.
  34534. */
  34535. TargetCamera.prototype.getTarget = function () {
  34536. return this._currentTarget;
  34537. };
  34538. TargetCamera.prototype._decideIfNeedsToMove = function () {
  34539. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  34540. };
  34541. TargetCamera.prototype._updatePosition = function () {
  34542. if (this.parent) {
  34543. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  34544. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  34545. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  34546. return;
  34547. }
  34548. this.position.addInPlace(this.cameraDirection);
  34549. };
  34550. TargetCamera.prototype._checkInputs = function () {
  34551. var needToMove = this._decideIfNeedsToMove();
  34552. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  34553. // Move
  34554. if (needToMove) {
  34555. this._updatePosition();
  34556. }
  34557. // Rotate
  34558. if (needToRotate) {
  34559. this.rotation.x += this.cameraRotation.x;
  34560. this.rotation.y += this.cameraRotation.y;
  34561. //rotate, if quaternion is set and rotation was used
  34562. if (this.rotationQuaternion) {
  34563. var len = this.rotation.lengthSquared();
  34564. if (len) {
  34565. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  34566. }
  34567. }
  34568. if (!this.noRotationConstraint) {
  34569. var limit = (Math.PI / 2) * 0.95;
  34570. if (this.rotation.x > limit)
  34571. this.rotation.x = limit;
  34572. if (this.rotation.x < -limit)
  34573. this.rotation.x = -limit;
  34574. }
  34575. }
  34576. // Inertia
  34577. if (needToMove) {
  34578. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  34579. this.cameraDirection.x = 0;
  34580. }
  34581. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  34582. this.cameraDirection.y = 0;
  34583. }
  34584. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  34585. this.cameraDirection.z = 0;
  34586. }
  34587. this.cameraDirection.scaleInPlace(this.inertia);
  34588. }
  34589. if (needToRotate) {
  34590. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  34591. this.cameraRotation.x = 0;
  34592. }
  34593. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  34594. this.cameraRotation.y = 0;
  34595. }
  34596. this.cameraRotation.scaleInPlace(this.inertia);
  34597. }
  34598. _super.prototype._checkInputs.call(this);
  34599. };
  34600. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  34601. if (this.rotationQuaternion) {
  34602. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  34603. //update the up vector!
  34604. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  34605. }
  34606. else {
  34607. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  34608. }
  34609. };
  34610. TargetCamera.prototype._getViewMatrix = function () {
  34611. if (!this.lockedTarget) {
  34612. // Compute
  34613. this._updateCameraRotationMatrix();
  34614. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  34615. // Computing target and final matrix
  34616. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  34617. }
  34618. else {
  34619. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  34620. }
  34621. if (this.getScene().useRightHandedSystem) {
  34622. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  34623. }
  34624. else {
  34625. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  34626. }
  34627. return this._viewMatrix;
  34628. };
  34629. /**
  34630. * @override
  34631. * Override Camera.createRigCamera
  34632. */
  34633. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  34634. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  34635. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  34636. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  34637. if (!this.rotationQuaternion) {
  34638. this.rotationQuaternion = new BABYLON.Quaternion();
  34639. }
  34640. rigCamera._cameraRigParams = {};
  34641. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  34642. }
  34643. return rigCamera;
  34644. }
  34645. return null;
  34646. };
  34647. /**
  34648. * @override
  34649. * Override Camera._updateRigCameras
  34650. */
  34651. TargetCamera.prototype._updateRigCameras = function () {
  34652. var camLeft = this._rigCameras[0];
  34653. var camRight = this._rigCameras[1];
  34654. switch (this.cameraRigMode) {
  34655. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  34656. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  34657. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  34658. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  34659. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  34660. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  34661. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  34662. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  34663. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  34664. camLeft.setTarget(this.getTarget());
  34665. camRight.setTarget(this.getTarget());
  34666. break;
  34667. case BABYLON.Camera.RIG_MODE_VR:
  34668. if (camLeft.rotationQuaternion) {
  34669. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34670. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34671. }
  34672. else {
  34673. camLeft.rotation.copyFrom(this.rotation);
  34674. camRight.rotation.copyFrom(this.rotation);
  34675. }
  34676. camLeft.position.copyFrom(this.position);
  34677. camRight.position.copyFrom(this.position);
  34678. break;
  34679. }
  34680. _super.prototype._updateRigCameras.call(this);
  34681. };
  34682. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  34683. if (!this._rigCamTransformMatrix) {
  34684. this._rigCamTransformMatrix = new BABYLON.Matrix();
  34685. }
  34686. var target = this.getTarget();
  34687. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  34688. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  34689. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  34690. };
  34691. TargetCamera.prototype.getClassName = function () {
  34692. return "TargetCamera";
  34693. };
  34694. __decorate([
  34695. BABYLON.serializeAsVector3()
  34696. ], TargetCamera.prototype, "rotation", void 0);
  34697. __decorate([
  34698. BABYLON.serialize()
  34699. ], TargetCamera.prototype, "speed", void 0);
  34700. __decorate([
  34701. BABYLON.serializeAsMeshReference("lockedTargetId")
  34702. ], TargetCamera.prototype, "lockedTarget", void 0);
  34703. return TargetCamera;
  34704. }(BABYLON.Camera));
  34705. BABYLON.TargetCamera = TargetCamera;
  34706. })(BABYLON || (BABYLON = {}));
  34707. //# sourceMappingURL=babylon.targetCamera.js.map
  34708. var BABYLON;
  34709. (function (BABYLON) {
  34710. var FreeCamera = (function (_super) {
  34711. __extends(FreeCamera, _super);
  34712. function FreeCamera(name, position, scene) {
  34713. var _this = _super.call(this, name, position, scene) || this;
  34714. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  34715. _this.checkCollisions = false;
  34716. _this.applyGravity = false;
  34717. _this._needMoveForGravity = false;
  34718. _this._oldPosition = BABYLON.Vector3.Zero();
  34719. _this._diffPosition = BABYLON.Vector3.Zero();
  34720. _this._newPosition = BABYLON.Vector3.Zero();
  34721. // Collisions
  34722. _this._collisionMask = -1;
  34723. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  34724. if (collidedMesh === void 0) { collidedMesh = null; }
  34725. //TODO move this to the collision coordinator!
  34726. if (_this.getScene().workerCollisions)
  34727. newPosition.multiplyInPlace(_this._collider.radius);
  34728. var updatePosition = function (newPos) {
  34729. _this._newPosition.copyFrom(newPos);
  34730. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  34731. var oldPosition = _this.position.clone();
  34732. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  34733. _this.position.addInPlace(_this._diffPosition);
  34734. if (_this.onCollide && collidedMesh) {
  34735. _this.onCollide(collidedMesh);
  34736. }
  34737. }
  34738. };
  34739. updatePosition(newPosition);
  34740. };
  34741. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  34742. _this.inputs.addKeyboard().addMouse();
  34743. return _this;
  34744. }
  34745. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  34746. //-- begin properties for backward compatibility for inputs
  34747. get: function () {
  34748. var mouse = this.inputs.attached["mouse"];
  34749. if (mouse)
  34750. return mouse.angularSensibility;
  34751. },
  34752. set: function (value) {
  34753. var mouse = this.inputs.attached["mouse"];
  34754. if (mouse)
  34755. mouse.angularSensibility = value;
  34756. },
  34757. enumerable: true,
  34758. configurable: true
  34759. });
  34760. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  34761. get: function () {
  34762. var keyboard = this.inputs.attached["keyboard"];
  34763. if (keyboard)
  34764. return keyboard.keysUp;
  34765. },
  34766. set: function (value) {
  34767. var keyboard = this.inputs.attached["keyboard"];
  34768. if (keyboard)
  34769. keyboard.keysUp = value;
  34770. },
  34771. enumerable: true,
  34772. configurable: true
  34773. });
  34774. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  34775. get: function () {
  34776. var keyboard = this.inputs.attached["keyboard"];
  34777. if (keyboard)
  34778. return keyboard.keysDown;
  34779. },
  34780. set: function (value) {
  34781. var keyboard = this.inputs.attached["keyboard"];
  34782. if (keyboard)
  34783. keyboard.keysDown = value;
  34784. },
  34785. enumerable: true,
  34786. configurable: true
  34787. });
  34788. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  34789. get: function () {
  34790. var keyboard = this.inputs.attached["keyboard"];
  34791. if (keyboard)
  34792. return keyboard.keysLeft;
  34793. },
  34794. set: function (value) {
  34795. var keyboard = this.inputs.attached["keyboard"];
  34796. if (keyboard)
  34797. keyboard.keysLeft = value;
  34798. },
  34799. enumerable: true,
  34800. configurable: true
  34801. });
  34802. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  34803. get: function () {
  34804. var keyboard = this.inputs.attached["keyboard"];
  34805. if (keyboard)
  34806. return keyboard.keysRight;
  34807. },
  34808. set: function (value) {
  34809. var keyboard = this.inputs.attached["keyboard"];
  34810. if (keyboard)
  34811. keyboard.keysRight = value;
  34812. },
  34813. enumerable: true,
  34814. configurable: true
  34815. });
  34816. // Controls
  34817. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  34818. this.inputs.attachElement(element, noPreventDefault);
  34819. };
  34820. FreeCamera.prototype.detachControl = function (element) {
  34821. this.inputs.detachElement(element);
  34822. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  34823. this.cameraRotation = new BABYLON.Vector2(0, 0);
  34824. };
  34825. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  34826. get: function () {
  34827. return this._collisionMask;
  34828. },
  34829. set: function (mask) {
  34830. this._collisionMask = !isNaN(mask) ? mask : -1;
  34831. },
  34832. enumerable: true,
  34833. configurable: true
  34834. });
  34835. FreeCamera.prototype._collideWithWorld = function (displacement) {
  34836. var globalPosition;
  34837. if (this.parent) {
  34838. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  34839. }
  34840. else {
  34841. globalPosition = this.position;
  34842. }
  34843. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  34844. if (!this._collider) {
  34845. this._collider = new BABYLON.Collider();
  34846. }
  34847. this._collider.radius = this.ellipsoid;
  34848. this._collider.collisionMask = this._collisionMask;
  34849. //no need for clone, as long as gravity is not on.
  34850. var actualDisplacement = displacement;
  34851. //add gravity to the direction to prevent the dual-collision checking
  34852. if (this.applyGravity) {
  34853. //this prevents mending with cameraDirection, a global variable of the free camera class.
  34854. actualDisplacement = displacement.add(this.getScene().gravity);
  34855. }
  34856. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  34857. };
  34858. FreeCamera.prototype._checkInputs = function () {
  34859. if (!this._localDirection) {
  34860. this._localDirection = BABYLON.Vector3.Zero();
  34861. this._transformedDirection = BABYLON.Vector3.Zero();
  34862. }
  34863. this.inputs.checkInputs();
  34864. _super.prototype._checkInputs.call(this);
  34865. };
  34866. FreeCamera.prototype._decideIfNeedsToMove = function () {
  34867. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  34868. };
  34869. FreeCamera.prototype._updatePosition = function () {
  34870. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  34871. this._collideWithWorld(this.cameraDirection);
  34872. }
  34873. else {
  34874. _super.prototype._updatePosition.call(this);
  34875. }
  34876. };
  34877. FreeCamera.prototype.dispose = function () {
  34878. this.inputs.clear();
  34879. _super.prototype.dispose.call(this);
  34880. };
  34881. FreeCamera.prototype.getClassName = function () {
  34882. return "FreeCamera";
  34883. };
  34884. __decorate([
  34885. BABYLON.serializeAsVector3()
  34886. ], FreeCamera.prototype, "ellipsoid", void 0);
  34887. __decorate([
  34888. BABYLON.serialize()
  34889. ], FreeCamera.prototype, "checkCollisions", void 0);
  34890. __decorate([
  34891. BABYLON.serialize()
  34892. ], FreeCamera.prototype, "applyGravity", void 0);
  34893. return FreeCamera;
  34894. }(BABYLON.TargetCamera));
  34895. BABYLON.FreeCamera = FreeCamera;
  34896. })(BABYLON || (BABYLON = {}));
  34897. //# sourceMappingURL=babylon.freeCamera.js.map
  34898. var BABYLON;
  34899. (function (BABYLON) {
  34900. var ArcRotateCameraKeyboardMoveInput = (function () {
  34901. function ArcRotateCameraKeyboardMoveInput() {
  34902. this._keys = [];
  34903. this.keysUp = [38];
  34904. this.keysDown = [40];
  34905. this.keysLeft = [37];
  34906. this.keysRight = [39];
  34907. this.keysReset = [111];
  34908. this.panningSensibility = 50.0;
  34909. }
  34910. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  34911. var _this = this;
  34912. if (this._onCanvasBlurObserver) {
  34913. return;
  34914. }
  34915. this._scene = this.camera.getScene();
  34916. this._engine = this._scene.getEngine();
  34917. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  34918. _this._keys = [];
  34919. });
  34920. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  34921. var evt = info.event;
  34922. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  34923. _this._ctrlPressed = evt.ctrlKey;
  34924. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34925. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34926. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34927. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  34928. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  34929. var index = _this._keys.indexOf(evt.keyCode);
  34930. if (index === -1) {
  34931. _this._keys.push(evt.keyCode);
  34932. }
  34933. if (evt.preventDefault) {
  34934. if (!noPreventDefault) {
  34935. evt.preventDefault();
  34936. }
  34937. }
  34938. }
  34939. }
  34940. else {
  34941. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34942. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34943. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34944. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  34945. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  34946. var index = _this._keys.indexOf(evt.keyCode);
  34947. if (index >= 0) {
  34948. _this._keys.splice(index, 1);
  34949. }
  34950. if (evt.preventDefault) {
  34951. if (!noPreventDefault) {
  34952. evt.preventDefault();
  34953. }
  34954. }
  34955. }
  34956. }
  34957. });
  34958. };
  34959. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  34960. if (this._scene) {
  34961. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  34962. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  34963. this._onKeyboardObserver = null;
  34964. this._onCanvasBlurObserver = null;
  34965. }
  34966. this._keys = [];
  34967. };
  34968. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  34969. if (this._onKeyboardObserver) {
  34970. var camera = this.camera;
  34971. for (var index = 0; index < this._keys.length; index++) {
  34972. var keyCode = this._keys[index];
  34973. if (this.keysLeft.indexOf(keyCode) !== -1) {
  34974. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  34975. camera.inertialPanningX -= 1 / this.panningSensibility;
  34976. }
  34977. else {
  34978. camera.inertialAlphaOffset -= 0.01;
  34979. }
  34980. }
  34981. else if (this.keysUp.indexOf(keyCode) !== -1) {
  34982. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  34983. camera.inertialPanningY += 1 / this.panningSensibility;
  34984. }
  34985. else {
  34986. camera.inertialBetaOffset -= 0.01;
  34987. }
  34988. }
  34989. else if (this.keysRight.indexOf(keyCode) !== -1) {
  34990. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  34991. camera.inertialPanningX += 1 / this.panningSensibility;
  34992. }
  34993. else {
  34994. camera.inertialAlphaOffset += 0.01;
  34995. }
  34996. }
  34997. else if (this.keysDown.indexOf(keyCode) !== -1) {
  34998. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  34999. camera.inertialPanningY -= 1 / this.panningSensibility;
  35000. }
  35001. else {
  35002. camera.inertialBetaOffset += 0.01;
  35003. }
  35004. }
  35005. else if (this.keysReset.indexOf(keyCode) !== -1) {
  35006. camera.restoreState();
  35007. }
  35008. }
  35009. }
  35010. };
  35011. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  35012. return "ArcRotateCameraKeyboardMoveInput";
  35013. };
  35014. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  35015. return "keyboard";
  35016. };
  35017. __decorate([
  35018. BABYLON.serialize()
  35019. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  35020. __decorate([
  35021. BABYLON.serialize()
  35022. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  35023. __decorate([
  35024. BABYLON.serialize()
  35025. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  35026. __decorate([
  35027. BABYLON.serialize()
  35028. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  35029. __decorate([
  35030. BABYLON.serialize()
  35031. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  35032. __decorate([
  35033. BABYLON.serialize()
  35034. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  35035. return ArcRotateCameraKeyboardMoveInput;
  35036. }());
  35037. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  35038. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  35039. })(BABYLON || (BABYLON = {}));
  35040. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  35041. var BABYLON;
  35042. (function (BABYLON) {
  35043. var ArcRotateCameraMouseWheelInput = (function () {
  35044. function ArcRotateCameraMouseWheelInput() {
  35045. this.wheelPrecision = 3.0;
  35046. }
  35047. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  35048. var _this = this;
  35049. this._wheel = function (p, s) {
  35050. //sanity check - this should be a PointerWheel event.
  35051. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  35052. return;
  35053. var event = p.event;
  35054. var delta = 0;
  35055. if (event.wheelDelta) {
  35056. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  35057. }
  35058. else if (event.detail) {
  35059. delta = -event.detail / _this.wheelPrecision;
  35060. }
  35061. if (delta)
  35062. _this.camera.inertialRadiusOffset += delta;
  35063. if (event.preventDefault) {
  35064. if (!noPreventDefault) {
  35065. event.preventDefault();
  35066. }
  35067. }
  35068. };
  35069. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  35070. };
  35071. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  35072. if (this._observer && element) {
  35073. this.camera.getScene().onPointerObservable.remove(this._observer);
  35074. this._observer = null;
  35075. this._wheel = null;
  35076. }
  35077. };
  35078. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  35079. return "ArcRotateCameraMouseWheelInput";
  35080. };
  35081. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  35082. return "mousewheel";
  35083. };
  35084. __decorate([
  35085. BABYLON.serialize()
  35086. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  35087. return ArcRotateCameraMouseWheelInput;
  35088. }());
  35089. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  35090. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  35091. })(BABYLON || (BABYLON = {}));
  35092. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  35093. var BABYLON;
  35094. (function (BABYLON) {
  35095. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  35096. var ArcRotateCameraPointersInput = (function () {
  35097. function ArcRotateCameraPointersInput() {
  35098. this.buttons = [0, 1, 2];
  35099. this.angularSensibilityX = 1000.0;
  35100. this.angularSensibilityY = 1000.0;
  35101. this.pinchPrecision = 6.0;
  35102. this.panningSensibility = 50.0;
  35103. this.multiTouchPanning = true;
  35104. this._isPanClick = false;
  35105. this.pinchInwards = true;
  35106. }
  35107. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  35108. var _this = this;
  35109. var engine = this.camera.getEngine();
  35110. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  35111. var pointA, pointB;
  35112. var previousPinchSquaredDistance = 0;
  35113. var previousPinchDistance = 0;
  35114. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false };
  35115. this._pointerInput = function (p, s) {
  35116. var evt = p.event;
  35117. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  35118. return;
  35119. }
  35120. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  35121. try {
  35122. evt.srcElement.setPointerCapture(evt.pointerId);
  35123. }
  35124. catch (e) {
  35125. //Nothing to do with the error. Execution will continue.
  35126. }
  35127. // Manage panning with pan button click
  35128. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  35129. // manage pointers
  35130. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  35131. if (pointA === undefined) {
  35132. pointA = cacheSoloPointer;
  35133. }
  35134. else if (pointB === undefined) {
  35135. pointB = cacheSoloPointer;
  35136. }
  35137. if (!noPreventDefault) {
  35138. evt.preventDefault();
  35139. element.focus();
  35140. }
  35141. }
  35142. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  35143. _this.camera.restoreState();
  35144. }
  35145. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  35146. try {
  35147. evt.srcElement.releasePointerCapture(evt.pointerId);
  35148. }
  35149. catch (e) {
  35150. //Nothing to do with the error.
  35151. }
  35152. cacheSoloPointer = null;
  35153. previousPinchSquaredDistance = 0;
  35154. previousPinchDistance = 0;
  35155. previousMultiTouchPanPosition.isPaning = false;
  35156. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  35157. //but emptying completly pointers collection is required to fix a bug on iPhone :
  35158. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  35159. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  35160. pointA = pointB = undefined;
  35161. if (!noPreventDefault) {
  35162. evt.preventDefault();
  35163. }
  35164. }
  35165. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  35166. if (!noPreventDefault) {
  35167. evt.preventDefault();
  35168. }
  35169. // One button down
  35170. if (pointA && pointB === undefined) {
  35171. if (_this.panningSensibility !== 0 &&
  35172. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  35173. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  35174. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  35175. }
  35176. else {
  35177. var offsetX = evt.clientX - cacheSoloPointer.x;
  35178. var offsetY = evt.clientY - cacheSoloPointer.y;
  35179. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  35180. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  35181. }
  35182. cacheSoloPointer.x = evt.clientX;
  35183. cacheSoloPointer.y = evt.clientY;
  35184. }
  35185. else if (pointA && pointB) {
  35186. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  35187. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  35188. ed.x = evt.clientX;
  35189. ed.y = evt.clientY;
  35190. var direction = _this.pinchInwards ? 1 : -1;
  35191. var distX = pointA.x - pointB.x;
  35192. var distY = pointA.y - pointB.y;
  35193. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  35194. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  35195. if (previousPinchSquaredDistance === 0) {
  35196. previousPinchSquaredDistance = pinchSquaredDistance;
  35197. previousPinchDistance = pinchDistance;
  35198. return;
  35199. }
  35200. if (Math.abs(pinchDistance - previousPinchDistance) > _this.camera.pinchToPanMaxDistance) {
  35201. _this.camera
  35202. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  35203. (_this.pinchPrecision *
  35204. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  35205. direction);
  35206. previousMultiTouchPanPosition.isPaning = false;
  35207. }
  35208. else {
  35209. if (cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  35210. if (!previousMultiTouchPanPosition.isPaning) {
  35211. previousMultiTouchPanPosition.isPaning = true;
  35212. previousMultiTouchPanPosition.x = ed.x;
  35213. previousMultiTouchPanPosition.y = ed.y;
  35214. return;
  35215. }
  35216. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / _this.panningSensibility;
  35217. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / _this.panningSensibility;
  35218. }
  35219. }
  35220. if (cacheSoloPointer.pointerId === evt.pointerId) {
  35221. previousMultiTouchPanPosition.x = ed.x;
  35222. previousMultiTouchPanPosition.y = ed.y;
  35223. }
  35224. previousPinchSquaredDistance = pinchSquaredDistance;
  35225. previousPinchDistance = pinchDistance;
  35226. }
  35227. }
  35228. };
  35229. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  35230. this._onContextMenu = function (evt) {
  35231. evt.preventDefault();
  35232. };
  35233. if (!this.camera._useCtrlForPanning) {
  35234. element.addEventListener("contextmenu", this._onContextMenu, false);
  35235. }
  35236. this._onLostFocus = function () {
  35237. //this._keys = [];
  35238. pointA = pointB = undefined;
  35239. previousPinchSquaredDistance = 0;
  35240. previousPinchDistance = 0;
  35241. previousMultiTouchPanPosition.isPaning = false;
  35242. cacheSoloPointer = null;
  35243. };
  35244. this._onMouseMove = function (evt) {
  35245. if (!engine.isPointerLock) {
  35246. return;
  35247. }
  35248. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  35249. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  35250. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  35251. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  35252. if (!noPreventDefault) {
  35253. evt.preventDefault();
  35254. }
  35255. };
  35256. this._onGestureStart = function (e) {
  35257. if (window.MSGesture === undefined) {
  35258. return;
  35259. }
  35260. if (!_this._MSGestureHandler) {
  35261. _this._MSGestureHandler = new MSGesture();
  35262. _this._MSGestureHandler.target = element;
  35263. }
  35264. _this._MSGestureHandler.addPointer(e.pointerId);
  35265. };
  35266. this._onGesture = function (e) {
  35267. _this.camera.radius *= e.scale;
  35268. if (e.preventDefault) {
  35269. if (!noPreventDefault) {
  35270. e.stopPropagation();
  35271. e.preventDefault();
  35272. }
  35273. }
  35274. };
  35275. element.addEventListener("mousemove", this._onMouseMove, false);
  35276. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  35277. element.addEventListener("MSGestureChange", this._onGesture, false);
  35278. BABYLON.Tools.RegisterTopRootEvents([
  35279. { name: "blur", handler: this._onLostFocus }
  35280. ]);
  35281. };
  35282. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  35283. BABYLON.Tools.UnregisterTopRootEvents([
  35284. { name: "blur", handler: this._onLostFocus }
  35285. ]);
  35286. if (element && this._observer) {
  35287. this.camera.getScene().onPointerObservable.remove(this._observer);
  35288. this._observer = null;
  35289. element.removeEventListener("contextmenu", this._onContextMenu);
  35290. element.removeEventListener("mousemove", this._onMouseMove);
  35291. element.removeEventListener("MSPointerDown", this._onGestureStart);
  35292. element.removeEventListener("MSGestureChange", this._onGesture);
  35293. this._isPanClick = false;
  35294. this.pinchInwards = true;
  35295. this._onMouseMove = null;
  35296. this._onGestureStart = null;
  35297. this._onGesture = null;
  35298. this._MSGestureHandler = null;
  35299. this._onLostFocus = null;
  35300. this._onContextMenu = null;
  35301. }
  35302. };
  35303. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  35304. return "ArcRotateCameraPointersInput";
  35305. };
  35306. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  35307. return "pointers";
  35308. };
  35309. __decorate([
  35310. BABYLON.serialize()
  35311. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  35312. __decorate([
  35313. BABYLON.serialize()
  35314. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  35315. __decorate([
  35316. BABYLON.serialize()
  35317. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  35318. __decorate([
  35319. BABYLON.serialize()
  35320. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  35321. __decorate([
  35322. BABYLON.serialize()
  35323. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  35324. __decorate([
  35325. BABYLON.serialize()
  35326. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  35327. return ArcRotateCameraPointersInput;
  35328. }());
  35329. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  35330. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  35331. })(BABYLON || (BABYLON = {}));
  35332. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  35333. /// <reference path="babylon.targetCamera.ts" />
  35334. /// <reference path="..\Tools\babylon.tools.ts" />
  35335. var BABYLON;
  35336. (function (BABYLON) {
  35337. var ArcRotateCamera = (function (_super) {
  35338. __extends(ArcRotateCamera, _super);
  35339. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  35340. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  35341. _this.inertialAlphaOffset = 0;
  35342. _this.inertialBetaOffset = 0;
  35343. _this.inertialRadiusOffset = 0;
  35344. _this.lowerAlphaLimit = null;
  35345. _this.upperAlphaLimit = null;
  35346. _this.lowerBetaLimit = 0.01;
  35347. _this.upperBetaLimit = Math.PI;
  35348. _this.lowerRadiusLimit = null;
  35349. _this.upperRadiusLimit = null;
  35350. _this.inertialPanningX = 0;
  35351. _this.inertialPanningY = 0;
  35352. _this.pinchToPanMaxDistance = 2;
  35353. _this.panningDistanceLimit = null;
  35354. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  35355. _this.panningInertia = 0.9;
  35356. //-- end properties for backward compatibility for inputs
  35357. _this.zoomOnFactor = 1;
  35358. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  35359. _this.allowUpsideDown = true;
  35360. _this._viewMatrix = new BABYLON.Matrix();
  35361. // Panning
  35362. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  35363. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  35364. _this.checkCollisions = false;
  35365. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  35366. _this._previousPosition = BABYLON.Vector3.Zero();
  35367. _this._collisionVelocity = BABYLON.Vector3.Zero();
  35368. _this._newPosition = BABYLON.Vector3.Zero();
  35369. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  35370. if (collidedMesh === void 0) { collidedMesh = null; }
  35371. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  35372. newPosition.multiplyInPlace(_this._collider.radius);
  35373. }
  35374. if (!collidedMesh) {
  35375. _this._previousPosition.copyFrom(_this.position);
  35376. }
  35377. else {
  35378. _this.setPosition(newPosition);
  35379. if (_this.onCollide) {
  35380. _this.onCollide(collidedMesh);
  35381. }
  35382. }
  35383. // Recompute because of constraints
  35384. var cosa = Math.cos(_this.alpha);
  35385. var sina = Math.sin(_this.alpha);
  35386. var cosb = Math.cos(_this.beta);
  35387. var sinb = Math.sin(_this.beta);
  35388. if (sinb === 0) {
  35389. sinb = 0.0001;
  35390. }
  35391. var target = _this._getTargetPosition();
  35392. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  35393. _this.position.copyFrom(_this._newPosition);
  35394. var up = _this.upVector;
  35395. if (_this.allowUpsideDown && _this.beta < 0) {
  35396. up = up.clone();
  35397. up = up.negate();
  35398. }
  35399. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  35400. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  35401. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  35402. _this._collisionTriggered = false;
  35403. };
  35404. _this._target = BABYLON.Vector3.Zero();
  35405. if (target) {
  35406. _this.setTarget(target);
  35407. }
  35408. _this.alpha = alpha;
  35409. _this.beta = beta;
  35410. _this.radius = radius;
  35411. _this.getViewMatrix();
  35412. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  35413. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  35414. return _this;
  35415. }
  35416. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  35417. get: function () {
  35418. return this._target;
  35419. },
  35420. set: function (value) {
  35421. this.setTarget(value);
  35422. },
  35423. enumerable: true,
  35424. configurable: true
  35425. });
  35426. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  35427. //-- begin properties for backward compatibility for inputs
  35428. get: function () {
  35429. var pointers = this.inputs.attached["pointers"];
  35430. if (pointers)
  35431. return pointers.angularSensibilityX;
  35432. },
  35433. set: function (value) {
  35434. var pointers = this.inputs.attached["pointers"];
  35435. if (pointers) {
  35436. pointers.angularSensibilityX = value;
  35437. }
  35438. },
  35439. enumerable: true,
  35440. configurable: true
  35441. });
  35442. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  35443. get: function () {
  35444. var pointers = this.inputs.attached["pointers"];
  35445. if (pointers)
  35446. return pointers.angularSensibilityY;
  35447. },
  35448. set: function (value) {
  35449. var pointers = this.inputs.attached["pointers"];
  35450. if (pointers) {
  35451. pointers.angularSensibilityY = value;
  35452. }
  35453. },
  35454. enumerable: true,
  35455. configurable: true
  35456. });
  35457. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  35458. get: function () {
  35459. var pointers = this.inputs.attached["pointers"];
  35460. if (pointers)
  35461. return pointers.pinchPrecision;
  35462. },
  35463. set: function (value) {
  35464. var pointers = this.inputs.attached["pointers"];
  35465. if (pointers) {
  35466. pointers.pinchPrecision = value;
  35467. }
  35468. },
  35469. enumerable: true,
  35470. configurable: true
  35471. });
  35472. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  35473. get: function () {
  35474. var pointers = this.inputs.attached["pointers"];
  35475. if (pointers)
  35476. return pointers.panningSensibility;
  35477. },
  35478. set: function (value) {
  35479. var pointers = this.inputs.attached["pointers"];
  35480. if (pointers) {
  35481. pointers.panningSensibility = value;
  35482. }
  35483. },
  35484. enumerable: true,
  35485. configurable: true
  35486. });
  35487. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  35488. get: function () {
  35489. var keyboard = this.inputs.attached["keyboard"];
  35490. if (keyboard)
  35491. return keyboard.keysUp;
  35492. },
  35493. set: function (value) {
  35494. var keyboard = this.inputs.attached["keyboard"];
  35495. if (keyboard)
  35496. keyboard.keysUp = value;
  35497. },
  35498. enumerable: true,
  35499. configurable: true
  35500. });
  35501. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  35502. get: function () {
  35503. var keyboard = this.inputs.attached["keyboard"];
  35504. if (keyboard)
  35505. return keyboard.keysDown;
  35506. },
  35507. set: function (value) {
  35508. var keyboard = this.inputs.attached["keyboard"];
  35509. if (keyboard)
  35510. keyboard.keysDown = value;
  35511. },
  35512. enumerable: true,
  35513. configurable: true
  35514. });
  35515. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  35516. get: function () {
  35517. var keyboard = this.inputs.attached["keyboard"];
  35518. if (keyboard)
  35519. return keyboard.keysLeft;
  35520. },
  35521. set: function (value) {
  35522. var keyboard = this.inputs.attached["keyboard"];
  35523. if (keyboard)
  35524. keyboard.keysLeft = value;
  35525. },
  35526. enumerable: true,
  35527. configurable: true
  35528. });
  35529. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  35530. get: function () {
  35531. var keyboard = this.inputs.attached["keyboard"];
  35532. if (keyboard)
  35533. return keyboard.keysRight;
  35534. },
  35535. set: function (value) {
  35536. var keyboard = this.inputs.attached["keyboard"];
  35537. if (keyboard)
  35538. keyboard.keysRight = value;
  35539. },
  35540. enumerable: true,
  35541. configurable: true
  35542. });
  35543. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  35544. get: function () {
  35545. var mousewheel = this.inputs.attached["mousewheel"];
  35546. if (mousewheel)
  35547. return mousewheel.wheelPrecision;
  35548. },
  35549. set: function (value) {
  35550. var mousewheel = this.inputs.attached["mousewheel"];
  35551. if (mousewheel)
  35552. mousewheel.wheelPrecision = value;
  35553. },
  35554. enumerable: true,
  35555. configurable: true
  35556. });
  35557. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  35558. get: function () {
  35559. return this._bouncingBehavior;
  35560. },
  35561. enumerable: true,
  35562. configurable: true
  35563. });
  35564. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  35565. get: function () {
  35566. return this._bouncingBehavior != null;
  35567. },
  35568. set: function (value) {
  35569. if (value === this.useBouncingBehavior) {
  35570. return;
  35571. }
  35572. if (value) {
  35573. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  35574. this.addBehavior(this._bouncingBehavior);
  35575. }
  35576. else {
  35577. this.removeBehavior(this._bouncingBehavior);
  35578. this._bouncingBehavior = null;
  35579. }
  35580. },
  35581. enumerable: true,
  35582. configurable: true
  35583. });
  35584. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  35585. get: function () {
  35586. return this._framingBehavior;
  35587. },
  35588. enumerable: true,
  35589. configurable: true
  35590. });
  35591. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  35592. get: function () {
  35593. return this._framingBehavior != null;
  35594. },
  35595. set: function (value) {
  35596. if (value === this.useFramingBehavior) {
  35597. return;
  35598. }
  35599. if (value) {
  35600. this._framingBehavior = new BABYLON.FramingBehavior();
  35601. this.addBehavior(this._framingBehavior);
  35602. }
  35603. else {
  35604. this.removeBehavior(this._framingBehavior);
  35605. this._framingBehavior = null;
  35606. }
  35607. },
  35608. enumerable: true,
  35609. configurable: true
  35610. });
  35611. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  35612. get: function () {
  35613. return this._autoRotationBehavior;
  35614. },
  35615. enumerable: true,
  35616. configurable: true
  35617. });
  35618. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  35619. get: function () {
  35620. return this._autoRotationBehavior != null;
  35621. },
  35622. set: function (value) {
  35623. if (value === this.useAutoRotationBehavior) {
  35624. return;
  35625. }
  35626. if (value) {
  35627. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  35628. this.addBehavior(this._autoRotationBehavior);
  35629. }
  35630. else {
  35631. this.removeBehavior(this._autoRotationBehavior);
  35632. this._autoRotationBehavior = null;
  35633. }
  35634. },
  35635. enumerable: true,
  35636. configurable: true
  35637. });
  35638. // Cache
  35639. ArcRotateCamera.prototype._initCache = function () {
  35640. _super.prototype._initCache.call(this);
  35641. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  35642. this._cache.alpha = undefined;
  35643. this._cache.beta = undefined;
  35644. this._cache.radius = undefined;
  35645. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  35646. };
  35647. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  35648. if (!ignoreParentClass) {
  35649. _super.prototype._updateCache.call(this);
  35650. }
  35651. this._cache._target.copyFrom(this._getTargetPosition());
  35652. this._cache.alpha = this.alpha;
  35653. this._cache.beta = this.beta;
  35654. this._cache.radius = this.radius;
  35655. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  35656. };
  35657. ArcRotateCamera.prototype._getTargetPosition = function () {
  35658. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  35659. var pos = this._targetHost.getAbsolutePosition();
  35660. if (this._targetBoundingCenter) {
  35661. pos.addToRef(this._targetBoundingCenter, this._target);
  35662. }
  35663. else {
  35664. this._target.copyFrom(pos);
  35665. }
  35666. }
  35667. var lockedTargetPosition = this._getLockedTargetPosition();
  35668. if (lockedTargetPosition) {
  35669. return lockedTargetPosition;
  35670. }
  35671. return this._target;
  35672. };
  35673. ArcRotateCamera.prototype.storeState = function () {
  35674. this._storedAlpha = this.alpha;
  35675. this._storedBeta = this.beta;
  35676. this._storedRadius = this.radius;
  35677. this._storedTarget = this._getTargetPosition().clone();
  35678. return _super.prototype.storeState.call(this);
  35679. };
  35680. /**
  35681. * Restored camera state. You must call storeState() first
  35682. */
  35683. ArcRotateCamera.prototype._restoreStateValues = function () {
  35684. if (!_super.prototype._restoreStateValues.call(this)) {
  35685. return false;
  35686. }
  35687. this.alpha = this._storedAlpha;
  35688. this.beta = this._storedBeta;
  35689. this.radius = this._storedRadius;
  35690. this.setTarget(this._storedTarget);
  35691. this.inertialAlphaOffset = 0;
  35692. this.inertialBetaOffset = 0;
  35693. this.inertialRadiusOffset = 0;
  35694. this.inertialPanningX = 0;
  35695. this.inertialPanningY = 0;
  35696. return true;
  35697. };
  35698. // Synchronized
  35699. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  35700. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  35701. return false;
  35702. return this._cache._target.equals(this._getTargetPosition())
  35703. && this._cache.alpha === this.alpha
  35704. && this._cache.beta === this.beta
  35705. && this._cache.radius === this.radius
  35706. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  35707. };
  35708. // Methods
  35709. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  35710. var _this = this;
  35711. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  35712. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  35713. this._useCtrlForPanning = useCtrlForPanning;
  35714. this._panningMouseButton = panningMouseButton;
  35715. this.inputs.attachElement(element, noPreventDefault);
  35716. this._reset = function () {
  35717. _this.inertialAlphaOffset = 0;
  35718. _this.inertialBetaOffset = 0;
  35719. _this.inertialRadiusOffset = 0;
  35720. _this.inertialPanningX = 0;
  35721. _this.inertialPanningY = 0;
  35722. };
  35723. };
  35724. ArcRotateCamera.prototype.detachControl = function (element) {
  35725. this.inputs.detachElement(element);
  35726. if (this._reset) {
  35727. this._reset();
  35728. }
  35729. };
  35730. ArcRotateCamera.prototype._checkInputs = function () {
  35731. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  35732. if (this._collisionTriggered) {
  35733. return;
  35734. }
  35735. this.inputs.checkInputs();
  35736. // Inertia
  35737. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  35738. if (this.getScene().useRightHandedSystem) {
  35739. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  35740. }
  35741. else {
  35742. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  35743. }
  35744. this.beta += this.inertialBetaOffset;
  35745. this.radius -= this.inertialRadiusOffset;
  35746. this.inertialAlphaOffset *= this.inertia;
  35747. this.inertialBetaOffset *= this.inertia;
  35748. this.inertialRadiusOffset *= this.inertia;
  35749. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  35750. this.inertialAlphaOffset = 0;
  35751. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  35752. this.inertialBetaOffset = 0;
  35753. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  35754. this.inertialRadiusOffset = 0;
  35755. }
  35756. // Panning inertia
  35757. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  35758. if (!this._localDirection) {
  35759. this._localDirection = BABYLON.Vector3.Zero();
  35760. this._transformedDirection = BABYLON.Vector3.Zero();
  35761. }
  35762. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  35763. this._localDirection.multiplyInPlace(this.panningAxis);
  35764. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  35765. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  35766. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  35767. if (!this.panningAxis.y) {
  35768. this._transformedDirection.y = 0;
  35769. }
  35770. if (!this._targetHost) {
  35771. if (this.panningDistanceLimit) {
  35772. this._transformedDirection.addInPlace(this._target);
  35773. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  35774. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  35775. this._target.copyFrom(this._transformedDirection);
  35776. }
  35777. }
  35778. else {
  35779. this._target.addInPlace(this._transformedDirection);
  35780. }
  35781. }
  35782. this.inertialPanningX *= this.panningInertia;
  35783. this.inertialPanningY *= this.panningInertia;
  35784. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  35785. this.inertialPanningX = 0;
  35786. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  35787. this.inertialPanningY = 0;
  35788. }
  35789. // Limits
  35790. this._checkLimits();
  35791. _super.prototype._checkInputs.call(this);
  35792. };
  35793. ArcRotateCamera.prototype._checkLimits = function () {
  35794. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  35795. if (this.allowUpsideDown && this.beta > Math.PI) {
  35796. this.beta = this.beta - (2 * Math.PI);
  35797. }
  35798. }
  35799. else {
  35800. if (this.beta < this.lowerBetaLimit) {
  35801. this.beta = this.lowerBetaLimit;
  35802. }
  35803. }
  35804. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  35805. if (this.allowUpsideDown && this.beta < -Math.PI) {
  35806. this.beta = this.beta + (2 * Math.PI);
  35807. }
  35808. }
  35809. else {
  35810. if (this.beta > this.upperBetaLimit) {
  35811. this.beta = this.upperBetaLimit;
  35812. }
  35813. }
  35814. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  35815. this.alpha = this.lowerAlphaLimit;
  35816. }
  35817. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  35818. this.alpha = this.upperAlphaLimit;
  35819. }
  35820. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  35821. this.radius = this.lowerRadiusLimit;
  35822. }
  35823. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  35824. this.radius = this.upperRadiusLimit;
  35825. }
  35826. };
  35827. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  35828. var radiusv3 = this.position.subtract(this._getTargetPosition());
  35829. this.radius = radiusv3.length();
  35830. if (this.radius === 0) {
  35831. this.radius = 0.0001; // Just to avoid division by zero
  35832. }
  35833. // Alpha
  35834. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  35835. if (radiusv3.z < 0) {
  35836. this.alpha = 2 * Math.PI - this.alpha;
  35837. }
  35838. // Beta
  35839. this.beta = Math.acos(radiusv3.y / this.radius);
  35840. this._checkLimits();
  35841. };
  35842. ArcRotateCamera.prototype.setPosition = function (position) {
  35843. if (this.position.equals(position)) {
  35844. return;
  35845. }
  35846. this.position.copyFrom(position);
  35847. this.rebuildAnglesAndRadius();
  35848. };
  35849. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  35850. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  35851. if (allowSamePosition === void 0) { allowSamePosition = false; }
  35852. if (target.getBoundingInfo) {
  35853. if (toBoundingCenter) {
  35854. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  35855. }
  35856. else {
  35857. this._targetBoundingCenter = null;
  35858. }
  35859. this._targetHost = target;
  35860. this._target = this._getTargetPosition();
  35861. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  35862. }
  35863. else {
  35864. var newTarget = target;
  35865. var currentTarget = this._getTargetPosition();
  35866. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  35867. return;
  35868. }
  35869. this._targetHost = null;
  35870. this._target = newTarget;
  35871. this._targetBoundingCenter = null;
  35872. this.onMeshTargetChangedObservable.notifyObservers(null);
  35873. }
  35874. this.rebuildAnglesAndRadius();
  35875. };
  35876. ArcRotateCamera.prototype._getViewMatrix = function () {
  35877. // Compute
  35878. var cosa = Math.cos(this.alpha);
  35879. var sina = Math.sin(this.alpha);
  35880. var cosb = Math.cos(this.beta);
  35881. var sinb = Math.sin(this.beta);
  35882. if (sinb === 0) {
  35883. sinb = 0.0001;
  35884. }
  35885. var target = this._getTargetPosition();
  35886. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  35887. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  35888. if (!this._collider) {
  35889. this._collider = new BABYLON.Collider();
  35890. }
  35891. this._collider.radius = this.collisionRadius;
  35892. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  35893. this._collisionTriggered = true;
  35894. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  35895. }
  35896. else {
  35897. this.position.copyFrom(this._newPosition);
  35898. var up = this.upVector;
  35899. if (this.allowUpsideDown && sinb < 0) {
  35900. up = up.clone();
  35901. up = up.negate();
  35902. }
  35903. if (this.getScene().useRightHandedSystem) {
  35904. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  35905. }
  35906. else {
  35907. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  35908. }
  35909. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  35910. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  35911. }
  35912. this._currentTarget = target;
  35913. return this._viewMatrix;
  35914. };
  35915. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  35916. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  35917. meshes = meshes || this.getScene().meshes;
  35918. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  35919. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  35920. this.radius = distance * this.zoomOnFactor;
  35921. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  35922. };
  35923. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  35924. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  35925. var meshesOrMinMaxVector;
  35926. var distance;
  35927. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  35928. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  35929. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  35930. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  35931. }
  35932. else {
  35933. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  35934. distance = meshesOrMinMaxVectorAndDistance.distance;
  35935. }
  35936. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  35937. if (!doNotUpdateMaxZ) {
  35938. this.maxZ = distance * 2;
  35939. }
  35940. };
  35941. /**
  35942. * @override
  35943. * Override Camera.createRigCamera
  35944. */
  35945. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  35946. var alphaShift;
  35947. switch (this.cameraRigMode) {
  35948. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  35949. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  35950. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  35951. case BABYLON.Camera.RIG_MODE_VR:
  35952. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  35953. break;
  35954. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  35955. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  35956. break;
  35957. }
  35958. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  35959. rigCam._cameraRigParams = {};
  35960. return rigCam;
  35961. };
  35962. /**
  35963. * @override
  35964. * Override Camera._updateRigCameras
  35965. */
  35966. ArcRotateCamera.prototype._updateRigCameras = function () {
  35967. var camLeft = this._rigCameras[0];
  35968. var camRight = this._rigCameras[1];
  35969. camLeft.beta = camRight.beta = this.beta;
  35970. camLeft.radius = camRight.radius = this.radius;
  35971. switch (this.cameraRigMode) {
  35972. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  35973. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  35974. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  35975. case BABYLON.Camera.RIG_MODE_VR:
  35976. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  35977. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  35978. break;
  35979. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  35980. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  35981. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  35982. break;
  35983. }
  35984. _super.prototype._updateRigCameras.call(this);
  35985. };
  35986. ArcRotateCamera.prototype.dispose = function () {
  35987. this.inputs.clear();
  35988. _super.prototype.dispose.call(this);
  35989. };
  35990. ArcRotateCamera.prototype.getClassName = function () {
  35991. return "ArcRotateCamera";
  35992. };
  35993. __decorate([
  35994. BABYLON.serialize()
  35995. ], ArcRotateCamera.prototype, "alpha", void 0);
  35996. __decorate([
  35997. BABYLON.serialize()
  35998. ], ArcRotateCamera.prototype, "beta", void 0);
  35999. __decorate([
  36000. BABYLON.serialize()
  36001. ], ArcRotateCamera.prototype, "radius", void 0);
  36002. __decorate([
  36003. BABYLON.serializeAsVector3("target")
  36004. ], ArcRotateCamera.prototype, "_target", void 0);
  36005. __decorate([
  36006. BABYLON.serialize()
  36007. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  36008. __decorate([
  36009. BABYLON.serialize()
  36010. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  36011. __decorate([
  36012. BABYLON.serialize()
  36013. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  36014. __decorate([
  36015. BABYLON.serialize()
  36016. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  36017. __decorate([
  36018. BABYLON.serialize()
  36019. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  36020. __decorate([
  36021. BABYLON.serialize()
  36022. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  36023. __decorate([
  36024. BABYLON.serialize()
  36025. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  36026. __decorate([
  36027. BABYLON.serialize()
  36028. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  36029. __decorate([
  36030. BABYLON.serialize()
  36031. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  36032. __decorate([
  36033. BABYLON.serialize()
  36034. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  36035. __decorate([
  36036. BABYLON.serialize()
  36037. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  36038. __decorate([
  36039. BABYLON.serialize()
  36040. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  36041. __decorate([
  36042. BABYLON.serialize()
  36043. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  36044. __decorate([
  36045. BABYLON.serializeAsVector3()
  36046. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  36047. __decorate([
  36048. BABYLON.serialize()
  36049. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  36050. __decorate([
  36051. BABYLON.serialize()
  36052. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  36053. __decorate([
  36054. BABYLON.serialize()
  36055. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  36056. return ArcRotateCamera;
  36057. }(BABYLON.TargetCamera));
  36058. BABYLON.ArcRotateCamera = ArcRotateCamera;
  36059. })(BABYLON || (BABYLON = {}));
  36060. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  36061. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  36062. var BABYLON;
  36063. (function (BABYLON) {
  36064. var ArcRotateCameraInputsManager = (function (_super) {
  36065. __extends(ArcRotateCameraInputsManager, _super);
  36066. function ArcRotateCameraInputsManager(camera) {
  36067. return _super.call(this, camera) || this;
  36068. }
  36069. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  36070. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  36071. return this;
  36072. };
  36073. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  36074. this.add(new BABYLON.ArcRotateCameraPointersInput());
  36075. return this;
  36076. };
  36077. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  36078. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  36079. return this;
  36080. };
  36081. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  36082. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  36083. return this;
  36084. };
  36085. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  36086. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  36087. return this;
  36088. };
  36089. return ArcRotateCameraInputsManager;
  36090. }(BABYLON.CameraInputsManager));
  36091. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  36092. })(BABYLON || (BABYLON = {}));
  36093. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  36094. var BABYLON;
  36095. (function (BABYLON) {
  36096. var HemisphericLight = (function (_super) {
  36097. __extends(HemisphericLight, _super);
  36098. /**
  36099. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  36100. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  36101. * The HemisphericLight can't cast shadows.
  36102. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36103. */
  36104. function HemisphericLight(name, direction, scene) {
  36105. var _this = _super.call(this, name, scene) || this;
  36106. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  36107. _this.direction = direction || BABYLON.Vector3.Up();
  36108. return _this;
  36109. }
  36110. HemisphericLight.prototype._buildUniformLayout = function () {
  36111. this._uniformBuffer.addUniform("vLightData", 4);
  36112. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36113. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36114. this._uniformBuffer.addUniform("vLightGround", 3);
  36115. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36116. this._uniformBuffer.addUniform("depthValues", 2);
  36117. this._uniformBuffer.create();
  36118. };
  36119. /**
  36120. * Returns the string "HemisphericLight".
  36121. */
  36122. HemisphericLight.prototype.getClassName = function () {
  36123. return "HemisphericLight";
  36124. };
  36125. /**
  36126. * Sets the HemisphericLight direction towards the passed target (Vector3).
  36127. * Returns the updated direction.
  36128. */
  36129. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  36130. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  36131. return this.direction;
  36132. };
  36133. HemisphericLight.prototype.getShadowGenerator = function () {
  36134. return null;
  36135. };
  36136. /**
  36137. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  36138. * Returns the HemisphericLight.
  36139. */
  36140. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  36141. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  36142. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  36143. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  36144. return this;
  36145. };
  36146. HemisphericLight.prototype._getWorldMatrix = function () {
  36147. if (!this._worldMatrix) {
  36148. this._worldMatrix = BABYLON.Matrix.Identity();
  36149. }
  36150. return this._worldMatrix;
  36151. };
  36152. /**
  36153. * Returns the integer 3.
  36154. */
  36155. HemisphericLight.prototype.getTypeID = function () {
  36156. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  36157. };
  36158. __decorate([
  36159. BABYLON.serializeAsColor3()
  36160. ], HemisphericLight.prototype, "groundColor", void 0);
  36161. __decorate([
  36162. BABYLON.serializeAsVector3()
  36163. ], HemisphericLight.prototype, "direction", void 0);
  36164. return HemisphericLight;
  36165. }(BABYLON.Light));
  36166. BABYLON.HemisphericLight = HemisphericLight;
  36167. })(BABYLON || (BABYLON = {}));
  36168. //# sourceMappingURL=babylon.hemisphericLight.js.map
  36169. var BABYLON;
  36170. (function (BABYLON) {
  36171. var ShadowLight = (function (_super) {
  36172. __extends(ShadowLight, _super);
  36173. function ShadowLight() {
  36174. var _this = _super !== null && _super.apply(this, arguments) || this;
  36175. _this._needProjectionMatrixCompute = true;
  36176. return _this;
  36177. }
  36178. Object.defineProperty(ShadowLight.prototype, "direction", {
  36179. get: function () {
  36180. return this._direction;
  36181. },
  36182. set: function (value) {
  36183. this._direction = value;
  36184. },
  36185. enumerable: true,
  36186. configurable: true
  36187. });
  36188. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  36189. get: function () {
  36190. return this._shadowMinZ;
  36191. },
  36192. set: function (value) {
  36193. this._shadowMinZ = value;
  36194. this.forceProjectionMatrixCompute();
  36195. },
  36196. enumerable: true,
  36197. configurable: true
  36198. });
  36199. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  36200. get: function () {
  36201. return this._shadowMaxZ;
  36202. },
  36203. set: function (value) {
  36204. this._shadowMaxZ = value;
  36205. this.forceProjectionMatrixCompute();
  36206. },
  36207. enumerable: true,
  36208. configurable: true
  36209. });
  36210. /**
  36211. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  36212. */
  36213. ShadowLight.prototype.computeTransformedInformation = function () {
  36214. if (this.parent && this.parent.getWorldMatrix) {
  36215. if (!this.transformedPosition) {
  36216. this.transformedPosition = BABYLON.Vector3.Zero();
  36217. }
  36218. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  36219. // In case the direction is present.
  36220. if (this.direction) {
  36221. if (!this.transformedDirection) {
  36222. this.transformedDirection = BABYLON.Vector3.Zero();
  36223. }
  36224. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  36225. }
  36226. return true;
  36227. }
  36228. return false;
  36229. };
  36230. /**
  36231. * Return the depth scale used for the shadow map.
  36232. */
  36233. ShadowLight.prototype.getDepthScale = function () {
  36234. return 50.0;
  36235. };
  36236. /**
  36237. * Returns the light direction (Vector3) for any passed face index.
  36238. */
  36239. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  36240. return this.transformedDirection ? this.transformedDirection : this.direction;
  36241. };
  36242. /**
  36243. * Returns the DirectionalLight absolute position in the World.
  36244. */
  36245. ShadowLight.prototype.getAbsolutePosition = function () {
  36246. return this.transformedPosition ? this.transformedPosition : this.position;
  36247. };
  36248. /**
  36249. * Sets the DirectionalLight direction toward the passed target (Vector3).
  36250. * Returns the updated DirectionalLight direction (Vector3).
  36251. */
  36252. ShadowLight.prototype.setDirectionToTarget = function (target) {
  36253. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  36254. return this.direction;
  36255. };
  36256. /**
  36257. * Returns the light rotation (Vector3).
  36258. */
  36259. ShadowLight.prototype.getRotation = function () {
  36260. this.direction.normalize();
  36261. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  36262. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  36263. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  36264. };
  36265. /**
  36266. * Boolean : false by default.
  36267. */
  36268. ShadowLight.prototype.needCube = function () {
  36269. return false;
  36270. };
  36271. /**
  36272. * Specifies wether or not the projection matrix should be recomputed this frame.
  36273. */
  36274. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  36275. return this._needProjectionMatrixCompute;
  36276. };
  36277. /**
  36278. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  36279. */
  36280. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  36281. this._needProjectionMatrixCompute = true;
  36282. };
  36283. /**
  36284. * Get the world matrix of the sahdow lights.
  36285. */
  36286. ShadowLight.prototype._getWorldMatrix = function () {
  36287. if (!this._worldMatrix) {
  36288. this._worldMatrix = BABYLON.Matrix.Identity();
  36289. }
  36290. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  36291. return this._worldMatrix;
  36292. };
  36293. /**
  36294. * Gets the minZ used for shadow according to both the scene and the light.
  36295. * @param activeCamera
  36296. */
  36297. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  36298. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  36299. };
  36300. /**
  36301. * Gets the maxZ used for shadow according to both the scene and the light.
  36302. * @param activeCamera
  36303. */
  36304. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  36305. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  36306. };
  36307. /**
  36308. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  36309. * Returns the light.
  36310. */
  36311. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36312. if (this.customProjectionMatrixBuilder) {
  36313. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  36314. }
  36315. else {
  36316. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36317. }
  36318. return this;
  36319. };
  36320. __decorate([
  36321. BABYLON.serializeAsVector3()
  36322. ], ShadowLight.prototype, "position", void 0);
  36323. __decorate([
  36324. BABYLON.serializeAsVector3()
  36325. ], ShadowLight.prototype, "direction", null);
  36326. __decorate([
  36327. BABYLON.serialize()
  36328. ], ShadowLight.prototype, "shadowMinZ", null);
  36329. __decorate([
  36330. BABYLON.serialize()
  36331. ], ShadowLight.prototype, "shadowMaxZ", null);
  36332. return ShadowLight;
  36333. }(BABYLON.Light));
  36334. BABYLON.ShadowLight = ShadowLight;
  36335. })(BABYLON || (BABYLON = {}));
  36336. //# sourceMappingURL=babylon.shadowLight.js.map
  36337. var BABYLON;
  36338. (function (BABYLON) {
  36339. var PointLight = (function (_super) {
  36340. __extends(PointLight, _super);
  36341. /**
  36342. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  36343. * A PointLight emits the light in every direction.
  36344. * It can cast shadows.
  36345. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  36346. * ```javascript
  36347. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  36348. * ```
  36349. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36350. */
  36351. function PointLight(name, position, scene) {
  36352. var _this = _super.call(this, name, scene) || this;
  36353. _this._shadowAngle = Math.PI / 2;
  36354. _this.position = position;
  36355. return _this;
  36356. }
  36357. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  36358. /**
  36359. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36360. * This specifies what angle the shadow will use to be created.
  36361. *
  36362. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36363. */
  36364. get: function () {
  36365. return this._shadowAngle;
  36366. },
  36367. /**
  36368. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36369. * This specifies what angle the shadow will use to be created.
  36370. *
  36371. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  36372. */
  36373. set: function (value) {
  36374. this._shadowAngle = value;
  36375. this.forceProjectionMatrixCompute();
  36376. },
  36377. enumerable: true,
  36378. configurable: true
  36379. });
  36380. Object.defineProperty(PointLight.prototype, "direction", {
  36381. get: function () {
  36382. return this._direction;
  36383. },
  36384. /**
  36385. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  36386. */
  36387. set: function (value) {
  36388. var previousNeedCube = this.needCube();
  36389. this._direction = value;
  36390. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  36391. this._shadowGenerator.recreateShadowMap();
  36392. }
  36393. },
  36394. enumerable: true,
  36395. configurable: true
  36396. });
  36397. /**
  36398. * Returns the string "PointLight"
  36399. */
  36400. PointLight.prototype.getClassName = function () {
  36401. return "PointLight";
  36402. };
  36403. /**
  36404. * Returns the integer 0.
  36405. */
  36406. PointLight.prototype.getTypeID = function () {
  36407. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  36408. };
  36409. /**
  36410. * Specifies wether or not the shadowmap should be a cube texture.
  36411. */
  36412. PointLight.prototype.needCube = function () {
  36413. return !this.direction;
  36414. };
  36415. /**
  36416. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  36417. */
  36418. PointLight.prototype.getShadowDirection = function (faceIndex) {
  36419. if (this.direction) {
  36420. return _super.prototype.getShadowDirection.call(this, faceIndex);
  36421. }
  36422. else {
  36423. switch (faceIndex) {
  36424. case 0:
  36425. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  36426. case 1:
  36427. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  36428. case 2:
  36429. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  36430. case 3:
  36431. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  36432. case 4:
  36433. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  36434. case 5:
  36435. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  36436. }
  36437. }
  36438. return BABYLON.Vector3.Zero();
  36439. };
  36440. /**
  36441. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  36442. * - fov = PI / 2
  36443. * - aspect ratio : 1.0
  36444. * - z-near and far equal to the active camera minZ and maxZ.
  36445. * Returns the PointLight.
  36446. */
  36447. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36448. var activeCamera = this.getScene().activeCamera;
  36449. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36450. };
  36451. PointLight.prototype._buildUniformLayout = function () {
  36452. this._uniformBuffer.addUniform("vLightData", 4);
  36453. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36454. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36455. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36456. this._uniformBuffer.addUniform("depthValues", 2);
  36457. this._uniformBuffer.create();
  36458. };
  36459. /**
  36460. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  36461. * Returns the PointLight.
  36462. */
  36463. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  36464. if (this.computeTransformedInformation()) {
  36465. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  36466. return this;
  36467. }
  36468. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  36469. return this;
  36470. };
  36471. __decorate([
  36472. BABYLON.serialize()
  36473. ], PointLight.prototype, "shadowAngle", null);
  36474. return PointLight;
  36475. }(BABYLON.ShadowLight));
  36476. BABYLON.PointLight = PointLight;
  36477. })(BABYLON || (BABYLON = {}));
  36478. //# sourceMappingURL=babylon.pointLight.js.map
  36479. /// <reference path="babylon.light.ts" />
  36480. var BABYLON;
  36481. (function (BABYLON) {
  36482. var DirectionalLight = (function (_super) {
  36483. __extends(DirectionalLight, _super);
  36484. /**
  36485. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  36486. * The directional light is emitted from everywhere in the given direction.
  36487. * It can cast shawdows.
  36488. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36489. */
  36490. function DirectionalLight(name, direction, scene) {
  36491. var _this = _super.call(this, name, scene) || this;
  36492. _this._shadowFrustumSize = 0;
  36493. _this._shadowOrthoScale = 0.5;
  36494. _this.autoUpdateExtends = true;
  36495. // Cache
  36496. _this._orthoLeft = Number.MAX_VALUE;
  36497. _this._orthoRight = Number.MIN_VALUE;
  36498. _this._orthoTop = Number.MIN_VALUE;
  36499. _this._orthoBottom = Number.MAX_VALUE;
  36500. _this.position = direction.scale(-1.0);
  36501. _this.direction = direction;
  36502. return _this;
  36503. }
  36504. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  36505. /**
  36506. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  36507. */
  36508. get: function () {
  36509. return this._shadowFrustumSize;
  36510. },
  36511. /**
  36512. * Specifies a fix frustum size for the shadow generation.
  36513. */
  36514. set: function (value) {
  36515. this._shadowFrustumSize = value;
  36516. this.forceProjectionMatrixCompute();
  36517. },
  36518. enumerable: true,
  36519. configurable: true
  36520. });
  36521. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  36522. get: function () {
  36523. return this._shadowOrthoScale;
  36524. },
  36525. set: function (value) {
  36526. this._shadowOrthoScale = value;
  36527. this.forceProjectionMatrixCompute();
  36528. },
  36529. enumerable: true,
  36530. configurable: true
  36531. });
  36532. /**
  36533. * Returns the string "DirectionalLight".
  36534. */
  36535. DirectionalLight.prototype.getClassName = function () {
  36536. return "DirectionalLight";
  36537. };
  36538. /**
  36539. * Returns the integer 1.
  36540. */
  36541. DirectionalLight.prototype.getTypeID = function () {
  36542. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  36543. };
  36544. /**
  36545. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  36546. * Returns the DirectionalLight Shadow projection matrix.
  36547. */
  36548. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36549. if (this.shadowFrustumSize > 0) {
  36550. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  36551. }
  36552. else {
  36553. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36554. }
  36555. };
  36556. /**
  36557. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  36558. * Returns the DirectionalLight Shadow projection matrix.
  36559. */
  36560. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  36561. var activeCamera = this.getScene().activeCamera;
  36562. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  36563. };
  36564. /**
  36565. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  36566. * Returns the DirectionalLight Shadow projection matrix.
  36567. */
  36568. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36569. var activeCamera = this.getScene().activeCamera;
  36570. // Check extends
  36571. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  36572. var tempVector3 = BABYLON.Vector3.Zero();
  36573. this._orthoLeft = Number.MAX_VALUE;
  36574. this._orthoRight = Number.MIN_VALUE;
  36575. this._orthoTop = Number.MIN_VALUE;
  36576. this._orthoBottom = Number.MAX_VALUE;
  36577. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  36578. var mesh = renderList[meshIndex];
  36579. if (!mesh) {
  36580. continue;
  36581. }
  36582. var boundingInfo = mesh.getBoundingInfo();
  36583. if (!boundingInfo) {
  36584. continue;
  36585. }
  36586. var boundingBox = boundingInfo.boundingBox;
  36587. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  36588. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  36589. if (tempVector3.x < this._orthoLeft)
  36590. this._orthoLeft = tempVector3.x;
  36591. if (tempVector3.y < this._orthoBottom)
  36592. this._orthoBottom = tempVector3.y;
  36593. if (tempVector3.x > this._orthoRight)
  36594. this._orthoRight = tempVector3.x;
  36595. if (tempVector3.y > this._orthoTop)
  36596. this._orthoTop = tempVector3.y;
  36597. }
  36598. }
  36599. }
  36600. var xOffset = this._orthoRight - this._orthoLeft;
  36601. var yOffset = this._orthoTop - this._orthoBottom;
  36602. 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);
  36603. };
  36604. DirectionalLight.prototype._buildUniformLayout = function () {
  36605. this._uniformBuffer.addUniform("vLightData", 4);
  36606. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36607. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36608. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36609. this._uniformBuffer.addUniform("depthValues", 2);
  36610. this._uniformBuffer.create();
  36611. };
  36612. /**
  36613. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  36614. * Returns the DirectionalLight.
  36615. */
  36616. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  36617. if (this.computeTransformedInformation()) {
  36618. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  36619. return this;
  36620. }
  36621. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  36622. return this;
  36623. };
  36624. /**
  36625. * Gets the minZ used for shadow according to both the scene and the light.
  36626. *
  36627. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36628. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36629. * @param activeCamera
  36630. */
  36631. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  36632. return 1;
  36633. };
  36634. /**
  36635. * Gets the maxZ used for shadow according to both the scene and the light.
  36636. *
  36637. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36638. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36639. * @param activeCamera
  36640. */
  36641. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  36642. return 1;
  36643. };
  36644. __decorate([
  36645. BABYLON.serialize()
  36646. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  36647. __decorate([
  36648. BABYLON.serialize()
  36649. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  36650. __decorate([
  36651. BABYLON.serialize()
  36652. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  36653. return DirectionalLight;
  36654. }(BABYLON.ShadowLight));
  36655. BABYLON.DirectionalLight = DirectionalLight;
  36656. })(BABYLON || (BABYLON = {}));
  36657. //# sourceMappingURL=babylon.directionalLight.js.map
  36658. var BABYLON;
  36659. (function (BABYLON) {
  36660. var SpotLight = (function (_super) {
  36661. __extends(SpotLight, _super);
  36662. /**
  36663. * Creates a SpotLight object in the scene with the passed parameters :
  36664. * - `position` (Vector3) is the initial SpotLight position,
  36665. * - `direction` (Vector3) is the initial SpotLight direction,
  36666. * - `angle` (float, in radians) is the spot light cone angle,
  36667. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  36668. * A spot light is a simply light oriented cone.
  36669. * It can cast shadows.
  36670. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36671. */
  36672. function SpotLight(name, position, direction, angle, exponent, scene) {
  36673. var _this = _super.call(this, name, scene) || this;
  36674. _this.position = position;
  36675. _this.direction = direction;
  36676. _this.angle = angle;
  36677. _this.exponent = exponent;
  36678. return _this;
  36679. }
  36680. Object.defineProperty(SpotLight.prototype, "angle", {
  36681. get: function () {
  36682. return this._angle;
  36683. },
  36684. set: function (value) {
  36685. this._angle = value;
  36686. this.forceProjectionMatrixCompute();
  36687. },
  36688. enumerable: true,
  36689. configurable: true
  36690. });
  36691. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  36692. get: function () {
  36693. return this._shadowAngleScale;
  36694. },
  36695. /**
  36696. * Allows scaling the angle of the light for shadow generation only.
  36697. */
  36698. set: function (value) {
  36699. this._shadowAngleScale = value;
  36700. this.forceProjectionMatrixCompute();
  36701. },
  36702. enumerable: true,
  36703. configurable: true
  36704. });
  36705. /**
  36706. * Returns the string "SpotLight".
  36707. */
  36708. SpotLight.prototype.getClassName = function () {
  36709. return "SpotLight";
  36710. };
  36711. /**
  36712. * Returns the integer 2.
  36713. */
  36714. SpotLight.prototype.getTypeID = function () {
  36715. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  36716. };
  36717. /**
  36718. * 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.
  36719. * Returns the SpotLight.
  36720. */
  36721. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36722. var activeCamera = this.getScene().activeCamera;
  36723. this._shadowAngleScale = this._shadowAngleScale || 1;
  36724. var angle = this._shadowAngleScale * this._angle;
  36725. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36726. };
  36727. SpotLight.prototype._buildUniformLayout = function () {
  36728. this._uniformBuffer.addUniform("vLightData", 4);
  36729. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36730. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36731. this._uniformBuffer.addUniform("vLightDirection", 3);
  36732. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36733. this._uniformBuffer.addUniform("depthValues", 2);
  36734. this._uniformBuffer.create();
  36735. };
  36736. /**
  36737. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  36738. * Return the SpotLight.
  36739. */
  36740. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  36741. var normalizeDirection;
  36742. if (this.computeTransformedInformation()) {
  36743. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  36744. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  36745. }
  36746. else {
  36747. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  36748. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  36749. }
  36750. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  36751. return this;
  36752. };
  36753. __decorate([
  36754. BABYLON.serialize()
  36755. ], SpotLight.prototype, "angle", null);
  36756. __decorate([
  36757. BABYLON.serialize()
  36758. /**
  36759. * Allows scaling the angle of the light for shadow generation only.
  36760. */
  36761. ], SpotLight.prototype, "shadowAngleScale", null);
  36762. __decorate([
  36763. BABYLON.serialize()
  36764. ], SpotLight.prototype, "exponent", void 0);
  36765. return SpotLight;
  36766. }(BABYLON.ShadowLight));
  36767. BABYLON.SpotLight = SpotLight;
  36768. })(BABYLON || (BABYLON = {}));
  36769. //# sourceMappingURL=babylon.spotLight.js.map
  36770. var BABYLON;
  36771. (function (BABYLON) {
  36772. var AnimationRange = (function () {
  36773. function AnimationRange(name, from, to) {
  36774. this.name = name;
  36775. this.from = from;
  36776. this.to = to;
  36777. }
  36778. AnimationRange.prototype.clone = function () {
  36779. return new AnimationRange(this.name, this.from, this.to);
  36780. };
  36781. return AnimationRange;
  36782. }());
  36783. BABYLON.AnimationRange = AnimationRange;
  36784. /**
  36785. * Composed of a frame, and an action function
  36786. */
  36787. var AnimationEvent = (function () {
  36788. function AnimationEvent(frame, action, onlyOnce) {
  36789. this.frame = frame;
  36790. this.action = action;
  36791. this.onlyOnce = onlyOnce;
  36792. this.isDone = false;
  36793. }
  36794. return AnimationEvent;
  36795. }());
  36796. BABYLON.AnimationEvent = AnimationEvent;
  36797. var PathCursor = (function () {
  36798. function PathCursor(path) {
  36799. this.path = path;
  36800. this._onchange = new Array();
  36801. this.value = 0;
  36802. this.animations = new Array();
  36803. }
  36804. PathCursor.prototype.getPoint = function () {
  36805. var point = this.path.getPointAtLengthPosition(this.value);
  36806. return new BABYLON.Vector3(point.x, 0, point.y);
  36807. };
  36808. PathCursor.prototype.moveAhead = function (step) {
  36809. if (step === void 0) { step = 0.002; }
  36810. this.move(step);
  36811. return this;
  36812. };
  36813. PathCursor.prototype.moveBack = function (step) {
  36814. if (step === void 0) { step = 0.002; }
  36815. this.move(-step);
  36816. return this;
  36817. };
  36818. PathCursor.prototype.move = function (step) {
  36819. if (Math.abs(step) > 1) {
  36820. throw "step size should be less than 1.";
  36821. }
  36822. this.value += step;
  36823. this.ensureLimits();
  36824. this.raiseOnChange();
  36825. return this;
  36826. };
  36827. PathCursor.prototype.ensureLimits = function () {
  36828. while (this.value > 1) {
  36829. this.value -= 1;
  36830. }
  36831. while (this.value < 0) {
  36832. this.value += 1;
  36833. }
  36834. return this;
  36835. };
  36836. // used by animation engine
  36837. PathCursor.prototype.markAsDirty = function (propertyName) {
  36838. this.ensureLimits();
  36839. this.raiseOnChange();
  36840. return this;
  36841. };
  36842. PathCursor.prototype.raiseOnChange = function () {
  36843. var _this = this;
  36844. this._onchange.forEach(function (f) { return f(_this); });
  36845. return this;
  36846. };
  36847. PathCursor.prototype.onchange = function (f) {
  36848. this._onchange.push(f);
  36849. return this;
  36850. };
  36851. return PathCursor;
  36852. }());
  36853. BABYLON.PathCursor = PathCursor;
  36854. var Animation = (function () {
  36855. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  36856. this.name = name;
  36857. this.targetProperty = targetProperty;
  36858. this.framePerSecond = framePerSecond;
  36859. this.dataType = dataType;
  36860. this.loopMode = loopMode;
  36861. this.enableBlending = enableBlending;
  36862. this._offsetsCache = {};
  36863. this._highLimitsCache = {};
  36864. this._stopped = false;
  36865. this._blendingFactor = 0;
  36866. // The set of event that will be linked to this animation
  36867. this._events = new Array();
  36868. this.blendingSpeed = 0.01;
  36869. this._ranges = {};
  36870. this.targetPropertyPath = targetProperty.split(".");
  36871. this.dataType = dataType;
  36872. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  36873. }
  36874. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  36875. var dataType = undefined;
  36876. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  36877. dataType = Animation.ANIMATIONTYPE_FLOAT;
  36878. }
  36879. else if (from instanceof BABYLON.Quaternion) {
  36880. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  36881. }
  36882. else if (from instanceof BABYLON.Vector3) {
  36883. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  36884. }
  36885. else if (from instanceof BABYLON.Vector2) {
  36886. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  36887. }
  36888. else if (from instanceof BABYLON.Color3) {
  36889. dataType = Animation.ANIMATIONTYPE_COLOR3;
  36890. }
  36891. else if (from instanceof BABYLON.Size) {
  36892. dataType = Animation.ANIMATIONTYPE_SIZE;
  36893. }
  36894. if (dataType == undefined) {
  36895. return null;
  36896. }
  36897. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  36898. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  36899. animation.setKeys(keys);
  36900. if (easingFunction !== undefined) {
  36901. animation.setEasingFunction(easingFunction);
  36902. }
  36903. return animation;
  36904. };
  36905. /**
  36906. * Sets up an animation.
  36907. * @param property the property to animate
  36908. * @param animationType the animation type to apply
  36909. * @param easingFunction the easing function used in the animation
  36910. * @returns The created animation
  36911. */
  36912. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  36913. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  36914. animation.setEasingFunction(easingFunction);
  36915. return animation;
  36916. };
  36917. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  36918. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  36919. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  36920. };
  36921. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  36922. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  36923. node.animations.push(animation);
  36924. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  36925. };
  36926. /**
  36927. * Transition property of the Camera to the target Value.
  36928. * @param property The property to transition
  36929. * @param targetValue The target Value of the property
  36930. * @param host The object where the property to animate belongs
  36931. * @param scene Scene used to run the animation
  36932. * @param frameRate Framerate (in frame/s) to use
  36933. * @param transition The transition type we want to use
  36934. * @param duration The duration of the animation, in milliseconds
  36935. * @param onAnimationEnd Call back trigger at the end of the animation.
  36936. */
  36937. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  36938. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  36939. if (duration <= 0) {
  36940. host[property] = targetValue;
  36941. if (onAnimationEnd) {
  36942. onAnimationEnd();
  36943. }
  36944. return;
  36945. }
  36946. var endFrame = frameRate * (duration / 1000);
  36947. transition.setKeys([{
  36948. frame: 0,
  36949. value: host[property].clone ? host[property].clone() : host[property]
  36950. },
  36951. {
  36952. frame: endFrame,
  36953. value: targetValue
  36954. }]);
  36955. if (!host.animations) {
  36956. host.animations = [];
  36957. }
  36958. host.animations.push(transition);
  36959. var animation = scene.beginAnimation(host, 0, endFrame, false);
  36960. animation.onAnimationEnd = onAnimationEnd;
  36961. return animation;
  36962. };
  36963. // Methods
  36964. /**
  36965. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  36966. */
  36967. Animation.prototype.toString = function (fullDetails) {
  36968. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  36969. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  36970. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  36971. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  36972. if (fullDetails) {
  36973. ret += ", Ranges: {";
  36974. var first = true;
  36975. for (var name in this._ranges) {
  36976. if (first) {
  36977. ret += ", ";
  36978. first = false;
  36979. }
  36980. ret += name;
  36981. }
  36982. ret += "}";
  36983. }
  36984. return ret;
  36985. };
  36986. /**
  36987. * Add an event to this animation.
  36988. */
  36989. Animation.prototype.addEvent = function (event) {
  36990. this._events.push(event);
  36991. };
  36992. /**
  36993. * Remove all events found at the given frame
  36994. * @param frame
  36995. */
  36996. Animation.prototype.removeEvents = function (frame) {
  36997. for (var index = 0; index < this._events.length; index++) {
  36998. if (this._events[index].frame === frame) {
  36999. this._events.splice(index, 1);
  37000. index--;
  37001. }
  37002. }
  37003. };
  37004. Animation.prototype.createRange = function (name, from, to) {
  37005. // check name not already in use; could happen for bones after serialized
  37006. if (!this._ranges[name]) {
  37007. this._ranges[name] = new AnimationRange(name, from, to);
  37008. }
  37009. };
  37010. Animation.prototype.deleteRange = function (name, deleteFrames) {
  37011. if (deleteFrames === void 0) { deleteFrames = true; }
  37012. if (this._ranges[name]) {
  37013. if (deleteFrames) {
  37014. var from = this._ranges[name].from;
  37015. var to = this._ranges[name].to;
  37016. // this loop MUST go high to low for multiple splices to work
  37017. for (var key = this._keys.length - 1; key >= 0; key--) {
  37018. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  37019. this._keys.splice(key, 1);
  37020. }
  37021. }
  37022. }
  37023. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  37024. }
  37025. };
  37026. Animation.prototype.getRange = function (name) {
  37027. return this._ranges[name];
  37028. };
  37029. Animation.prototype.reset = function () {
  37030. this._offsetsCache = {};
  37031. this._highLimitsCache = {};
  37032. this.currentFrame = 0;
  37033. this._blendingFactor = 0;
  37034. this._originalBlendValue = null;
  37035. };
  37036. Animation.prototype.isStopped = function () {
  37037. return this._stopped;
  37038. };
  37039. Animation.prototype.getKeys = function () {
  37040. return this._keys;
  37041. };
  37042. Animation.prototype.getHighestFrame = function () {
  37043. var ret = 0;
  37044. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  37045. if (ret < this._keys[key].frame) {
  37046. ret = this._keys[key].frame;
  37047. }
  37048. }
  37049. return ret;
  37050. };
  37051. Animation.prototype.getEasingFunction = function () {
  37052. return this._easingFunction;
  37053. };
  37054. Animation.prototype.setEasingFunction = function (easingFunction) {
  37055. this._easingFunction = easingFunction;
  37056. };
  37057. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  37058. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  37059. };
  37060. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37061. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  37062. };
  37063. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  37064. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  37065. };
  37066. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37067. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  37068. };
  37069. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  37070. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  37071. };
  37072. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37073. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  37074. };
  37075. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  37076. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  37077. };
  37078. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  37079. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  37080. };
  37081. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  37082. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  37083. };
  37084. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  37085. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  37086. };
  37087. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  37088. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  37089. };
  37090. Animation.prototype.clone = function () {
  37091. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  37092. clone.enableBlending = this.enableBlending;
  37093. clone.blendingSpeed = this.blendingSpeed;
  37094. if (this._keys) {
  37095. clone.setKeys(this._keys);
  37096. }
  37097. if (this._ranges) {
  37098. clone._ranges = {};
  37099. for (var name in this._ranges) {
  37100. clone._ranges[name] = this._ranges[name].clone();
  37101. }
  37102. }
  37103. return clone;
  37104. };
  37105. Animation.prototype.setKeys = function (values) {
  37106. this._keys = values.slice(0);
  37107. this._offsetsCache = {};
  37108. this._highLimitsCache = {};
  37109. };
  37110. Animation.prototype._getKeyValue = function (value) {
  37111. if (typeof value === "function") {
  37112. return value();
  37113. }
  37114. return value;
  37115. };
  37116. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  37117. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  37118. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  37119. }
  37120. this.currentFrame = currentFrame;
  37121. // Try to get a hash to find the right key
  37122. var startKeyIndex = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
  37123. if (this._keys[startKeyIndex].frame >= currentFrame) {
  37124. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  37125. startKeyIndex--;
  37126. }
  37127. }
  37128. for (var key = startKeyIndex; key < this._keys.length; key++) {
  37129. var endKey = this._keys[key + 1];
  37130. if (endKey.frame >= currentFrame) {
  37131. var startKey = this._keys[key];
  37132. var startValue = this._getKeyValue(startKey.value);
  37133. var endValue = this._getKeyValue(endKey.value);
  37134. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  37135. var frameDelta = endKey.frame - startKey.frame;
  37136. // gradient : percent of currentFrame between the frame inf and the frame sup
  37137. var gradient = (currentFrame - startKey.frame) / frameDelta;
  37138. // check for easingFunction and correction of gradient
  37139. if (this._easingFunction != null) {
  37140. gradient = this._easingFunction.ease(gradient);
  37141. }
  37142. switch (this.dataType) {
  37143. // Float
  37144. case Animation.ANIMATIONTYPE_FLOAT:
  37145. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  37146. switch (loopMode) {
  37147. case Animation.ANIMATIONLOOPMODE_CYCLE:
  37148. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  37149. return floatValue;
  37150. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  37151. return offsetValue * repeatCount + floatValue;
  37152. }
  37153. break;
  37154. // Quaternion
  37155. case Animation.ANIMATIONTYPE_QUATERNION:
  37156. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  37157. switch (loopMode) {
  37158. case Animation.ANIMATIONLOOPMODE_CYCLE:
  37159. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  37160. return quatValue;
  37161. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  37162. return quatValue.add(offsetValue.scale(repeatCount));
  37163. }
  37164. return quatValue;
  37165. // Vector3
  37166. case Animation.ANIMATIONTYPE_VECTOR3:
  37167. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  37168. switch (loopMode) {
  37169. case Animation.ANIMATIONLOOPMODE_CYCLE:
  37170. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  37171. return vec3Value;
  37172. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  37173. return vec3Value.add(offsetValue.scale(repeatCount));
  37174. }
  37175. // Vector2
  37176. case Animation.ANIMATIONTYPE_VECTOR2:
  37177. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  37178. switch (loopMode) {
  37179. case Animation.ANIMATIONLOOPMODE_CYCLE:
  37180. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  37181. return vec2Value;
  37182. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  37183. return vec2Value.add(offsetValue.scale(repeatCount));
  37184. }
  37185. // Size
  37186. case Animation.ANIMATIONTYPE_SIZE:
  37187. switch (loopMode) {
  37188. case Animation.ANIMATIONLOOPMODE_CYCLE:
  37189. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  37190. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  37191. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  37192. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  37193. }
  37194. // Color3
  37195. case Animation.ANIMATIONTYPE_COLOR3:
  37196. switch (loopMode) {
  37197. case Animation.ANIMATIONLOOPMODE_CYCLE:
  37198. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  37199. return this.color3InterpolateFunction(startValue, endValue, gradient);
  37200. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  37201. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  37202. }
  37203. // Matrix
  37204. case Animation.ANIMATIONTYPE_MATRIX:
  37205. switch (loopMode) {
  37206. case Animation.ANIMATIONLOOPMODE_CYCLE:
  37207. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  37208. if (Animation.AllowMatricesInterpolation) {
  37209. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  37210. }
  37211. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  37212. return startValue;
  37213. }
  37214. default:
  37215. break;
  37216. }
  37217. break;
  37218. }
  37219. }
  37220. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  37221. };
  37222. Animation.prototype.setValue = function (currentValue, blend) {
  37223. if (blend === void 0) { blend = false; }
  37224. // Set value
  37225. var path;
  37226. var destination;
  37227. if (this.targetPropertyPath.length > 1) {
  37228. var property = this._target[this.targetPropertyPath[0]];
  37229. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  37230. property = property[this.targetPropertyPath[index]];
  37231. }
  37232. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  37233. destination = property;
  37234. }
  37235. else {
  37236. path = this.targetPropertyPath[0];
  37237. destination = this._target;
  37238. }
  37239. // Blending
  37240. if (this.enableBlending && this._blendingFactor <= 1.0) {
  37241. if (!this._originalBlendValue) {
  37242. if (destination[path].clone) {
  37243. this._originalBlendValue = destination[path].clone();
  37244. }
  37245. else {
  37246. this._originalBlendValue = destination[path];
  37247. }
  37248. }
  37249. if (this._originalBlendValue.prototype) {
  37250. if (this._originalBlendValue.prototype.Lerp) {
  37251. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  37252. }
  37253. else {
  37254. destination[path] = currentValue;
  37255. }
  37256. }
  37257. else if (this._originalBlendValue.m) {
  37258. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  37259. }
  37260. else {
  37261. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  37262. }
  37263. this._blendingFactor += this.blendingSpeed;
  37264. }
  37265. else {
  37266. destination[path] = currentValue;
  37267. }
  37268. if (this._target.markAsDirty) {
  37269. this._target.markAsDirty(this.targetProperty);
  37270. }
  37271. };
  37272. Animation.prototype.goToFrame = function (frame) {
  37273. if (frame < this._keys[0].frame) {
  37274. frame = this._keys[0].frame;
  37275. }
  37276. else if (frame > this._keys[this._keys.length - 1].frame) {
  37277. frame = this._keys[this._keys.length - 1].frame;
  37278. }
  37279. var currentValue = this._interpolate(frame, 0, this.loopMode);
  37280. this.setValue(currentValue);
  37281. };
  37282. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  37283. if (blend === void 0) { blend = false; }
  37284. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  37285. this._stopped = true;
  37286. return false;
  37287. }
  37288. var returnValue = true;
  37289. // Adding a start key at frame 0 if missing
  37290. if (this._keys[0].frame !== 0) {
  37291. var newKey = { frame: 0, value: this._keys[0].value };
  37292. this._keys.splice(0, 0, newKey);
  37293. }
  37294. // Check limits
  37295. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  37296. from = this._keys[0].frame;
  37297. }
  37298. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  37299. to = this._keys[this._keys.length - 1].frame;
  37300. }
  37301. //to and from cannot be the same key
  37302. if (from === to) {
  37303. from++;
  37304. }
  37305. // Compute ratio
  37306. var range = to - from;
  37307. var offsetValue;
  37308. // ratio represents the frame delta between from and to
  37309. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  37310. var highLimitValue = 0;
  37311. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  37312. returnValue = false;
  37313. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  37314. }
  37315. else {
  37316. // Get max value if required
  37317. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  37318. var keyOffset = to.toString() + from.toString();
  37319. if (!this._offsetsCache[keyOffset]) {
  37320. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  37321. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  37322. switch (this.dataType) {
  37323. // Float
  37324. case Animation.ANIMATIONTYPE_FLOAT:
  37325. this._offsetsCache[keyOffset] = toValue - fromValue;
  37326. break;
  37327. // Quaternion
  37328. case Animation.ANIMATIONTYPE_QUATERNION:
  37329. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37330. break;
  37331. // Vector3
  37332. case Animation.ANIMATIONTYPE_VECTOR3:
  37333. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37334. // Vector2
  37335. case Animation.ANIMATIONTYPE_VECTOR2:
  37336. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37337. // Size
  37338. case Animation.ANIMATIONTYPE_SIZE:
  37339. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37340. // Color3
  37341. case Animation.ANIMATIONTYPE_COLOR3:
  37342. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  37343. default:
  37344. break;
  37345. }
  37346. this._highLimitsCache[keyOffset] = toValue;
  37347. }
  37348. highLimitValue = this._highLimitsCache[keyOffset];
  37349. offsetValue = this._offsetsCache[keyOffset];
  37350. }
  37351. }
  37352. if (offsetValue === undefined) {
  37353. switch (this.dataType) {
  37354. // Float
  37355. case Animation.ANIMATIONTYPE_FLOAT:
  37356. offsetValue = 0;
  37357. break;
  37358. // Quaternion
  37359. case Animation.ANIMATIONTYPE_QUATERNION:
  37360. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  37361. break;
  37362. // Vector3
  37363. case Animation.ANIMATIONTYPE_VECTOR3:
  37364. offsetValue = BABYLON.Vector3.Zero();
  37365. break;
  37366. // Vector2
  37367. case Animation.ANIMATIONTYPE_VECTOR2:
  37368. offsetValue = BABYLON.Vector2.Zero();
  37369. break;
  37370. // Size
  37371. case Animation.ANIMATIONTYPE_SIZE:
  37372. offsetValue = BABYLON.Size.Zero();
  37373. break;
  37374. // Color3
  37375. case Animation.ANIMATIONTYPE_COLOR3:
  37376. offsetValue = BABYLON.Color3.Black();
  37377. }
  37378. }
  37379. // Compute value
  37380. var repeatCount = (ratio / range) >> 0;
  37381. var currentFrame = returnValue ? from + ratio % range : to;
  37382. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  37383. // Set value
  37384. this.setValue(currentValue);
  37385. // Check events
  37386. for (var index = 0; index < this._events.length; index++) {
  37387. // Make sure current frame has passed event frame and that event frame is within the current range
  37388. // Also, handle both forward and reverse animations
  37389. if ((range > 0 && currentFrame >= this._events[index].frame && this._events[index].frame >= from) ||
  37390. (range < 0 && currentFrame <= this._events[index].frame && this._events[index].frame <= from)) {
  37391. var event = this._events[index];
  37392. if (!event.isDone) {
  37393. // If event should be done only once, remove it.
  37394. if (event.onlyOnce) {
  37395. this._events.splice(index, 1);
  37396. index--;
  37397. }
  37398. event.isDone = true;
  37399. event.action();
  37400. } // Don't do anything if the event has already be done.
  37401. }
  37402. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  37403. // reset event, the animation is looping
  37404. this._events[index].isDone = false;
  37405. }
  37406. }
  37407. if (!returnValue) {
  37408. this._stopped = true;
  37409. }
  37410. return returnValue;
  37411. };
  37412. Animation.prototype.serialize = function () {
  37413. var serializationObject = {};
  37414. serializationObject.name = this.name;
  37415. serializationObject.property = this.targetProperty;
  37416. serializationObject.framePerSecond = this.framePerSecond;
  37417. serializationObject.dataType = this.dataType;
  37418. serializationObject.loopBehavior = this.loopMode;
  37419. serializationObject.enableBlending = this.enableBlending;
  37420. serializationObject.blendingSpeed = this.blendingSpeed;
  37421. var dataType = this.dataType;
  37422. serializationObject.keys = [];
  37423. var keys = this.getKeys();
  37424. for (var index = 0; index < keys.length; index++) {
  37425. var animationKey = keys[index];
  37426. var key = {};
  37427. key.frame = animationKey.frame;
  37428. switch (dataType) {
  37429. case Animation.ANIMATIONTYPE_FLOAT:
  37430. key.values = [animationKey.value];
  37431. break;
  37432. case Animation.ANIMATIONTYPE_QUATERNION:
  37433. case Animation.ANIMATIONTYPE_MATRIX:
  37434. case Animation.ANIMATIONTYPE_VECTOR3:
  37435. case Animation.ANIMATIONTYPE_COLOR3:
  37436. key.values = animationKey.value.asArray();
  37437. break;
  37438. }
  37439. serializationObject.keys.push(key);
  37440. }
  37441. serializationObject.ranges = [];
  37442. for (var name in this._ranges) {
  37443. var range = {};
  37444. range.name = name;
  37445. range.from = this._ranges[name].from;
  37446. range.to = this._ranges[name].to;
  37447. serializationObject.ranges.push(range);
  37448. }
  37449. return serializationObject;
  37450. };
  37451. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  37452. get: function () {
  37453. return Animation._ANIMATIONTYPE_FLOAT;
  37454. },
  37455. enumerable: true,
  37456. configurable: true
  37457. });
  37458. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  37459. get: function () {
  37460. return Animation._ANIMATIONTYPE_VECTOR3;
  37461. },
  37462. enumerable: true,
  37463. configurable: true
  37464. });
  37465. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  37466. get: function () {
  37467. return Animation._ANIMATIONTYPE_VECTOR2;
  37468. },
  37469. enumerable: true,
  37470. configurable: true
  37471. });
  37472. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  37473. get: function () {
  37474. return Animation._ANIMATIONTYPE_SIZE;
  37475. },
  37476. enumerable: true,
  37477. configurable: true
  37478. });
  37479. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  37480. get: function () {
  37481. return Animation._ANIMATIONTYPE_QUATERNION;
  37482. },
  37483. enumerable: true,
  37484. configurable: true
  37485. });
  37486. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  37487. get: function () {
  37488. return Animation._ANIMATIONTYPE_MATRIX;
  37489. },
  37490. enumerable: true,
  37491. configurable: true
  37492. });
  37493. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  37494. get: function () {
  37495. return Animation._ANIMATIONTYPE_COLOR3;
  37496. },
  37497. enumerable: true,
  37498. configurable: true
  37499. });
  37500. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  37501. get: function () {
  37502. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  37503. },
  37504. enumerable: true,
  37505. configurable: true
  37506. });
  37507. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  37508. get: function () {
  37509. return Animation._ANIMATIONLOOPMODE_CYCLE;
  37510. },
  37511. enumerable: true,
  37512. configurable: true
  37513. });
  37514. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  37515. get: function () {
  37516. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  37517. },
  37518. enumerable: true,
  37519. configurable: true
  37520. });
  37521. Animation.Parse = function (parsedAnimation) {
  37522. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  37523. var dataType = parsedAnimation.dataType;
  37524. var keys = [];
  37525. var data;
  37526. var index;
  37527. if (parsedAnimation.enableBlending) {
  37528. animation.enableBlending = parsedAnimation.enableBlending;
  37529. }
  37530. if (parsedAnimation.blendingSpeed) {
  37531. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  37532. }
  37533. for (index = 0; index < parsedAnimation.keys.length; index++) {
  37534. var key = parsedAnimation.keys[index];
  37535. switch (dataType) {
  37536. case Animation.ANIMATIONTYPE_FLOAT:
  37537. data = key.values[0];
  37538. break;
  37539. case Animation.ANIMATIONTYPE_QUATERNION:
  37540. data = BABYLON.Quaternion.FromArray(key.values);
  37541. break;
  37542. case Animation.ANIMATIONTYPE_MATRIX:
  37543. data = BABYLON.Matrix.FromArray(key.values);
  37544. break;
  37545. case Animation.ANIMATIONTYPE_COLOR3:
  37546. data = BABYLON.Color3.FromArray(key.values);
  37547. break;
  37548. case Animation.ANIMATIONTYPE_VECTOR3:
  37549. default:
  37550. data = BABYLON.Vector3.FromArray(key.values);
  37551. break;
  37552. }
  37553. keys.push({
  37554. frame: key.frame,
  37555. value: data
  37556. });
  37557. }
  37558. animation.setKeys(keys);
  37559. if (parsedAnimation.ranges) {
  37560. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  37561. data = parsedAnimation.ranges[index];
  37562. animation.createRange(data.name, data.from, data.to);
  37563. }
  37564. }
  37565. return animation;
  37566. };
  37567. Animation.AppendSerializedAnimations = function (source, destination) {
  37568. if (source.animations) {
  37569. destination.animations = [];
  37570. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  37571. var animation = source.animations[animationIndex];
  37572. destination.animations.push(animation.serialize());
  37573. }
  37574. }
  37575. };
  37576. Animation.AllowMatricesInterpolation = false;
  37577. // Statics
  37578. Animation._ANIMATIONTYPE_FLOAT = 0;
  37579. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  37580. Animation._ANIMATIONTYPE_QUATERNION = 2;
  37581. Animation._ANIMATIONTYPE_MATRIX = 3;
  37582. Animation._ANIMATIONTYPE_COLOR3 = 4;
  37583. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  37584. Animation._ANIMATIONTYPE_SIZE = 6;
  37585. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  37586. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  37587. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  37588. return Animation;
  37589. }());
  37590. BABYLON.Animation = Animation;
  37591. })(BABYLON || (BABYLON = {}));
  37592. //# sourceMappingURL=babylon.animation.js.map
  37593. var BABYLON;
  37594. (function (BABYLON) {
  37595. var Animatable = (function () {
  37596. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  37597. if (fromFrame === void 0) { fromFrame = 0; }
  37598. if (toFrame === void 0) { toFrame = 100; }
  37599. if (loopAnimation === void 0) { loopAnimation = false; }
  37600. if (speedRatio === void 0) { speedRatio = 1.0; }
  37601. this.target = target;
  37602. this.fromFrame = fromFrame;
  37603. this.toFrame = toFrame;
  37604. this.loopAnimation = loopAnimation;
  37605. this.speedRatio = speedRatio;
  37606. this.onAnimationEnd = onAnimationEnd;
  37607. this._localDelayOffset = null;
  37608. this._pausedDelay = null;
  37609. this._animations = new Array();
  37610. this._paused = false;
  37611. this.animationStarted = false;
  37612. if (animations) {
  37613. this.appendAnimations(target, animations);
  37614. }
  37615. this._scene = scene;
  37616. scene._activeAnimatables.push(this);
  37617. }
  37618. // Methods
  37619. Animatable.prototype.getAnimations = function () {
  37620. return this._animations;
  37621. };
  37622. Animatable.prototype.appendAnimations = function (target, animations) {
  37623. for (var index = 0; index < animations.length; index++) {
  37624. var animation = animations[index];
  37625. animation._target = target;
  37626. this._animations.push(animation);
  37627. }
  37628. };
  37629. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  37630. var animations = this._animations;
  37631. for (var index = 0; index < animations.length; index++) {
  37632. if (animations[index].targetProperty === property) {
  37633. return animations[index];
  37634. }
  37635. }
  37636. return null;
  37637. };
  37638. Animatable.prototype.reset = function () {
  37639. var animations = this._animations;
  37640. for (var index = 0; index < animations.length; index++) {
  37641. animations[index].reset();
  37642. }
  37643. this._localDelayOffset = null;
  37644. this._pausedDelay = null;
  37645. };
  37646. Animatable.prototype.enableBlending = function (blendingSpeed) {
  37647. var animations = this._animations;
  37648. for (var index = 0; index < animations.length; index++) {
  37649. animations[index].enableBlending = true;
  37650. animations[index].blendingSpeed = blendingSpeed;
  37651. }
  37652. };
  37653. Animatable.prototype.disableBlending = function () {
  37654. var animations = this._animations;
  37655. for (var index = 0; index < animations.length; index++) {
  37656. animations[index].enableBlending = false;
  37657. }
  37658. };
  37659. Animatable.prototype.goToFrame = function (frame) {
  37660. var animations = this._animations;
  37661. if (animations[0]) {
  37662. var fps = animations[0].framePerSecond;
  37663. var currentFrame = animations[0].currentFrame;
  37664. var adjustTime = frame - currentFrame;
  37665. var delay = adjustTime * 1000 / fps;
  37666. this._localDelayOffset -= delay;
  37667. }
  37668. for (var index = 0; index < animations.length; index++) {
  37669. animations[index].goToFrame(frame);
  37670. }
  37671. };
  37672. Animatable.prototype.pause = function () {
  37673. if (this._paused) {
  37674. return;
  37675. }
  37676. this._paused = true;
  37677. };
  37678. Animatable.prototype.restart = function () {
  37679. this._paused = false;
  37680. };
  37681. Animatable.prototype.stop = function (animationName) {
  37682. if (animationName) {
  37683. var idx = this._scene._activeAnimatables.indexOf(this);
  37684. if (idx > -1) {
  37685. var animations = this._animations;
  37686. for (var index = animations.length - 1; index >= 0; index--) {
  37687. if (typeof animationName === "string" && animations[index].name != animationName) {
  37688. continue;
  37689. }
  37690. animations[index].reset();
  37691. animations.splice(index, 1);
  37692. }
  37693. if (animations.length == 0) {
  37694. this._scene._activeAnimatables.splice(idx, 1);
  37695. if (this.onAnimationEnd) {
  37696. this.onAnimationEnd();
  37697. }
  37698. }
  37699. }
  37700. }
  37701. else {
  37702. var index = this._scene._activeAnimatables.indexOf(this);
  37703. if (index > -1) {
  37704. this._scene._activeAnimatables.splice(index, 1);
  37705. var animations = this._animations;
  37706. for (var index = 0; index < animations.length; index++) {
  37707. animations[index].reset();
  37708. }
  37709. if (this.onAnimationEnd) {
  37710. this.onAnimationEnd();
  37711. }
  37712. }
  37713. }
  37714. };
  37715. Animatable.prototype._animate = function (delay) {
  37716. if (this._paused) {
  37717. this.animationStarted = false;
  37718. if (this._pausedDelay === null) {
  37719. this._pausedDelay = delay;
  37720. }
  37721. return true;
  37722. }
  37723. if (this._localDelayOffset === null) {
  37724. this._localDelayOffset = delay;
  37725. }
  37726. else if (this._pausedDelay !== null) {
  37727. this._localDelayOffset += delay - this._pausedDelay;
  37728. this._pausedDelay = null;
  37729. }
  37730. // Animating
  37731. var running = false;
  37732. var animations = this._animations;
  37733. var index;
  37734. for (index = 0; index < animations.length; index++) {
  37735. var animation = animations[index];
  37736. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  37737. running = running || isRunning;
  37738. }
  37739. this.animationStarted = running;
  37740. if (!running) {
  37741. // Remove from active animatables
  37742. index = this._scene._activeAnimatables.indexOf(this);
  37743. this._scene._activeAnimatables.splice(index, 1);
  37744. }
  37745. if (!running && this.onAnimationEnd) {
  37746. this.onAnimationEnd();
  37747. this.onAnimationEnd = null;
  37748. }
  37749. return running;
  37750. };
  37751. return Animatable;
  37752. }());
  37753. BABYLON.Animatable = Animatable;
  37754. })(BABYLON || (BABYLON = {}));
  37755. //# sourceMappingURL=babylon.animatable.js.map
  37756. var BABYLON;
  37757. (function (BABYLON) {
  37758. var EasingFunction = (function () {
  37759. function EasingFunction() {
  37760. // Properties
  37761. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  37762. }
  37763. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  37764. get: function () {
  37765. return EasingFunction._EASINGMODE_EASEIN;
  37766. },
  37767. enumerable: true,
  37768. configurable: true
  37769. });
  37770. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  37771. get: function () {
  37772. return EasingFunction._EASINGMODE_EASEOUT;
  37773. },
  37774. enumerable: true,
  37775. configurable: true
  37776. });
  37777. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  37778. get: function () {
  37779. return EasingFunction._EASINGMODE_EASEINOUT;
  37780. },
  37781. enumerable: true,
  37782. configurable: true
  37783. });
  37784. EasingFunction.prototype.setEasingMode = function (easingMode) {
  37785. var n = Math.min(Math.max(easingMode, 0), 2);
  37786. this._easingMode = n;
  37787. };
  37788. EasingFunction.prototype.getEasingMode = function () {
  37789. return this._easingMode;
  37790. };
  37791. EasingFunction.prototype.easeInCore = function (gradient) {
  37792. throw new Error('You must implement this method');
  37793. };
  37794. EasingFunction.prototype.ease = function (gradient) {
  37795. switch (this._easingMode) {
  37796. case EasingFunction.EASINGMODE_EASEIN:
  37797. return this.easeInCore(gradient);
  37798. case EasingFunction.EASINGMODE_EASEOUT:
  37799. return (1 - this.easeInCore(1 - gradient));
  37800. }
  37801. if (gradient >= 0.5) {
  37802. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  37803. }
  37804. return (this.easeInCore(gradient * 2) * 0.5);
  37805. };
  37806. //Statics
  37807. EasingFunction._EASINGMODE_EASEIN = 0;
  37808. EasingFunction._EASINGMODE_EASEOUT = 1;
  37809. EasingFunction._EASINGMODE_EASEINOUT = 2;
  37810. return EasingFunction;
  37811. }());
  37812. BABYLON.EasingFunction = EasingFunction;
  37813. var CircleEase = (function (_super) {
  37814. __extends(CircleEase, _super);
  37815. function CircleEase() {
  37816. return _super !== null && _super.apply(this, arguments) || this;
  37817. }
  37818. CircleEase.prototype.easeInCore = function (gradient) {
  37819. gradient = Math.max(0, Math.min(1, gradient));
  37820. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  37821. };
  37822. return CircleEase;
  37823. }(EasingFunction));
  37824. BABYLON.CircleEase = CircleEase;
  37825. var BackEase = (function (_super) {
  37826. __extends(BackEase, _super);
  37827. function BackEase(amplitude) {
  37828. if (amplitude === void 0) { amplitude = 1; }
  37829. var _this = _super.call(this) || this;
  37830. _this.amplitude = amplitude;
  37831. return _this;
  37832. }
  37833. BackEase.prototype.easeInCore = function (gradient) {
  37834. var num = Math.max(0, this.amplitude);
  37835. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  37836. };
  37837. return BackEase;
  37838. }(EasingFunction));
  37839. BABYLON.BackEase = BackEase;
  37840. var BounceEase = (function (_super) {
  37841. __extends(BounceEase, _super);
  37842. function BounceEase(bounces, bounciness) {
  37843. if (bounces === void 0) { bounces = 3; }
  37844. if (bounciness === void 0) { bounciness = 2; }
  37845. var _this = _super.call(this) || this;
  37846. _this.bounces = bounces;
  37847. _this.bounciness = bounciness;
  37848. return _this;
  37849. }
  37850. BounceEase.prototype.easeInCore = function (gradient) {
  37851. var y = Math.max(0.0, this.bounces);
  37852. var bounciness = this.bounciness;
  37853. if (bounciness <= 1.0) {
  37854. bounciness = 1.001;
  37855. }
  37856. var num9 = Math.pow(bounciness, y);
  37857. var num5 = 1.0 - bounciness;
  37858. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  37859. var num15 = gradient * num4;
  37860. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  37861. var num3 = Math.floor(num65);
  37862. var num13 = num3 + 1.0;
  37863. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  37864. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  37865. var num7 = (num8 + num12) * 0.5;
  37866. var num6 = gradient - num7;
  37867. var num2 = num7 - num8;
  37868. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  37869. };
  37870. return BounceEase;
  37871. }(EasingFunction));
  37872. BABYLON.BounceEase = BounceEase;
  37873. var CubicEase = (function (_super) {
  37874. __extends(CubicEase, _super);
  37875. function CubicEase() {
  37876. return _super !== null && _super.apply(this, arguments) || this;
  37877. }
  37878. CubicEase.prototype.easeInCore = function (gradient) {
  37879. return (gradient * gradient * gradient);
  37880. };
  37881. return CubicEase;
  37882. }(EasingFunction));
  37883. BABYLON.CubicEase = CubicEase;
  37884. var ElasticEase = (function (_super) {
  37885. __extends(ElasticEase, _super);
  37886. function ElasticEase(oscillations, springiness) {
  37887. if (oscillations === void 0) { oscillations = 3; }
  37888. if (springiness === void 0) { springiness = 3; }
  37889. var _this = _super.call(this) || this;
  37890. _this.oscillations = oscillations;
  37891. _this.springiness = springiness;
  37892. return _this;
  37893. }
  37894. ElasticEase.prototype.easeInCore = function (gradient) {
  37895. var num2;
  37896. var num3 = Math.max(0.0, this.oscillations);
  37897. var num = Math.max(0.0, this.springiness);
  37898. if (num == 0) {
  37899. num2 = gradient;
  37900. }
  37901. else {
  37902. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  37903. }
  37904. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  37905. };
  37906. return ElasticEase;
  37907. }(EasingFunction));
  37908. BABYLON.ElasticEase = ElasticEase;
  37909. var ExponentialEase = (function (_super) {
  37910. __extends(ExponentialEase, _super);
  37911. function ExponentialEase(exponent) {
  37912. if (exponent === void 0) { exponent = 2; }
  37913. var _this = _super.call(this) || this;
  37914. _this.exponent = exponent;
  37915. return _this;
  37916. }
  37917. ExponentialEase.prototype.easeInCore = function (gradient) {
  37918. if (this.exponent <= 0) {
  37919. return gradient;
  37920. }
  37921. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  37922. };
  37923. return ExponentialEase;
  37924. }(EasingFunction));
  37925. BABYLON.ExponentialEase = ExponentialEase;
  37926. var PowerEase = (function (_super) {
  37927. __extends(PowerEase, _super);
  37928. function PowerEase(power) {
  37929. if (power === void 0) { power = 2; }
  37930. var _this = _super.call(this) || this;
  37931. _this.power = power;
  37932. return _this;
  37933. }
  37934. PowerEase.prototype.easeInCore = function (gradient) {
  37935. var y = Math.max(0.0, this.power);
  37936. return Math.pow(gradient, y);
  37937. };
  37938. return PowerEase;
  37939. }(EasingFunction));
  37940. BABYLON.PowerEase = PowerEase;
  37941. var QuadraticEase = (function (_super) {
  37942. __extends(QuadraticEase, _super);
  37943. function QuadraticEase() {
  37944. return _super !== null && _super.apply(this, arguments) || this;
  37945. }
  37946. QuadraticEase.prototype.easeInCore = function (gradient) {
  37947. return (gradient * gradient);
  37948. };
  37949. return QuadraticEase;
  37950. }(EasingFunction));
  37951. BABYLON.QuadraticEase = QuadraticEase;
  37952. var QuarticEase = (function (_super) {
  37953. __extends(QuarticEase, _super);
  37954. function QuarticEase() {
  37955. return _super !== null && _super.apply(this, arguments) || this;
  37956. }
  37957. QuarticEase.prototype.easeInCore = function (gradient) {
  37958. return (gradient * gradient * gradient * gradient);
  37959. };
  37960. return QuarticEase;
  37961. }(EasingFunction));
  37962. BABYLON.QuarticEase = QuarticEase;
  37963. var QuinticEase = (function (_super) {
  37964. __extends(QuinticEase, _super);
  37965. function QuinticEase() {
  37966. return _super !== null && _super.apply(this, arguments) || this;
  37967. }
  37968. QuinticEase.prototype.easeInCore = function (gradient) {
  37969. return (gradient * gradient * gradient * gradient * gradient);
  37970. };
  37971. return QuinticEase;
  37972. }(EasingFunction));
  37973. BABYLON.QuinticEase = QuinticEase;
  37974. var SineEase = (function (_super) {
  37975. __extends(SineEase, _super);
  37976. function SineEase() {
  37977. return _super !== null && _super.apply(this, arguments) || this;
  37978. }
  37979. SineEase.prototype.easeInCore = function (gradient) {
  37980. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  37981. };
  37982. return SineEase;
  37983. }(EasingFunction));
  37984. BABYLON.SineEase = SineEase;
  37985. var BezierCurveEase = (function (_super) {
  37986. __extends(BezierCurveEase, _super);
  37987. function BezierCurveEase(x1, y1, x2, y2) {
  37988. if (x1 === void 0) { x1 = 0; }
  37989. if (y1 === void 0) { y1 = 0; }
  37990. if (x2 === void 0) { x2 = 1; }
  37991. if (y2 === void 0) { y2 = 1; }
  37992. var _this = _super.call(this) || this;
  37993. _this.x1 = x1;
  37994. _this.y1 = y1;
  37995. _this.x2 = x2;
  37996. _this.y2 = y2;
  37997. return _this;
  37998. }
  37999. BezierCurveEase.prototype.easeInCore = function (gradient) {
  38000. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  38001. };
  38002. return BezierCurveEase;
  38003. }(EasingFunction));
  38004. BABYLON.BezierCurveEase = BezierCurveEase;
  38005. })(BABYLON || (BABYLON = {}));
  38006. //# sourceMappingURL=babylon.easing.js.map
  38007. var BABYLON;
  38008. (function (BABYLON) {
  38009. var Condition = (function () {
  38010. function Condition(actionManager) {
  38011. this._actionManager = actionManager;
  38012. }
  38013. Condition.prototype.isValid = function () {
  38014. return true;
  38015. };
  38016. Condition.prototype._getProperty = function (propertyPath) {
  38017. return this._actionManager._getProperty(propertyPath);
  38018. };
  38019. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  38020. return this._actionManager._getEffectiveTarget(target, propertyPath);
  38021. };
  38022. Condition.prototype.serialize = function () {
  38023. };
  38024. Condition.prototype._serialize = function (serializedCondition) {
  38025. return {
  38026. type: 2,
  38027. children: [],
  38028. name: serializedCondition.name,
  38029. properties: serializedCondition.properties
  38030. };
  38031. };
  38032. return Condition;
  38033. }());
  38034. BABYLON.Condition = Condition;
  38035. var ValueCondition = (function (_super) {
  38036. __extends(ValueCondition, _super);
  38037. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  38038. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  38039. var _this = _super.call(this, actionManager) || this;
  38040. _this.propertyPath = propertyPath;
  38041. _this.value = value;
  38042. _this.operator = operator;
  38043. _this._target = target;
  38044. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  38045. _this._property = _this._getProperty(_this.propertyPath);
  38046. return _this;
  38047. }
  38048. Object.defineProperty(ValueCondition, "IsEqual", {
  38049. get: function () {
  38050. return ValueCondition._IsEqual;
  38051. },
  38052. enumerable: true,
  38053. configurable: true
  38054. });
  38055. Object.defineProperty(ValueCondition, "IsDifferent", {
  38056. get: function () {
  38057. return ValueCondition._IsDifferent;
  38058. },
  38059. enumerable: true,
  38060. configurable: true
  38061. });
  38062. Object.defineProperty(ValueCondition, "IsGreater", {
  38063. get: function () {
  38064. return ValueCondition._IsGreater;
  38065. },
  38066. enumerable: true,
  38067. configurable: true
  38068. });
  38069. Object.defineProperty(ValueCondition, "IsLesser", {
  38070. get: function () {
  38071. return ValueCondition._IsLesser;
  38072. },
  38073. enumerable: true,
  38074. configurable: true
  38075. });
  38076. // Methods
  38077. ValueCondition.prototype.isValid = function () {
  38078. switch (this.operator) {
  38079. case ValueCondition.IsGreater:
  38080. return this._effectiveTarget[this._property] > this.value;
  38081. case ValueCondition.IsLesser:
  38082. return this._effectiveTarget[this._property] < this.value;
  38083. case ValueCondition.IsEqual:
  38084. case ValueCondition.IsDifferent:
  38085. var check;
  38086. if (this.value.equals) {
  38087. check = this.value.equals(this._effectiveTarget[this._property]);
  38088. }
  38089. else {
  38090. check = this.value === this._effectiveTarget[this._property];
  38091. }
  38092. return this.operator === ValueCondition.IsEqual ? check : !check;
  38093. }
  38094. return false;
  38095. };
  38096. ValueCondition.prototype.serialize = function () {
  38097. return this._serialize({
  38098. name: "ValueCondition",
  38099. properties: [
  38100. BABYLON.Action._GetTargetProperty(this._target),
  38101. { name: "propertyPath", value: this.propertyPath },
  38102. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  38103. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  38104. ]
  38105. });
  38106. };
  38107. ValueCondition.GetOperatorName = function (operator) {
  38108. switch (operator) {
  38109. case ValueCondition._IsEqual: return "IsEqual";
  38110. case ValueCondition._IsDifferent: return "IsDifferent";
  38111. case ValueCondition._IsGreater: return "IsGreater";
  38112. case ValueCondition._IsLesser: return "IsLesser";
  38113. default: return "";
  38114. }
  38115. };
  38116. // Statics
  38117. ValueCondition._IsEqual = 0;
  38118. ValueCondition._IsDifferent = 1;
  38119. ValueCondition._IsGreater = 2;
  38120. ValueCondition._IsLesser = 3;
  38121. return ValueCondition;
  38122. }(Condition));
  38123. BABYLON.ValueCondition = ValueCondition;
  38124. var PredicateCondition = (function (_super) {
  38125. __extends(PredicateCondition, _super);
  38126. function PredicateCondition(actionManager, predicate) {
  38127. var _this = _super.call(this, actionManager) || this;
  38128. _this.predicate = predicate;
  38129. return _this;
  38130. }
  38131. PredicateCondition.prototype.isValid = function () {
  38132. return this.predicate();
  38133. };
  38134. return PredicateCondition;
  38135. }(Condition));
  38136. BABYLON.PredicateCondition = PredicateCondition;
  38137. var StateCondition = (function (_super) {
  38138. __extends(StateCondition, _super);
  38139. function StateCondition(actionManager, target, value) {
  38140. var _this = _super.call(this, actionManager) || this;
  38141. _this.value = value;
  38142. _this._target = target;
  38143. return _this;
  38144. }
  38145. // Methods
  38146. StateCondition.prototype.isValid = function () {
  38147. return this._target.state === this.value;
  38148. };
  38149. StateCondition.prototype.serialize = function () {
  38150. return this._serialize({
  38151. name: "StateCondition",
  38152. properties: [
  38153. BABYLON.Action._GetTargetProperty(this._target),
  38154. { name: "value", value: this.value }
  38155. ]
  38156. });
  38157. };
  38158. return StateCondition;
  38159. }(Condition));
  38160. BABYLON.StateCondition = StateCondition;
  38161. })(BABYLON || (BABYLON = {}));
  38162. //# sourceMappingURL=babylon.condition.js.map
  38163. var BABYLON;
  38164. (function (BABYLON) {
  38165. var Action = (function () {
  38166. function Action(triggerOptions, condition) {
  38167. this.triggerOptions = triggerOptions;
  38168. if (triggerOptions.parameter) {
  38169. this.trigger = triggerOptions.trigger;
  38170. this._triggerParameter = triggerOptions.parameter;
  38171. }
  38172. else {
  38173. this.trigger = triggerOptions;
  38174. }
  38175. this._nextActiveAction = this;
  38176. this._condition = condition;
  38177. }
  38178. // Methods
  38179. Action.prototype._prepare = function () {
  38180. };
  38181. Action.prototype.getTriggerParameter = function () {
  38182. return this._triggerParameter;
  38183. };
  38184. Action.prototype._executeCurrent = function (evt) {
  38185. if (this._nextActiveAction._condition) {
  38186. var condition = this._nextActiveAction._condition;
  38187. var currentRenderId = this._actionManager.getScene().getRenderId();
  38188. // We cache the current evaluation for the current frame
  38189. if (condition._evaluationId === currentRenderId) {
  38190. if (!condition._currentResult) {
  38191. return;
  38192. }
  38193. }
  38194. else {
  38195. condition._evaluationId = currentRenderId;
  38196. if (!condition.isValid()) {
  38197. condition._currentResult = false;
  38198. return;
  38199. }
  38200. condition._currentResult = true;
  38201. }
  38202. }
  38203. this._nextActiveAction.execute(evt);
  38204. this.skipToNextActiveAction();
  38205. };
  38206. Action.prototype.execute = function (evt) {
  38207. };
  38208. Action.prototype.skipToNextActiveAction = function () {
  38209. if (this._nextActiveAction._child) {
  38210. if (!this._nextActiveAction._child._actionManager) {
  38211. this._nextActiveAction._child._actionManager = this._actionManager;
  38212. }
  38213. this._nextActiveAction = this._nextActiveAction._child;
  38214. }
  38215. else {
  38216. this._nextActiveAction = this;
  38217. }
  38218. };
  38219. Action.prototype.then = function (action) {
  38220. this._child = action;
  38221. action._actionManager = this._actionManager;
  38222. action._prepare();
  38223. return action;
  38224. };
  38225. Action.prototype._getProperty = function (propertyPath) {
  38226. return this._actionManager._getProperty(propertyPath);
  38227. };
  38228. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  38229. return this._actionManager._getEffectiveTarget(target, propertyPath);
  38230. };
  38231. Action.prototype.serialize = function (parent) {
  38232. };
  38233. // Called by BABYLON.Action objects in serialize(...). Internal use
  38234. Action.prototype._serialize = function (serializedAction, parent) {
  38235. var serializationObject = {
  38236. type: 1,
  38237. children: [],
  38238. name: serializedAction.name,
  38239. properties: serializedAction.properties || []
  38240. };
  38241. // Serialize child
  38242. if (this._child) {
  38243. this._child.serialize(serializationObject);
  38244. }
  38245. // Check if "this" has a condition
  38246. if (this._condition) {
  38247. var serializedCondition = this._condition.serialize();
  38248. serializedCondition.children.push(serializationObject);
  38249. if (parent) {
  38250. parent.children.push(serializedCondition);
  38251. }
  38252. return serializedCondition;
  38253. }
  38254. if (parent) {
  38255. parent.children.push(serializationObject);
  38256. }
  38257. return serializationObject;
  38258. };
  38259. Action._SerializeValueAsString = function (value) {
  38260. if (typeof value === "number") {
  38261. return value.toString();
  38262. }
  38263. if (typeof value === "boolean") {
  38264. return value ? "true" : "false";
  38265. }
  38266. if (value instanceof BABYLON.Vector2) {
  38267. return value.x + ", " + value.y;
  38268. }
  38269. if (value instanceof BABYLON.Vector3) {
  38270. return value.x + ", " + value.y + ", " + value.z;
  38271. }
  38272. if (value instanceof BABYLON.Color3) {
  38273. return value.r + ", " + value.g + ", " + value.b;
  38274. }
  38275. if (value instanceof BABYLON.Color4) {
  38276. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  38277. }
  38278. return value; // string
  38279. };
  38280. Action._GetTargetProperty = function (target) {
  38281. return {
  38282. name: "target",
  38283. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  38284. : target instanceof BABYLON.Light ? "LightProperties"
  38285. : target instanceof BABYLON.Camera ? "CameraProperties"
  38286. : "SceneProperties",
  38287. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  38288. };
  38289. };
  38290. return Action;
  38291. }());
  38292. BABYLON.Action = Action;
  38293. })(BABYLON || (BABYLON = {}));
  38294. //# sourceMappingURL=babylon.action.js.map
  38295. var BABYLON;
  38296. (function (BABYLON) {
  38297. /**
  38298. * ActionEvent is the event beint sent when an action is triggered.
  38299. */
  38300. var ActionEvent = (function () {
  38301. /**
  38302. * @param source The mesh or sprite that triggered the action.
  38303. * @param pointerX The X mouse cursor position at the time of the event
  38304. * @param pointerY The Y mouse cursor position at the time of the event
  38305. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  38306. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  38307. */
  38308. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  38309. this.source = source;
  38310. this.pointerX = pointerX;
  38311. this.pointerY = pointerY;
  38312. this.meshUnderPointer = meshUnderPointer;
  38313. this.sourceEvent = sourceEvent;
  38314. this.additionalData = additionalData;
  38315. }
  38316. /**
  38317. * Helper function to auto-create an ActionEvent from a source mesh.
  38318. * @param source The source mesh that triggered the event
  38319. * @param evt {Event} The original (browser) event
  38320. */
  38321. ActionEvent.CreateNew = function (source, evt, additionalData) {
  38322. var scene = source.getScene();
  38323. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  38324. };
  38325. /**
  38326. * Helper function to auto-create an ActionEvent from a source mesh.
  38327. * @param source The source sprite that triggered the event
  38328. * @param scene Scene associated with the sprite
  38329. * @param evt {Event} The original (browser) event
  38330. */
  38331. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  38332. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  38333. };
  38334. /**
  38335. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  38336. * @param scene the scene where the event occurred
  38337. * @param evt {Event} The original (browser) event
  38338. */
  38339. ActionEvent.CreateNewFromScene = function (scene, evt) {
  38340. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  38341. };
  38342. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  38343. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  38344. };
  38345. return ActionEvent;
  38346. }());
  38347. BABYLON.ActionEvent = ActionEvent;
  38348. /**
  38349. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  38350. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  38351. */
  38352. var ActionManager = (function () {
  38353. function ActionManager(scene) {
  38354. // Members
  38355. this.actions = new Array();
  38356. this.hoverCursor = '';
  38357. this._scene = scene;
  38358. scene._actionManagers.push(this);
  38359. }
  38360. Object.defineProperty(ActionManager, "NothingTrigger", {
  38361. get: function () {
  38362. return ActionManager._NothingTrigger;
  38363. },
  38364. enumerable: true,
  38365. configurable: true
  38366. });
  38367. Object.defineProperty(ActionManager, "OnPickTrigger", {
  38368. get: function () {
  38369. return ActionManager._OnPickTrigger;
  38370. },
  38371. enumerable: true,
  38372. configurable: true
  38373. });
  38374. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  38375. get: function () {
  38376. return ActionManager._OnLeftPickTrigger;
  38377. },
  38378. enumerable: true,
  38379. configurable: true
  38380. });
  38381. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  38382. get: function () {
  38383. return ActionManager._OnRightPickTrigger;
  38384. },
  38385. enumerable: true,
  38386. configurable: true
  38387. });
  38388. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  38389. get: function () {
  38390. return ActionManager._OnCenterPickTrigger;
  38391. },
  38392. enumerable: true,
  38393. configurable: true
  38394. });
  38395. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  38396. get: function () {
  38397. return ActionManager._OnPickDownTrigger;
  38398. },
  38399. enumerable: true,
  38400. configurable: true
  38401. });
  38402. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  38403. get: function () {
  38404. return ActionManager._OnDoublePickTrigger;
  38405. },
  38406. enumerable: true,
  38407. configurable: true
  38408. });
  38409. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  38410. get: function () {
  38411. return ActionManager._OnPickUpTrigger;
  38412. },
  38413. enumerable: true,
  38414. configurable: true
  38415. });
  38416. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  38417. /// This trigger will only be raised if you also declared a OnPickDown
  38418. get: function () {
  38419. return ActionManager._OnPickOutTrigger;
  38420. },
  38421. enumerable: true,
  38422. configurable: true
  38423. });
  38424. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  38425. get: function () {
  38426. return ActionManager._OnLongPressTrigger;
  38427. },
  38428. enumerable: true,
  38429. configurable: true
  38430. });
  38431. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  38432. get: function () {
  38433. return ActionManager._OnPointerOverTrigger;
  38434. },
  38435. enumerable: true,
  38436. configurable: true
  38437. });
  38438. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  38439. get: function () {
  38440. return ActionManager._OnPointerOutTrigger;
  38441. },
  38442. enumerable: true,
  38443. configurable: true
  38444. });
  38445. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  38446. get: function () {
  38447. return ActionManager._OnEveryFrameTrigger;
  38448. },
  38449. enumerable: true,
  38450. configurable: true
  38451. });
  38452. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  38453. get: function () {
  38454. return ActionManager._OnIntersectionEnterTrigger;
  38455. },
  38456. enumerable: true,
  38457. configurable: true
  38458. });
  38459. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  38460. get: function () {
  38461. return ActionManager._OnIntersectionExitTrigger;
  38462. },
  38463. enumerable: true,
  38464. configurable: true
  38465. });
  38466. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  38467. get: function () {
  38468. return ActionManager._OnKeyDownTrigger;
  38469. },
  38470. enumerable: true,
  38471. configurable: true
  38472. });
  38473. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  38474. get: function () {
  38475. return ActionManager._OnKeyUpTrigger;
  38476. },
  38477. enumerable: true,
  38478. configurable: true
  38479. });
  38480. // Methods
  38481. ActionManager.prototype.dispose = function () {
  38482. var index = this._scene._actionManagers.indexOf(this);
  38483. for (var i = 0; i < this.actions.length; i++) {
  38484. var action = this.actions[i];
  38485. ActionManager.Triggers[action.trigger]--;
  38486. if (ActionManager.Triggers[action.trigger] === 0) {
  38487. delete ActionManager.Triggers[action.trigger];
  38488. }
  38489. }
  38490. if (index > -1) {
  38491. this._scene._actionManagers.splice(index, 1);
  38492. }
  38493. };
  38494. ActionManager.prototype.getScene = function () {
  38495. return this._scene;
  38496. };
  38497. /**
  38498. * Does this action manager handles actions of any of the given triggers
  38499. * @param {number[]} triggers - the triggers to be tested
  38500. * @return {boolean} whether one (or more) of the triggers is handeled
  38501. */
  38502. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  38503. for (var index = 0; index < this.actions.length; index++) {
  38504. var action = this.actions[index];
  38505. if (triggers.indexOf(action.trigger) > -1) {
  38506. return true;
  38507. }
  38508. }
  38509. return false;
  38510. };
  38511. /**
  38512. * Does this action manager handles actions of a given trigger
  38513. * @param {number} trigger - the trigger to be tested
  38514. * @return {boolean} whether the trigger is handeled
  38515. */
  38516. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  38517. for (var index = 0; index < this.actions.length; index++) {
  38518. var action = this.actions[index];
  38519. if (action.trigger === trigger) {
  38520. return true;
  38521. }
  38522. }
  38523. return false;
  38524. };
  38525. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  38526. /**
  38527. * Does this action manager has pointer triggers
  38528. * @return {boolean} whether or not it has pointer triggers
  38529. */
  38530. get: function () {
  38531. for (var index = 0; index < this.actions.length; index++) {
  38532. var action = this.actions[index];
  38533. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  38534. return true;
  38535. }
  38536. }
  38537. return false;
  38538. },
  38539. enumerable: true,
  38540. configurable: true
  38541. });
  38542. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  38543. /**
  38544. * Does this action manager has pick triggers
  38545. * @return {boolean} whether or not it has pick triggers
  38546. */
  38547. get: function () {
  38548. for (var index = 0; index < this.actions.length; index++) {
  38549. var action = this.actions[index];
  38550. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  38551. return true;
  38552. }
  38553. }
  38554. return false;
  38555. },
  38556. enumerable: true,
  38557. configurable: true
  38558. });
  38559. Object.defineProperty(ActionManager, "HasTriggers", {
  38560. /**
  38561. * Does exist one action manager with at least one trigger
  38562. * @return {boolean} whether or not it exists one action manager with one trigger
  38563. **/
  38564. get: function () {
  38565. for (var t in ActionManager.Triggers) {
  38566. if (ActionManager.Triggers.hasOwnProperty(t)) {
  38567. return true;
  38568. }
  38569. }
  38570. return false;
  38571. },
  38572. enumerable: true,
  38573. configurable: true
  38574. });
  38575. Object.defineProperty(ActionManager, "HasPickTriggers", {
  38576. /**
  38577. * Does exist one action manager with at least one pick trigger
  38578. * @return {boolean} whether or not it exists one action manager with one pick trigger
  38579. **/
  38580. get: function () {
  38581. for (var t in ActionManager.Triggers) {
  38582. if (ActionManager.Triggers.hasOwnProperty(t)) {
  38583. var t_int = parseInt(t);
  38584. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  38585. return true;
  38586. }
  38587. }
  38588. }
  38589. return false;
  38590. },
  38591. enumerable: true,
  38592. configurable: true
  38593. });
  38594. /**
  38595. * Does exist one action manager that handles actions of a given trigger
  38596. * @param {number} trigger - the trigger to be tested
  38597. * @return {boolean} whether the trigger is handeled by at least one action manager
  38598. **/
  38599. ActionManager.HasSpecificTrigger = function (trigger) {
  38600. for (var t in ActionManager.Triggers) {
  38601. if (ActionManager.Triggers.hasOwnProperty(t)) {
  38602. var t_int = parseInt(t);
  38603. if (t_int === trigger) {
  38604. return true;
  38605. }
  38606. }
  38607. }
  38608. return false;
  38609. };
  38610. /**
  38611. * Registers an action to this action manager
  38612. * @param {BABYLON.Action} action - the action to be registered
  38613. * @return {BABYLON.Action} the action amended (prepared) after registration
  38614. */
  38615. ActionManager.prototype.registerAction = function (action) {
  38616. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  38617. if (this.getScene().actionManager !== this) {
  38618. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  38619. return null;
  38620. }
  38621. }
  38622. this.actions.push(action);
  38623. if (ActionManager.Triggers[action.trigger]) {
  38624. ActionManager.Triggers[action.trigger]++;
  38625. }
  38626. else {
  38627. ActionManager.Triggers[action.trigger] = 1;
  38628. }
  38629. action._actionManager = this;
  38630. action._prepare();
  38631. return action;
  38632. };
  38633. /**
  38634. * Process a specific trigger
  38635. * @param {number} trigger - the trigger to process
  38636. * @param evt {BABYLON.ActionEvent} the event details to be processed
  38637. */
  38638. ActionManager.prototype.processTrigger = function (trigger, evt) {
  38639. for (var index = 0; index < this.actions.length; index++) {
  38640. var action = this.actions[index];
  38641. if (action.trigger === trigger) {
  38642. if (trigger === ActionManager.OnKeyUpTrigger
  38643. || trigger === ActionManager.OnKeyDownTrigger) {
  38644. var parameter = action.getTriggerParameter();
  38645. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  38646. if (!parameter.toLowerCase) {
  38647. continue;
  38648. }
  38649. var lowerCase = parameter.toLowerCase();
  38650. if (lowerCase !== evt.sourceEvent.key) {
  38651. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  38652. var actualkey = String.fromCharCode(unicode).toLowerCase();
  38653. if (actualkey !== lowerCase) {
  38654. continue;
  38655. }
  38656. }
  38657. }
  38658. }
  38659. action._executeCurrent(evt);
  38660. }
  38661. }
  38662. };
  38663. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  38664. var properties = propertyPath.split(".");
  38665. for (var index = 0; index < properties.length - 1; index++) {
  38666. target = target[properties[index]];
  38667. }
  38668. return target;
  38669. };
  38670. ActionManager.prototype._getProperty = function (propertyPath) {
  38671. var properties = propertyPath.split(".");
  38672. return properties[properties.length - 1];
  38673. };
  38674. ActionManager.prototype.serialize = function (name) {
  38675. var root = {
  38676. children: [],
  38677. name: name,
  38678. type: 3,
  38679. properties: [] // Empty for root but required
  38680. };
  38681. for (var i = 0; i < this.actions.length; i++) {
  38682. var triggerObject = {
  38683. type: 0,
  38684. children: [],
  38685. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  38686. properties: []
  38687. };
  38688. var triggerOptions = this.actions[i].triggerOptions;
  38689. if (triggerOptions && typeof triggerOptions !== "number") {
  38690. if (triggerOptions.parameter instanceof BABYLON.Node) {
  38691. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  38692. }
  38693. else {
  38694. var parameter = {};
  38695. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  38696. if (triggerOptions.parameter.mesh) {
  38697. parameter._meshId = triggerOptions.parameter.mesh.id;
  38698. }
  38699. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  38700. }
  38701. }
  38702. // Serialize child action, recursively
  38703. this.actions[i].serialize(triggerObject);
  38704. // Add serialized trigger
  38705. root.children.push(triggerObject);
  38706. }
  38707. return root;
  38708. };
  38709. ActionManager.Parse = function (parsedActions, object, scene) {
  38710. var actionManager = new BABYLON.ActionManager(scene);
  38711. if (object === null)
  38712. scene.actionManager = actionManager;
  38713. else
  38714. object.actionManager = actionManager;
  38715. // instanciate a new object
  38716. var instanciate = function (name, params) {
  38717. var newInstance = Object.create(BABYLON[name].prototype);
  38718. newInstance.constructor.apply(newInstance, params);
  38719. return newInstance;
  38720. };
  38721. var parseParameter = function (name, value, target, propertyPath) {
  38722. if (propertyPath === null) {
  38723. // String, boolean or float
  38724. var floatValue = parseFloat(value);
  38725. if (value === "true" || value === "false")
  38726. return value === "true";
  38727. else
  38728. return isNaN(floatValue) ? value : floatValue;
  38729. }
  38730. var effectiveTarget = propertyPath.split(".");
  38731. var values = value.split(",");
  38732. // Get effective Target
  38733. for (var i = 0; i < effectiveTarget.length; i++) {
  38734. target = target[effectiveTarget[i]];
  38735. }
  38736. // Return appropriate value with its type
  38737. if (typeof (target) === "boolean")
  38738. return values[0] === "true";
  38739. if (typeof (target) === "string")
  38740. return values[0];
  38741. // Parameters with multiple values such as Vector3 etc.
  38742. var split = new Array();
  38743. for (var i = 0; i < values.length; i++)
  38744. split.push(parseFloat(values[i]));
  38745. if (target instanceof BABYLON.Vector3)
  38746. return BABYLON.Vector3.FromArray(split);
  38747. if (target instanceof BABYLON.Vector4)
  38748. return BABYLON.Vector4.FromArray(split);
  38749. if (target instanceof BABYLON.Color3)
  38750. return BABYLON.Color3.FromArray(split);
  38751. if (target instanceof BABYLON.Color4)
  38752. return BABYLON.Color4.FromArray(split);
  38753. return parseFloat(values[0]);
  38754. };
  38755. // traverse graph per trigger
  38756. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  38757. if (combineArray === void 0) { combineArray = null; }
  38758. if (parsedAction.detached)
  38759. return;
  38760. var parameters = new Array();
  38761. var target = null;
  38762. var propertyPath = null;
  38763. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  38764. // Parameters
  38765. if (parsedAction.type === 2)
  38766. parameters.push(actionManager);
  38767. else
  38768. parameters.push(trigger);
  38769. if (combine) {
  38770. var actions = new Array();
  38771. for (var j = 0; j < parsedAction.combine.length; j++) {
  38772. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  38773. }
  38774. parameters.push(actions);
  38775. }
  38776. else {
  38777. for (var i = 0; i < parsedAction.properties.length; i++) {
  38778. var value = parsedAction.properties[i].value;
  38779. var name = parsedAction.properties[i].name;
  38780. var targetType = parsedAction.properties[i].targetType;
  38781. if (name === "target")
  38782. if (targetType !== null && targetType === "SceneProperties")
  38783. value = target = scene;
  38784. else
  38785. value = target = scene.getNodeByName(value);
  38786. else if (name === "parent")
  38787. value = scene.getNodeByName(value);
  38788. else if (name === "sound")
  38789. value = scene.getSoundByName(value);
  38790. else if (name !== "propertyPath") {
  38791. if (parsedAction.type === 2 && name === "operator")
  38792. value = BABYLON.ValueCondition[value];
  38793. else
  38794. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  38795. }
  38796. else {
  38797. propertyPath = value;
  38798. }
  38799. parameters.push(value);
  38800. }
  38801. }
  38802. if (combineArray === null) {
  38803. parameters.push(condition);
  38804. }
  38805. else {
  38806. parameters.push(null);
  38807. }
  38808. // If interpolate value action
  38809. if (parsedAction.name === "InterpolateValueAction") {
  38810. var param = parameters[parameters.length - 2];
  38811. parameters[parameters.length - 1] = param;
  38812. parameters[parameters.length - 2] = condition;
  38813. }
  38814. // Action or condition(s) and not CombineAction
  38815. var newAction = instanciate(parsedAction.name, parameters);
  38816. if (newAction instanceof BABYLON.Condition && condition !== null) {
  38817. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  38818. if (action)
  38819. action.then(nothing);
  38820. else
  38821. actionManager.registerAction(nothing);
  38822. action = nothing;
  38823. }
  38824. if (combineArray === null) {
  38825. if (newAction instanceof BABYLON.Condition) {
  38826. condition = newAction;
  38827. newAction = action;
  38828. }
  38829. else {
  38830. condition = null;
  38831. if (action)
  38832. action.then(newAction);
  38833. else
  38834. actionManager.registerAction(newAction);
  38835. }
  38836. }
  38837. else {
  38838. combineArray.push(newAction);
  38839. }
  38840. for (var i = 0; i < parsedAction.children.length; i++)
  38841. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  38842. };
  38843. // triggers
  38844. for (var i = 0; i < parsedActions.children.length; i++) {
  38845. var triggerParams;
  38846. var trigger = parsedActions.children[i];
  38847. if (trigger.properties.length > 0) {
  38848. var param = trigger.properties[0].value;
  38849. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  38850. if (value._meshId) {
  38851. value.mesh = scene.getMeshByID(value._meshId);
  38852. }
  38853. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  38854. }
  38855. else
  38856. triggerParams = BABYLON.ActionManager[trigger.name];
  38857. for (var j = 0; j < trigger.children.length; j++) {
  38858. if (!trigger.detached)
  38859. traverse(trigger.children[j], triggerParams, null, null);
  38860. }
  38861. }
  38862. };
  38863. ActionManager.GetTriggerName = function (trigger) {
  38864. switch (trigger) {
  38865. case 0: return "NothingTrigger";
  38866. case 1: return "OnPickTrigger";
  38867. case 2: return "OnLeftPickTrigger";
  38868. case 3: return "OnRightPickTrigger";
  38869. case 4: return "OnCenterPickTrigger";
  38870. case 5: return "OnPickDownTrigger";
  38871. case 6: return "OnPickUpTrigger";
  38872. case 7: return "OnLongPressTrigger";
  38873. case 8: return "OnPointerOverTrigger";
  38874. case 9: return "OnPointerOutTrigger";
  38875. case 10: return "OnEveryFrameTrigger";
  38876. case 11: return "OnIntersectionEnterTrigger";
  38877. case 12: return "OnIntersectionExitTrigger";
  38878. case 13: return "OnKeyDownTrigger";
  38879. case 14: return "OnKeyUpTrigger";
  38880. case 15: return "OnPickOutTrigger";
  38881. default: return "";
  38882. }
  38883. };
  38884. // Statics
  38885. ActionManager._NothingTrigger = 0;
  38886. ActionManager._OnPickTrigger = 1;
  38887. ActionManager._OnLeftPickTrigger = 2;
  38888. ActionManager._OnRightPickTrigger = 3;
  38889. ActionManager._OnCenterPickTrigger = 4;
  38890. ActionManager._OnPickDownTrigger = 5;
  38891. ActionManager._OnDoublePickTrigger = 6;
  38892. ActionManager._OnPickUpTrigger = 7;
  38893. ActionManager._OnLongPressTrigger = 8;
  38894. ActionManager._OnPointerOverTrigger = 9;
  38895. ActionManager._OnPointerOutTrigger = 10;
  38896. ActionManager._OnEveryFrameTrigger = 11;
  38897. ActionManager._OnIntersectionEnterTrigger = 12;
  38898. ActionManager._OnIntersectionExitTrigger = 13;
  38899. ActionManager._OnKeyDownTrigger = 14;
  38900. ActionManager._OnKeyUpTrigger = 15;
  38901. ActionManager._OnPickOutTrigger = 16;
  38902. ActionManager.Triggers = {};
  38903. return ActionManager;
  38904. }());
  38905. BABYLON.ActionManager = ActionManager;
  38906. })(BABYLON || (BABYLON = {}));
  38907. //# sourceMappingURL=babylon.actionManager.js.map
  38908. var BABYLON;
  38909. (function (BABYLON) {
  38910. var InterpolateValueAction = (function (_super) {
  38911. __extends(InterpolateValueAction, _super);
  38912. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  38913. if (duration === void 0) { duration = 1000; }
  38914. var _this = _super.call(this, triggerOptions, condition) || this;
  38915. _this.propertyPath = propertyPath;
  38916. _this.value = value;
  38917. _this.duration = duration;
  38918. _this.stopOtherAnimations = stopOtherAnimations;
  38919. _this.onInterpolationDone = onInterpolationDone;
  38920. _this._target = _this._effectiveTarget = target;
  38921. return _this;
  38922. }
  38923. InterpolateValueAction.prototype._prepare = function () {
  38924. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  38925. this._property = this._getProperty(this.propertyPath);
  38926. };
  38927. InterpolateValueAction.prototype.execute = function () {
  38928. var scene = this._actionManager.getScene();
  38929. var keys = [
  38930. {
  38931. frame: 0,
  38932. value: this._effectiveTarget[this._property]
  38933. }, {
  38934. frame: 100,
  38935. value: this.value
  38936. }
  38937. ];
  38938. var dataType;
  38939. if (typeof this.value === "number") {
  38940. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  38941. }
  38942. else if (this.value instanceof BABYLON.Color3) {
  38943. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  38944. }
  38945. else if (this.value instanceof BABYLON.Vector3) {
  38946. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  38947. }
  38948. else if (this.value instanceof BABYLON.Matrix) {
  38949. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  38950. }
  38951. else if (this.value instanceof BABYLON.Quaternion) {
  38952. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  38953. }
  38954. else {
  38955. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  38956. return;
  38957. }
  38958. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  38959. animation.setKeys(keys);
  38960. if (this.stopOtherAnimations) {
  38961. scene.stopAnimation(this._effectiveTarget);
  38962. }
  38963. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  38964. };
  38965. InterpolateValueAction.prototype.serialize = function (parent) {
  38966. return _super.prototype._serialize.call(this, {
  38967. name: "InterpolateValueAction",
  38968. properties: [
  38969. BABYLON.Action._GetTargetProperty(this._target),
  38970. { name: "propertyPath", value: this.propertyPath },
  38971. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  38972. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  38973. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  38974. ]
  38975. }, parent);
  38976. };
  38977. return InterpolateValueAction;
  38978. }(BABYLON.Action));
  38979. BABYLON.InterpolateValueAction = InterpolateValueAction;
  38980. })(BABYLON || (BABYLON = {}));
  38981. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  38982. var BABYLON;
  38983. (function (BABYLON) {
  38984. var SwitchBooleanAction = (function (_super) {
  38985. __extends(SwitchBooleanAction, _super);
  38986. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  38987. var _this = _super.call(this, triggerOptions, condition) || this;
  38988. _this.propertyPath = propertyPath;
  38989. _this._target = _this._effectiveTarget = target;
  38990. return _this;
  38991. }
  38992. SwitchBooleanAction.prototype._prepare = function () {
  38993. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  38994. this._property = this._getProperty(this.propertyPath);
  38995. };
  38996. SwitchBooleanAction.prototype.execute = function () {
  38997. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  38998. };
  38999. SwitchBooleanAction.prototype.serialize = function (parent) {
  39000. return _super.prototype._serialize.call(this, {
  39001. name: "SwitchBooleanAction",
  39002. properties: [
  39003. BABYLON.Action._GetTargetProperty(this._target),
  39004. { name: "propertyPath", value: this.propertyPath }
  39005. ]
  39006. }, parent);
  39007. };
  39008. return SwitchBooleanAction;
  39009. }(BABYLON.Action));
  39010. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  39011. var SetStateAction = (function (_super) {
  39012. __extends(SetStateAction, _super);
  39013. function SetStateAction(triggerOptions, target, value, condition) {
  39014. var _this = _super.call(this, triggerOptions, condition) || this;
  39015. _this.value = value;
  39016. _this._target = target;
  39017. return _this;
  39018. }
  39019. SetStateAction.prototype.execute = function () {
  39020. this._target.state = this.value;
  39021. };
  39022. SetStateAction.prototype.serialize = function (parent) {
  39023. return _super.prototype._serialize.call(this, {
  39024. name: "SetStateAction",
  39025. properties: [
  39026. BABYLON.Action._GetTargetProperty(this._target),
  39027. { name: "value", value: this.value }
  39028. ]
  39029. }, parent);
  39030. };
  39031. return SetStateAction;
  39032. }(BABYLON.Action));
  39033. BABYLON.SetStateAction = SetStateAction;
  39034. var SetValueAction = (function (_super) {
  39035. __extends(SetValueAction, _super);
  39036. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  39037. var _this = _super.call(this, triggerOptions, condition) || this;
  39038. _this.propertyPath = propertyPath;
  39039. _this.value = value;
  39040. _this._target = _this._effectiveTarget = target;
  39041. return _this;
  39042. }
  39043. SetValueAction.prototype._prepare = function () {
  39044. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39045. this._property = this._getProperty(this.propertyPath);
  39046. };
  39047. SetValueAction.prototype.execute = function () {
  39048. this._effectiveTarget[this._property] = this.value;
  39049. if (this._target.markAsDirty) {
  39050. this._target.markAsDirty(this._property);
  39051. }
  39052. };
  39053. SetValueAction.prototype.serialize = function (parent) {
  39054. return _super.prototype._serialize.call(this, {
  39055. name: "SetValueAction",
  39056. properties: [
  39057. BABYLON.Action._GetTargetProperty(this._target),
  39058. { name: "propertyPath", value: this.propertyPath },
  39059. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  39060. ]
  39061. }, parent);
  39062. };
  39063. return SetValueAction;
  39064. }(BABYLON.Action));
  39065. BABYLON.SetValueAction = SetValueAction;
  39066. var IncrementValueAction = (function (_super) {
  39067. __extends(IncrementValueAction, _super);
  39068. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  39069. var _this = _super.call(this, triggerOptions, condition) || this;
  39070. _this.propertyPath = propertyPath;
  39071. _this.value = value;
  39072. _this._target = _this._effectiveTarget = target;
  39073. return _this;
  39074. }
  39075. IncrementValueAction.prototype._prepare = function () {
  39076. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  39077. this._property = this._getProperty(this.propertyPath);
  39078. if (typeof this._effectiveTarget[this._property] !== "number") {
  39079. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  39080. }
  39081. };
  39082. IncrementValueAction.prototype.execute = function () {
  39083. this._effectiveTarget[this._property] += this.value;
  39084. if (this._target.markAsDirty) {
  39085. this._target.markAsDirty(this._property);
  39086. }
  39087. };
  39088. IncrementValueAction.prototype.serialize = function (parent) {
  39089. return _super.prototype._serialize.call(this, {
  39090. name: "IncrementValueAction",
  39091. properties: [
  39092. BABYLON.Action._GetTargetProperty(this._target),
  39093. { name: "propertyPath", value: this.propertyPath },
  39094. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  39095. ]
  39096. }, parent);
  39097. };
  39098. return IncrementValueAction;
  39099. }(BABYLON.Action));
  39100. BABYLON.IncrementValueAction = IncrementValueAction;
  39101. var PlayAnimationAction = (function (_super) {
  39102. __extends(PlayAnimationAction, _super);
  39103. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  39104. var _this = _super.call(this, triggerOptions, condition) || this;
  39105. _this.from = from;
  39106. _this.to = to;
  39107. _this.loop = loop;
  39108. _this._target = target;
  39109. return _this;
  39110. }
  39111. PlayAnimationAction.prototype._prepare = function () {
  39112. };
  39113. PlayAnimationAction.prototype.execute = function () {
  39114. var scene = this._actionManager.getScene();
  39115. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  39116. };
  39117. PlayAnimationAction.prototype.serialize = function (parent) {
  39118. return _super.prototype._serialize.call(this, {
  39119. name: "PlayAnimationAction",
  39120. properties: [
  39121. BABYLON.Action._GetTargetProperty(this._target),
  39122. { name: "from", value: String(this.from) },
  39123. { name: "to", value: String(this.to) },
  39124. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  39125. ]
  39126. }, parent);
  39127. };
  39128. return PlayAnimationAction;
  39129. }(BABYLON.Action));
  39130. BABYLON.PlayAnimationAction = PlayAnimationAction;
  39131. var StopAnimationAction = (function (_super) {
  39132. __extends(StopAnimationAction, _super);
  39133. function StopAnimationAction(triggerOptions, target, condition) {
  39134. var _this = _super.call(this, triggerOptions, condition) || this;
  39135. _this._target = target;
  39136. return _this;
  39137. }
  39138. StopAnimationAction.prototype._prepare = function () {
  39139. };
  39140. StopAnimationAction.prototype.execute = function () {
  39141. var scene = this._actionManager.getScene();
  39142. scene.stopAnimation(this._target);
  39143. };
  39144. StopAnimationAction.prototype.serialize = function (parent) {
  39145. return _super.prototype._serialize.call(this, {
  39146. name: "StopAnimationAction",
  39147. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  39148. }, parent);
  39149. };
  39150. return StopAnimationAction;
  39151. }(BABYLON.Action));
  39152. BABYLON.StopAnimationAction = StopAnimationAction;
  39153. var DoNothingAction = (function (_super) {
  39154. __extends(DoNothingAction, _super);
  39155. function DoNothingAction(triggerOptions, condition) {
  39156. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  39157. return _super.call(this, triggerOptions, condition) || this;
  39158. }
  39159. DoNothingAction.prototype.execute = function () {
  39160. };
  39161. DoNothingAction.prototype.serialize = function (parent) {
  39162. return _super.prototype._serialize.call(this, {
  39163. name: "DoNothingAction",
  39164. properties: []
  39165. }, parent);
  39166. };
  39167. return DoNothingAction;
  39168. }(BABYLON.Action));
  39169. BABYLON.DoNothingAction = DoNothingAction;
  39170. var CombineAction = (function (_super) {
  39171. __extends(CombineAction, _super);
  39172. function CombineAction(triggerOptions, children, condition) {
  39173. var _this = _super.call(this, triggerOptions, condition) || this;
  39174. _this.children = children;
  39175. return _this;
  39176. }
  39177. CombineAction.prototype._prepare = function () {
  39178. for (var index = 0; index < this.children.length; index++) {
  39179. this.children[index]._actionManager = this._actionManager;
  39180. this.children[index]._prepare();
  39181. }
  39182. };
  39183. CombineAction.prototype.execute = function (evt) {
  39184. for (var index = 0; index < this.children.length; index++) {
  39185. this.children[index].execute(evt);
  39186. }
  39187. };
  39188. CombineAction.prototype.serialize = function (parent) {
  39189. var serializationObject = _super.prototype._serialize.call(this, {
  39190. name: "CombineAction",
  39191. properties: [],
  39192. combine: []
  39193. }, parent);
  39194. for (var i = 0; i < this.children.length; i++) {
  39195. serializationObject.combine.push(this.children[i].serialize(null));
  39196. }
  39197. return serializationObject;
  39198. };
  39199. return CombineAction;
  39200. }(BABYLON.Action));
  39201. BABYLON.CombineAction = CombineAction;
  39202. var ExecuteCodeAction = (function (_super) {
  39203. __extends(ExecuteCodeAction, _super);
  39204. function ExecuteCodeAction(triggerOptions, func, condition) {
  39205. var _this = _super.call(this, triggerOptions, condition) || this;
  39206. _this.func = func;
  39207. return _this;
  39208. }
  39209. ExecuteCodeAction.prototype.execute = function (evt) {
  39210. this.func(evt);
  39211. };
  39212. return ExecuteCodeAction;
  39213. }(BABYLON.Action));
  39214. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  39215. var SetParentAction = (function (_super) {
  39216. __extends(SetParentAction, _super);
  39217. function SetParentAction(triggerOptions, target, parent, condition) {
  39218. var _this = _super.call(this, triggerOptions, condition) || this;
  39219. _this._target = target;
  39220. _this._parent = parent;
  39221. return _this;
  39222. }
  39223. SetParentAction.prototype._prepare = function () {
  39224. };
  39225. SetParentAction.prototype.execute = function () {
  39226. if (this._target.parent === this._parent) {
  39227. return;
  39228. }
  39229. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  39230. invertParentWorldMatrix.invert();
  39231. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  39232. this._target.parent = this._parent;
  39233. };
  39234. SetParentAction.prototype.serialize = function (parent) {
  39235. return _super.prototype._serialize.call(this, {
  39236. name: "SetParentAction",
  39237. properties: [
  39238. BABYLON.Action._GetTargetProperty(this._target),
  39239. BABYLON.Action._GetTargetProperty(this._parent),
  39240. ]
  39241. }, parent);
  39242. };
  39243. return SetParentAction;
  39244. }(BABYLON.Action));
  39245. BABYLON.SetParentAction = SetParentAction;
  39246. var PlaySoundAction = (function (_super) {
  39247. __extends(PlaySoundAction, _super);
  39248. function PlaySoundAction(triggerOptions, sound, condition) {
  39249. var _this = _super.call(this, triggerOptions, condition) || this;
  39250. _this._sound = sound;
  39251. return _this;
  39252. }
  39253. PlaySoundAction.prototype._prepare = function () {
  39254. };
  39255. PlaySoundAction.prototype.execute = function () {
  39256. if (this._sound !== undefined)
  39257. this._sound.play();
  39258. };
  39259. PlaySoundAction.prototype.serialize = function (parent) {
  39260. return _super.prototype._serialize.call(this, {
  39261. name: "PlaySoundAction",
  39262. properties: [{ name: "sound", value: this._sound.name }]
  39263. }, parent);
  39264. };
  39265. return PlaySoundAction;
  39266. }(BABYLON.Action));
  39267. BABYLON.PlaySoundAction = PlaySoundAction;
  39268. var StopSoundAction = (function (_super) {
  39269. __extends(StopSoundAction, _super);
  39270. function StopSoundAction(triggerOptions, sound, condition) {
  39271. var _this = _super.call(this, triggerOptions, condition) || this;
  39272. _this._sound = sound;
  39273. return _this;
  39274. }
  39275. StopSoundAction.prototype._prepare = function () {
  39276. };
  39277. StopSoundAction.prototype.execute = function () {
  39278. if (this._sound !== undefined)
  39279. this._sound.stop();
  39280. };
  39281. StopSoundAction.prototype.serialize = function (parent) {
  39282. return _super.prototype._serialize.call(this, {
  39283. name: "StopSoundAction",
  39284. properties: [{ name: "sound", value: this._sound.name }]
  39285. }, parent);
  39286. };
  39287. return StopSoundAction;
  39288. }(BABYLON.Action));
  39289. BABYLON.StopSoundAction = StopSoundAction;
  39290. })(BABYLON || (BABYLON = {}));
  39291. //# sourceMappingURL=babylon.directActions.js.map
  39292. var BABYLON;
  39293. (function (BABYLON) {
  39294. var SpriteManager = (function () {
  39295. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  39296. if (epsilon === void 0) { epsilon = 0.01; }
  39297. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  39298. this.name = name;
  39299. this.sprites = new Array();
  39300. this.renderingGroupId = 0;
  39301. this.layerMask = 0x0FFFFFFF;
  39302. this.fogEnabled = true;
  39303. this.isPickable = false;
  39304. /**
  39305. * An event triggered when the manager is disposed.
  39306. * @type {BABYLON.Observable}
  39307. */
  39308. this.onDisposeObservable = new BABYLON.Observable();
  39309. this._vertexBuffers = {};
  39310. this._capacity = capacity;
  39311. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  39312. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39313. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39314. if (cellSize.width && cellSize.height) {
  39315. this.cellWidth = cellSize.width;
  39316. this.cellHeight = cellSize.height;
  39317. }
  39318. else if (cellSize !== undefined) {
  39319. this.cellWidth = cellSize;
  39320. this.cellHeight = cellSize;
  39321. }
  39322. else {
  39323. return;
  39324. }
  39325. this._epsilon = epsilon;
  39326. this._scene = scene;
  39327. this._scene.spriteManagers.push(this);
  39328. var indices = [];
  39329. var index = 0;
  39330. for (var count = 0; count < capacity; count++) {
  39331. indices.push(index);
  39332. indices.push(index + 1);
  39333. indices.push(index + 2);
  39334. indices.push(index);
  39335. indices.push(index + 2);
  39336. indices.push(index + 3);
  39337. index += 4;
  39338. }
  39339. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  39340. // VBO
  39341. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  39342. this._vertexData = new Float32Array(capacity * 16 * 4);
  39343. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  39344. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  39345. var options = this._buffer.createVertexBuffer("options", 4, 4);
  39346. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  39347. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  39348. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  39349. this._vertexBuffers["options"] = options;
  39350. this._vertexBuffers["cellInfo"] = cellInfo;
  39351. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  39352. // Effects
  39353. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  39354. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  39355. }
  39356. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  39357. set: function (callback) {
  39358. if (this._onDisposeObserver) {
  39359. this.onDisposeObservable.remove(this._onDisposeObserver);
  39360. }
  39361. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  39362. },
  39363. enumerable: true,
  39364. configurable: true
  39365. });
  39366. Object.defineProperty(SpriteManager.prototype, "texture", {
  39367. get: function () {
  39368. return this._spriteTexture;
  39369. },
  39370. set: function (value) {
  39371. this._spriteTexture = value;
  39372. },
  39373. enumerable: true,
  39374. configurable: true
  39375. });
  39376. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  39377. var arrayOffset = index * 16;
  39378. if (offsetX === 0)
  39379. offsetX = this._epsilon;
  39380. else if (offsetX === 1)
  39381. offsetX = 1 - this._epsilon;
  39382. if (offsetY === 0)
  39383. offsetY = this._epsilon;
  39384. else if (offsetY === 1)
  39385. offsetY = 1 - this._epsilon;
  39386. this._vertexData[arrayOffset] = sprite.position.x;
  39387. this._vertexData[arrayOffset + 1] = sprite.position.y;
  39388. this._vertexData[arrayOffset + 2] = sprite.position.z;
  39389. this._vertexData[arrayOffset + 3] = sprite.angle;
  39390. this._vertexData[arrayOffset + 4] = sprite.width;
  39391. this._vertexData[arrayOffset + 5] = sprite.height;
  39392. this._vertexData[arrayOffset + 6] = offsetX;
  39393. this._vertexData[arrayOffset + 7] = offsetY;
  39394. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  39395. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  39396. var offset = (sprite.cellIndex / rowSize) >> 0;
  39397. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  39398. this._vertexData[arrayOffset + 11] = offset;
  39399. // Color
  39400. this._vertexData[arrayOffset + 12] = sprite.color.r;
  39401. this._vertexData[arrayOffset + 13] = sprite.color.g;
  39402. this._vertexData[arrayOffset + 14] = sprite.color.b;
  39403. this._vertexData[arrayOffset + 15] = sprite.color.a;
  39404. };
  39405. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  39406. var count = Math.min(this._capacity, this.sprites.length);
  39407. var min = BABYLON.Vector3.Zero();
  39408. var max = BABYLON.Vector3.Zero();
  39409. var distance = Number.MAX_VALUE;
  39410. var currentSprite;
  39411. var cameraSpacePosition = BABYLON.Vector3.Zero();
  39412. var cameraView = camera.getViewMatrix();
  39413. for (var index = 0; index < count; index++) {
  39414. var sprite = this.sprites[index];
  39415. if (!sprite) {
  39416. continue;
  39417. }
  39418. if (predicate) {
  39419. if (!predicate(sprite)) {
  39420. continue;
  39421. }
  39422. }
  39423. else if (!sprite.isPickable) {
  39424. continue;
  39425. }
  39426. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  39427. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  39428. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  39429. if (ray.intersectsBoxMinMax(min, max)) {
  39430. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  39431. if (distance > currentDistance) {
  39432. distance = currentDistance;
  39433. currentSprite = sprite;
  39434. if (fastCheck) {
  39435. break;
  39436. }
  39437. }
  39438. }
  39439. }
  39440. if (currentSprite) {
  39441. var result = new BABYLON.PickingInfo();
  39442. result.hit = true;
  39443. result.pickedSprite = currentSprite;
  39444. result.distance = distance;
  39445. return result;
  39446. }
  39447. return null;
  39448. };
  39449. SpriteManager.prototype.render = function () {
  39450. // Check
  39451. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  39452. return;
  39453. var engine = this._scene.getEngine();
  39454. var baseSize = this._spriteTexture.getBaseSize();
  39455. // Sprites
  39456. var deltaTime = engine.getDeltaTime();
  39457. var max = Math.min(this._capacity, this.sprites.length);
  39458. var rowSize = baseSize.width / this.cellWidth;
  39459. var offset = 0;
  39460. for (var index = 0; index < max; index++) {
  39461. var sprite = this.sprites[index];
  39462. if (!sprite) {
  39463. continue;
  39464. }
  39465. sprite._animate(deltaTime);
  39466. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  39467. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  39468. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  39469. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  39470. }
  39471. this._buffer.update(this._vertexData);
  39472. // Render
  39473. var effect = this._effectBase;
  39474. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  39475. effect = this._effectFog;
  39476. }
  39477. engine.enableEffect(effect);
  39478. var viewMatrix = this._scene.getViewMatrix();
  39479. effect.setTexture("diffuseSampler", this._spriteTexture);
  39480. effect.setMatrix("view", viewMatrix);
  39481. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  39482. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  39483. // Fog
  39484. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  39485. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  39486. effect.setColor3("vFogColor", this._scene.fogColor);
  39487. }
  39488. // VBOs
  39489. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  39490. // Draw order
  39491. engine.setDepthFunctionToLessOrEqual();
  39492. effect.setBool("alphaTest", true);
  39493. engine.setColorWrite(false);
  39494. engine.draw(true, 0, max * 6);
  39495. engine.setColorWrite(true);
  39496. effect.setBool("alphaTest", false);
  39497. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  39498. engine.draw(true, 0, max * 6);
  39499. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  39500. };
  39501. SpriteManager.prototype.dispose = function () {
  39502. if (this._buffer) {
  39503. this._buffer.dispose();
  39504. this._buffer = null;
  39505. }
  39506. if (this._indexBuffer) {
  39507. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39508. this._indexBuffer = null;
  39509. }
  39510. if (this._spriteTexture) {
  39511. this._spriteTexture.dispose();
  39512. this._spriteTexture = null;
  39513. }
  39514. // Remove from scene
  39515. var index = this._scene.spriteManagers.indexOf(this);
  39516. this._scene.spriteManagers.splice(index, 1);
  39517. // Callback
  39518. this.onDisposeObservable.notifyObservers(this);
  39519. this.onDisposeObservable.clear();
  39520. };
  39521. return SpriteManager;
  39522. }());
  39523. BABYLON.SpriteManager = SpriteManager;
  39524. })(BABYLON || (BABYLON = {}));
  39525. //# sourceMappingURL=babylon.spriteManager.js.map
  39526. var BABYLON;
  39527. (function (BABYLON) {
  39528. var Sprite = (function () {
  39529. function Sprite(name, manager) {
  39530. this.name = name;
  39531. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  39532. this.width = 1.0;
  39533. this.height = 1.0;
  39534. this.angle = 0;
  39535. this.cellIndex = 0;
  39536. this.invertU = 0;
  39537. this.invertV = 0;
  39538. this.animations = new Array();
  39539. this.isPickable = false;
  39540. this._animationStarted = false;
  39541. this._loopAnimation = false;
  39542. this._fromIndex = 0;
  39543. this._toIndex = 0;
  39544. this._delay = 0;
  39545. this._direction = 1;
  39546. this._frameCount = 0;
  39547. this._time = 0;
  39548. this._manager = manager;
  39549. this._manager.sprites.push(this);
  39550. this.position = BABYLON.Vector3.Zero();
  39551. }
  39552. Object.defineProperty(Sprite.prototype, "size", {
  39553. get: function () {
  39554. return this.width;
  39555. },
  39556. set: function (value) {
  39557. this.width = value;
  39558. this.height = value;
  39559. },
  39560. enumerable: true,
  39561. configurable: true
  39562. });
  39563. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  39564. this._fromIndex = from;
  39565. this._toIndex = to;
  39566. this._loopAnimation = loop;
  39567. this._delay = delay;
  39568. this._animationStarted = true;
  39569. this._direction = from < to ? 1 : -1;
  39570. this.cellIndex = from;
  39571. this._time = 0;
  39572. this._onAnimationEnd = onAnimationEnd;
  39573. };
  39574. Sprite.prototype.stopAnimation = function () {
  39575. this._animationStarted = false;
  39576. };
  39577. Sprite.prototype._animate = function (deltaTime) {
  39578. if (!this._animationStarted)
  39579. return;
  39580. this._time += deltaTime;
  39581. if (this._time > this._delay) {
  39582. this._time = this._time % this._delay;
  39583. this.cellIndex += this._direction;
  39584. if (this.cellIndex > this._toIndex) {
  39585. if (this._loopAnimation) {
  39586. this.cellIndex = this._fromIndex;
  39587. }
  39588. else {
  39589. this.cellIndex = this._toIndex;
  39590. this._animationStarted = false;
  39591. if (this._onAnimationEnd) {
  39592. this._onAnimationEnd();
  39593. }
  39594. if (this.disposeWhenFinishedAnimating) {
  39595. this.dispose();
  39596. }
  39597. }
  39598. }
  39599. }
  39600. };
  39601. Sprite.prototype.dispose = function () {
  39602. for (var i = 0; i < this._manager.sprites.length; i++) {
  39603. if (this._manager.sprites[i] == this) {
  39604. this._manager.sprites.splice(i, 1);
  39605. }
  39606. }
  39607. };
  39608. return Sprite;
  39609. }());
  39610. BABYLON.Sprite = Sprite;
  39611. })(BABYLON || (BABYLON = {}));
  39612. //# sourceMappingURL=babylon.sprite.js.map
  39613. var BABYLON;
  39614. (function (BABYLON) {
  39615. var IntersectionInfo = (function () {
  39616. function IntersectionInfo(bu, bv, distance) {
  39617. this.bu = bu;
  39618. this.bv = bv;
  39619. this.distance = distance;
  39620. this.faceId = 0;
  39621. this.subMeshId = 0;
  39622. }
  39623. return IntersectionInfo;
  39624. }());
  39625. BABYLON.IntersectionInfo = IntersectionInfo;
  39626. var PickingInfo = (function () {
  39627. function PickingInfo() {
  39628. this.hit = false;
  39629. this.distance = 0;
  39630. this.pickedPoint = null;
  39631. this.pickedMesh = null;
  39632. this.bu = 0;
  39633. this.bv = 0;
  39634. this.faceId = -1;
  39635. this.subMeshId = 0;
  39636. this.pickedSprite = null;
  39637. }
  39638. // Methods
  39639. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  39640. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  39641. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  39642. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39643. return null;
  39644. }
  39645. var indices = this.pickedMesh.getIndices();
  39646. var result;
  39647. if (useVerticesNormals) {
  39648. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39649. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  39650. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  39651. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  39652. normal0 = normal0.scale(this.bu);
  39653. normal1 = normal1.scale(this.bv);
  39654. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  39655. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  39656. }
  39657. else {
  39658. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39659. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  39660. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  39661. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  39662. var p1p2 = vertex1.subtract(vertex2);
  39663. var p3p2 = vertex3.subtract(vertex2);
  39664. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  39665. }
  39666. if (useWorldCoordinates) {
  39667. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  39668. }
  39669. return BABYLON.Vector3.Normalize(result);
  39670. };
  39671. PickingInfo.prototype.getTextureCoordinates = function () {
  39672. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39673. return null;
  39674. }
  39675. var indices = this.pickedMesh.getIndices();
  39676. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39677. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  39678. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  39679. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  39680. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  39681. uv1 = uv1.scale(this.bu);
  39682. uv2 = uv2.scale(this.bv);
  39683. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  39684. };
  39685. return PickingInfo;
  39686. }());
  39687. BABYLON.PickingInfo = PickingInfo;
  39688. })(BABYLON || (BABYLON = {}));
  39689. //# sourceMappingURL=babylon.pickingInfo.js.map
  39690. var BABYLON;
  39691. (function (BABYLON) {
  39692. var Ray = (function () {
  39693. function Ray(origin, direction, length) {
  39694. if (length === void 0) { length = Number.MAX_VALUE; }
  39695. this.origin = origin;
  39696. this.direction = direction;
  39697. this.length = length;
  39698. }
  39699. // Methods
  39700. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  39701. var d = 0.0;
  39702. var maxValue = Number.MAX_VALUE;
  39703. var inv;
  39704. var min;
  39705. var max;
  39706. var temp;
  39707. if (Math.abs(this.direction.x) < 0.0000001) {
  39708. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  39709. return false;
  39710. }
  39711. }
  39712. else {
  39713. inv = 1.0 / this.direction.x;
  39714. min = (minimum.x - this.origin.x) * inv;
  39715. max = (maximum.x - this.origin.x) * inv;
  39716. if (max === -Infinity) {
  39717. max = Infinity;
  39718. }
  39719. if (min > max) {
  39720. temp = min;
  39721. min = max;
  39722. max = temp;
  39723. }
  39724. d = Math.max(min, d);
  39725. maxValue = Math.min(max, maxValue);
  39726. if (d > maxValue) {
  39727. return false;
  39728. }
  39729. }
  39730. if (Math.abs(this.direction.y) < 0.0000001) {
  39731. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  39732. return false;
  39733. }
  39734. }
  39735. else {
  39736. inv = 1.0 / this.direction.y;
  39737. min = (minimum.y - this.origin.y) * inv;
  39738. max = (maximum.y - this.origin.y) * inv;
  39739. if (max === -Infinity) {
  39740. max = Infinity;
  39741. }
  39742. if (min > max) {
  39743. temp = min;
  39744. min = max;
  39745. max = temp;
  39746. }
  39747. d = Math.max(min, d);
  39748. maxValue = Math.min(max, maxValue);
  39749. if (d > maxValue) {
  39750. return false;
  39751. }
  39752. }
  39753. if (Math.abs(this.direction.z) < 0.0000001) {
  39754. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  39755. return false;
  39756. }
  39757. }
  39758. else {
  39759. inv = 1.0 / this.direction.z;
  39760. min = (minimum.z - this.origin.z) * inv;
  39761. max = (maximum.z - this.origin.z) * inv;
  39762. if (max === -Infinity) {
  39763. max = Infinity;
  39764. }
  39765. if (min > max) {
  39766. temp = min;
  39767. min = max;
  39768. max = temp;
  39769. }
  39770. d = Math.max(min, d);
  39771. maxValue = Math.min(max, maxValue);
  39772. if (d > maxValue) {
  39773. return false;
  39774. }
  39775. }
  39776. return true;
  39777. };
  39778. Ray.prototype.intersectsBox = function (box) {
  39779. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  39780. };
  39781. Ray.prototype.intersectsSphere = function (sphere) {
  39782. var x = sphere.center.x - this.origin.x;
  39783. var y = sphere.center.y - this.origin.y;
  39784. var z = sphere.center.z - this.origin.z;
  39785. var pyth = (x * x) + (y * y) + (z * z);
  39786. var rr = sphere.radius * sphere.radius;
  39787. if (pyth <= rr) {
  39788. return true;
  39789. }
  39790. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  39791. if (dot < 0.0) {
  39792. return false;
  39793. }
  39794. var temp = pyth - (dot * dot);
  39795. return temp <= rr;
  39796. };
  39797. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  39798. if (!this._edge1) {
  39799. this._edge1 = BABYLON.Vector3.Zero();
  39800. this._edge2 = BABYLON.Vector3.Zero();
  39801. this._pvec = BABYLON.Vector3.Zero();
  39802. this._tvec = BABYLON.Vector3.Zero();
  39803. this._qvec = BABYLON.Vector3.Zero();
  39804. }
  39805. vertex1.subtractToRef(vertex0, this._edge1);
  39806. vertex2.subtractToRef(vertex0, this._edge2);
  39807. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  39808. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  39809. if (det === 0) {
  39810. return null;
  39811. }
  39812. var invdet = 1 / det;
  39813. this.origin.subtractToRef(vertex0, this._tvec);
  39814. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  39815. if (bu < 0 || bu > 1.0) {
  39816. return null;
  39817. }
  39818. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  39819. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  39820. if (bv < 0 || bu + bv > 1.0) {
  39821. return null;
  39822. }
  39823. //check if the distance is longer than the predefined length.
  39824. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  39825. if (distance > this.length) {
  39826. return null;
  39827. }
  39828. return new BABYLON.IntersectionInfo(bu, bv, distance);
  39829. };
  39830. Ray.prototype.intersectsPlane = function (plane) {
  39831. var distance;
  39832. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  39833. if (Math.abs(result1) < 9.99999997475243E-07) {
  39834. return null;
  39835. }
  39836. else {
  39837. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  39838. distance = (-plane.d - result2) / result1;
  39839. if (distance < 0.0) {
  39840. if (distance < -9.99999997475243E-07) {
  39841. return null;
  39842. }
  39843. else {
  39844. return 0;
  39845. }
  39846. }
  39847. return distance;
  39848. }
  39849. };
  39850. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  39851. var tm = BABYLON.Tmp.Matrix[0];
  39852. mesh.getWorldMatrix().invertToRef(tm);
  39853. if (this._tmpRay) {
  39854. Ray.TransformToRef(this, tm, this._tmpRay);
  39855. }
  39856. else {
  39857. this._tmpRay = Ray.Transform(this, tm);
  39858. }
  39859. return mesh.intersects(this._tmpRay, fastCheck);
  39860. };
  39861. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  39862. if (results) {
  39863. results.length = 0;
  39864. }
  39865. else {
  39866. results = [];
  39867. }
  39868. for (var i = 0; i < meshes.length; i++) {
  39869. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  39870. if (pickInfo.hit) {
  39871. results.push(pickInfo);
  39872. }
  39873. }
  39874. results.sort(this._comparePickingInfo);
  39875. return results;
  39876. };
  39877. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  39878. if (pickingInfoA.distance < pickingInfoB.distance) {
  39879. return -1;
  39880. }
  39881. else if (pickingInfoA.distance > pickingInfoB.distance) {
  39882. return 1;
  39883. }
  39884. else {
  39885. return 0;
  39886. }
  39887. };
  39888. /**
  39889. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  39890. * @param sega the first point of the segment to test the intersection against
  39891. * @param segb the second point of the segment to test the intersection against
  39892. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  39893. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  39894. */
  39895. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  39896. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  39897. var u = segb.subtract(sega);
  39898. var v = rsegb.subtract(this.origin);
  39899. var w = sega.subtract(this.origin);
  39900. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  39901. var b = BABYLON.Vector3.Dot(u, v);
  39902. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  39903. var d = BABYLON.Vector3.Dot(u, w);
  39904. var e = BABYLON.Vector3.Dot(v, w);
  39905. var D = a * c - b * b; // always >= 0
  39906. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  39907. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  39908. // compute the line parameters of the two closest points
  39909. if (D < Ray.smallnum) {
  39910. sN = 0.0; // force using point P0 on segment S1
  39911. sD = 1.0; // to prevent possible division by 0.0 later
  39912. tN = e;
  39913. tD = c;
  39914. }
  39915. else {
  39916. sN = (b * e - c * d);
  39917. tN = (a * e - b * d);
  39918. if (sN < 0.0) {
  39919. sN = 0.0;
  39920. tN = e;
  39921. tD = c;
  39922. }
  39923. else if (sN > sD) {
  39924. sN = sD;
  39925. tN = e + b;
  39926. tD = c;
  39927. }
  39928. }
  39929. if (tN < 0.0) {
  39930. tN = 0.0;
  39931. // recompute sc for this edge
  39932. if (-d < 0.0) {
  39933. sN = 0.0;
  39934. }
  39935. else if (-d > a)
  39936. sN = sD;
  39937. else {
  39938. sN = -d;
  39939. sD = a;
  39940. }
  39941. }
  39942. else if (tN > tD) {
  39943. tN = tD;
  39944. // recompute sc for this edge
  39945. if ((-d + b) < 0.0) {
  39946. sN = 0;
  39947. }
  39948. else if ((-d + b) > a) {
  39949. sN = sD;
  39950. }
  39951. else {
  39952. sN = (-d + b);
  39953. sD = a;
  39954. }
  39955. }
  39956. // finally do the division to get sc and tc
  39957. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  39958. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  39959. // get the difference of the two closest points
  39960. var qtc = v.multiplyByFloats(tc, tc, tc);
  39961. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  39962. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  39963. if (isIntersected) {
  39964. return qtc.length();
  39965. }
  39966. return -1;
  39967. };
  39968. // Statics
  39969. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  39970. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  39971. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  39972. var direction = end.subtract(start);
  39973. direction.normalize();
  39974. return new Ray(start, direction);
  39975. };
  39976. /**
  39977. * 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
  39978. * transformed to the given world matrix.
  39979. * @param origin The origin point
  39980. * @param end The end point
  39981. * @param world a matrix to transform the ray to. Default is the identity matrix.
  39982. */
  39983. Ray.CreateNewFromTo = function (origin, end, world) {
  39984. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  39985. var direction = end.subtract(origin);
  39986. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  39987. direction.normalize();
  39988. return Ray.Transform(new Ray(origin, direction, length), world);
  39989. };
  39990. Ray.Transform = function (ray, matrix) {
  39991. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  39992. Ray.TransformToRef(ray, matrix, result);
  39993. return result;
  39994. };
  39995. Ray.TransformToRef = function (ray, matrix, result) {
  39996. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  39997. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  39998. result.length = ray.length;
  39999. var dir = result.direction;
  40000. var len = dir.length();
  40001. if (!(len === 0 || len === 1)) {
  40002. var num = 1.0 / len;
  40003. dir.x *= num;
  40004. dir.y *= num;
  40005. dir.z *= num;
  40006. result.length *= len;
  40007. }
  40008. };
  40009. Ray.smallnum = 0.00000001;
  40010. Ray.rayl = 10e8;
  40011. return Ray;
  40012. }());
  40013. BABYLON.Ray = Ray;
  40014. })(BABYLON || (BABYLON = {}));
  40015. //# sourceMappingURL=babylon.ray.js.map
  40016. var BABYLON;
  40017. (function (BABYLON) {
  40018. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  40019. if (boxMin.x > sphereCenter.x + sphereRadius)
  40020. return false;
  40021. if (sphereCenter.x - sphereRadius > boxMax.x)
  40022. return false;
  40023. if (boxMin.y > sphereCenter.y + sphereRadius)
  40024. return false;
  40025. if (sphereCenter.y - sphereRadius > boxMax.y)
  40026. return false;
  40027. if (boxMin.z > sphereCenter.z + sphereRadius)
  40028. return false;
  40029. if (sphereCenter.z - sphereRadius > boxMax.z)
  40030. return false;
  40031. return true;
  40032. };
  40033. var getLowestRoot = (function () {
  40034. var result = { root: 0, found: false };
  40035. return function (a, b, c, maxR) {
  40036. result.root = 0;
  40037. result.found = false;
  40038. var determinant = b * b - 4.0 * a * c;
  40039. if (determinant < 0)
  40040. return result;
  40041. var sqrtD = Math.sqrt(determinant);
  40042. var r1 = (-b - sqrtD) / (2.0 * a);
  40043. var r2 = (-b + sqrtD) / (2.0 * a);
  40044. if (r1 > r2) {
  40045. var temp = r2;
  40046. r2 = r1;
  40047. r1 = temp;
  40048. }
  40049. if (r1 > 0 && r1 < maxR) {
  40050. result.root = r1;
  40051. result.found = true;
  40052. return result;
  40053. }
  40054. if (r2 > 0 && r2 < maxR) {
  40055. result.root = r2;
  40056. result.found = true;
  40057. return result;
  40058. }
  40059. return result;
  40060. };
  40061. })();
  40062. var Collider = (function () {
  40063. function Collider() {
  40064. this.radius = BABYLON.Vector3.One();
  40065. this.retry = 0;
  40066. this.basePointWorld = BABYLON.Vector3.Zero();
  40067. this.velocityWorld = BABYLON.Vector3.Zero();
  40068. this.normalizedVelocity = BABYLON.Vector3.Zero();
  40069. this._collisionPoint = BABYLON.Vector3.Zero();
  40070. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  40071. this._tempVector = BABYLON.Vector3.Zero();
  40072. this._tempVector2 = BABYLON.Vector3.Zero();
  40073. this._tempVector3 = BABYLON.Vector3.Zero();
  40074. this._tempVector4 = BABYLON.Vector3.Zero();
  40075. this._edge = BABYLON.Vector3.Zero();
  40076. this._baseToVertex = BABYLON.Vector3.Zero();
  40077. this._destinationPoint = BABYLON.Vector3.Zero();
  40078. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  40079. this._displacementVector = BABYLON.Vector3.Zero();
  40080. this._collisionMask = -1;
  40081. }
  40082. Object.defineProperty(Collider.prototype, "collisionMask", {
  40083. get: function () {
  40084. return this._collisionMask;
  40085. },
  40086. set: function (mask) {
  40087. this._collisionMask = !isNaN(mask) ? mask : -1;
  40088. },
  40089. enumerable: true,
  40090. configurable: true
  40091. });
  40092. // Methods
  40093. Collider.prototype._initialize = function (source, dir, e) {
  40094. this.velocity = dir;
  40095. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  40096. this.basePoint = source;
  40097. source.multiplyToRef(this.radius, this.basePointWorld);
  40098. dir.multiplyToRef(this.radius, this.velocityWorld);
  40099. this.velocityWorldLength = this.velocityWorld.length();
  40100. this.epsilon = e;
  40101. this.collisionFound = false;
  40102. };
  40103. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  40104. pa.subtractToRef(point, this._tempVector);
  40105. pb.subtractToRef(point, this._tempVector2);
  40106. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  40107. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  40108. if (d < 0)
  40109. return false;
  40110. pc.subtractToRef(point, this._tempVector3);
  40111. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  40112. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  40113. if (d < 0)
  40114. return false;
  40115. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  40116. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  40117. return d >= 0;
  40118. };
  40119. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  40120. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  40121. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  40122. if (distance > this.velocityWorldLength + max + sphereRadius) {
  40123. return false;
  40124. }
  40125. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  40126. return false;
  40127. return true;
  40128. };
  40129. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  40130. var t0;
  40131. var embeddedInPlane = false;
  40132. //defensive programming, actually not needed.
  40133. if (!trianglePlaneArray) {
  40134. trianglePlaneArray = [];
  40135. }
  40136. if (!trianglePlaneArray[faceIndex]) {
  40137. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  40138. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  40139. }
  40140. var trianglePlane = trianglePlaneArray[faceIndex];
  40141. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  40142. return;
  40143. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  40144. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  40145. if (normalDotVelocity == 0) {
  40146. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  40147. return;
  40148. embeddedInPlane = true;
  40149. t0 = 0;
  40150. }
  40151. else {
  40152. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  40153. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  40154. if (t0 > t1) {
  40155. var temp = t1;
  40156. t1 = t0;
  40157. t0 = temp;
  40158. }
  40159. if (t0 > 1.0 || t1 < 0.0)
  40160. return;
  40161. if (t0 < 0)
  40162. t0 = 0;
  40163. if (t0 > 1.0)
  40164. t0 = 1.0;
  40165. }
  40166. this._collisionPoint.copyFromFloats(0, 0, 0);
  40167. var found = false;
  40168. var t = 1.0;
  40169. if (!embeddedInPlane) {
  40170. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  40171. this.velocity.scaleToRef(t0, this._tempVector);
  40172. this._planeIntersectionPoint.addInPlace(this._tempVector);
  40173. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  40174. found = true;
  40175. t = t0;
  40176. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  40177. }
  40178. }
  40179. if (!found) {
  40180. var velocitySquaredLength = this.velocity.lengthSquared();
  40181. var a = velocitySquaredLength;
  40182. this.basePoint.subtractToRef(p1, this._tempVector);
  40183. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  40184. var c = this._tempVector.lengthSquared() - 1.0;
  40185. var lowestRoot = getLowestRoot(a, b, c, t);
  40186. if (lowestRoot.found) {
  40187. t = lowestRoot.root;
  40188. found = true;
  40189. this._collisionPoint.copyFrom(p1);
  40190. }
  40191. this.basePoint.subtractToRef(p2, this._tempVector);
  40192. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  40193. c = this._tempVector.lengthSquared() - 1.0;
  40194. lowestRoot = getLowestRoot(a, b, c, t);
  40195. if (lowestRoot.found) {
  40196. t = lowestRoot.root;
  40197. found = true;
  40198. this._collisionPoint.copyFrom(p2);
  40199. }
  40200. this.basePoint.subtractToRef(p3, this._tempVector);
  40201. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  40202. c = this._tempVector.lengthSquared() - 1.0;
  40203. lowestRoot = getLowestRoot(a, b, c, t);
  40204. if (lowestRoot.found) {
  40205. t = lowestRoot.root;
  40206. found = true;
  40207. this._collisionPoint.copyFrom(p3);
  40208. }
  40209. p2.subtractToRef(p1, this._edge);
  40210. p1.subtractToRef(this.basePoint, this._baseToVertex);
  40211. var edgeSquaredLength = this._edge.lengthSquared();
  40212. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  40213. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  40214. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  40215. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  40216. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  40217. lowestRoot = getLowestRoot(a, b, c, t);
  40218. if (lowestRoot.found) {
  40219. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  40220. if (f >= 0.0 && f <= 1.0) {
  40221. t = lowestRoot.root;
  40222. found = true;
  40223. this._edge.scaleInPlace(f);
  40224. p1.addToRef(this._edge, this._collisionPoint);
  40225. }
  40226. }
  40227. p3.subtractToRef(p2, this._edge);
  40228. p2.subtractToRef(this.basePoint, this._baseToVertex);
  40229. edgeSquaredLength = this._edge.lengthSquared();
  40230. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  40231. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  40232. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  40233. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  40234. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  40235. lowestRoot = getLowestRoot(a, b, c, t);
  40236. if (lowestRoot.found) {
  40237. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  40238. if (f >= 0.0 && f <= 1.0) {
  40239. t = lowestRoot.root;
  40240. found = true;
  40241. this._edge.scaleInPlace(f);
  40242. p2.addToRef(this._edge, this._collisionPoint);
  40243. }
  40244. }
  40245. p1.subtractToRef(p3, this._edge);
  40246. p3.subtractToRef(this.basePoint, this._baseToVertex);
  40247. edgeSquaredLength = this._edge.lengthSquared();
  40248. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  40249. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  40250. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  40251. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  40252. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  40253. lowestRoot = getLowestRoot(a, b, c, t);
  40254. if (lowestRoot.found) {
  40255. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  40256. if (f >= 0.0 && f <= 1.0) {
  40257. t = lowestRoot.root;
  40258. found = true;
  40259. this._edge.scaleInPlace(f);
  40260. p3.addToRef(this._edge, this._collisionPoint);
  40261. }
  40262. }
  40263. }
  40264. if (found) {
  40265. var distToCollision = t * this.velocity.length();
  40266. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  40267. if (!this.intersectionPoint) {
  40268. this.intersectionPoint = this._collisionPoint.clone();
  40269. }
  40270. else {
  40271. this.intersectionPoint.copyFrom(this._collisionPoint);
  40272. }
  40273. this.nearestDistance = distToCollision;
  40274. this.collisionFound = true;
  40275. }
  40276. }
  40277. };
  40278. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  40279. for (var i = indexStart; i < indexEnd; i += 3) {
  40280. var p1 = pts[indices[i] - decal];
  40281. var p2 = pts[indices[i + 1] - decal];
  40282. var p3 = pts[indices[i + 2] - decal];
  40283. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  40284. }
  40285. };
  40286. Collider.prototype._getResponse = function (pos, vel) {
  40287. pos.addToRef(vel, this._destinationPoint);
  40288. vel.scaleInPlace((this.nearestDistance / vel.length()));
  40289. this.basePoint.addToRef(vel, pos);
  40290. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  40291. this._slidePlaneNormal.normalize();
  40292. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  40293. pos.addInPlace(this._displacementVector);
  40294. this.intersectionPoint.addInPlace(this._displacementVector);
  40295. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  40296. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  40297. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  40298. };
  40299. return Collider;
  40300. }());
  40301. BABYLON.Collider = Collider;
  40302. })(BABYLON || (BABYLON = {}));
  40303. //# sourceMappingURL=babylon.collider.js.map
  40304. var BABYLON;
  40305. (function (BABYLON) {
  40306. //WebWorker code will be inserted to this variable.
  40307. BABYLON.CollisionWorker = "";
  40308. var WorkerTaskType;
  40309. (function (WorkerTaskType) {
  40310. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  40311. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  40312. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  40313. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  40314. var WorkerReplyType;
  40315. (function (WorkerReplyType) {
  40316. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  40317. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  40318. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  40319. var CollisionCoordinatorWorker = (function () {
  40320. function CollisionCoordinatorWorker() {
  40321. var _this = this;
  40322. this._scaledPosition = BABYLON.Vector3.Zero();
  40323. this._scaledVelocity = BABYLON.Vector3.Zero();
  40324. this.onMeshUpdated = function (mesh) {
  40325. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  40326. };
  40327. this.onGeometryUpdated = function (geometry) {
  40328. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  40329. };
  40330. this._afterRender = function () {
  40331. if (!_this._init)
  40332. return;
  40333. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  40334. return;
  40335. }
  40336. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  40337. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  40338. if (_this._runningUpdated > 4) {
  40339. return;
  40340. }
  40341. ++_this._runningUpdated;
  40342. var payload = {
  40343. updatedMeshes: _this._addUpdateMeshesList,
  40344. updatedGeometries: _this._addUpdateGeometriesList,
  40345. removedGeometries: _this._toRemoveGeometryArray,
  40346. removedMeshes: _this._toRemoveMeshesArray
  40347. };
  40348. var message = {
  40349. payload: payload,
  40350. taskType: WorkerTaskType.UPDATE
  40351. };
  40352. var serializable = [];
  40353. for (var id in payload.updatedGeometries) {
  40354. if (payload.updatedGeometries.hasOwnProperty(id)) {
  40355. //prepare transferables
  40356. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  40357. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  40358. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  40359. }
  40360. }
  40361. _this._worker.postMessage(message, serializable);
  40362. _this._addUpdateMeshesList = {};
  40363. _this._addUpdateGeometriesList = {};
  40364. _this._toRemoveGeometryArray = [];
  40365. _this._toRemoveMeshesArray = [];
  40366. };
  40367. this._onMessageFromWorker = function (e) {
  40368. var returnData = e.data;
  40369. if (returnData.error != WorkerReplyType.SUCCESS) {
  40370. //TODO what errors can be returned from the worker?
  40371. BABYLON.Tools.Warn("error returned from worker!");
  40372. return;
  40373. }
  40374. switch (returnData.taskType) {
  40375. case WorkerTaskType.INIT:
  40376. _this._init = true;
  40377. //Update the worked with ALL of the scene's current state
  40378. _this._scene.meshes.forEach(function (mesh) {
  40379. _this.onMeshAdded(mesh);
  40380. });
  40381. _this._scene.getGeometries().forEach(function (geometry) {
  40382. _this.onGeometryAdded(geometry);
  40383. });
  40384. break;
  40385. case WorkerTaskType.UPDATE:
  40386. _this._runningUpdated--;
  40387. break;
  40388. case WorkerTaskType.COLLIDE:
  40389. _this._runningCollisionTask = false;
  40390. var returnPayload = returnData.payload;
  40391. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  40392. return;
  40393. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  40394. //cleanup
  40395. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  40396. break;
  40397. }
  40398. };
  40399. this._collisionsCallbackArray = [];
  40400. this._init = false;
  40401. this._runningUpdated = 0;
  40402. this._runningCollisionTask = false;
  40403. this._addUpdateMeshesList = {};
  40404. this._addUpdateGeometriesList = {};
  40405. this._toRemoveGeometryArray = [];
  40406. this._toRemoveMeshesArray = [];
  40407. }
  40408. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  40409. if (!this._init)
  40410. return;
  40411. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  40412. return;
  40413. position.divideToRef(collider.radius, this._scaledPosition);
  40414. displacement.divideToRef(collider.radius, this._scaledVelocity);
  40415. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  40416. var payload = {
  40417. collider: {
  40418. position: this._scaledPosition.asArray(),
  40419. velocity: this._scaledVelocity.asArray(),
  40420. radius: collider.radius.asArray()
  40421. },
  40422. collisionId: collisionIndex,
  40423. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  40424. maximumRetry: maximumRetry
  40425. };
  40426. var message = {
  40427. payload: payload,
  40428. taskType: WorkerTaskType.COLLIDE
  40429. };
  40430. this._worker.postMessage(message);
  40431. };
  40432. CollisionCoordinatorWorker.prototype.init = function (scene) {
  40433. this._scene = scene;
  40434. this._scene.registerAfterRender(this._afterRender);
  40435. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  40436. this._worker = new Worker(workerUrl);
  40437. this._worker.onmessage = this._onMessageFromWorker;
  40438. var message = {
  40439. payload: {},
  40440. taskType: WorkerTaskType.INIT
  40441. };
  40442. this._worker.postMessage(message);
  40443. };
  40444. CollisionCoordinatorWorker.prototype.destroy = function () {
  40445. this._scene.unregisterAfterRender(this._afterRender);
  40446. this._worker.terminate();
  40447. };
  40448. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  40449. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  40450. this.onMeshUpdated(mesh);
  40451. };
  40452. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  40453. this._toRemoveMeshesArray.push(mesh.uniqueId);
  40454. };
  40455. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  40456. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  40457. geometry.onGeometryUpdated = this.onGeometryUpdated;
  40458. this.onGeometryUpdated(geometry);
  40459. };
  40460. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  40461. this._toRemoveGeometryArray.push(geometry.id);
  40462. };
  40463. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  40464. var submeshes = [];
  40465. if (mesh.subMeshes) {
  40466. submeshes = mesh.subMeshes.map(function (sm, idx) {
  40467. return {
  40468. position: idx,
  40469. verticesStart: sm.verticesStart,
  40470. verticesCount: sm.verticesCount,
  40471. indexStart: sm.indexStart,
  40472. indexCount: sm.indexCount,
  40473. hasMaterial: !!sm.getMaterial(),
  40474. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  40475. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  40476. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  40477. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  40478. };
  40479. });
  40480. }
  40481. var geometryId = null;
  40482. if (mesh instanceof BABYLON.Mesh) {
  40483. geometryId = mesh.geometry ? mesh.geometry.id : null;
  40484. }
  40485. else if (mesh instanceof BABYLON.InstancedMesh) {
  40486. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  40487. }
  40488. return {
  40489. uniqueId: mesh.uniqueId,
  40490. id: mesh.id,
  40491. name: mesh.name,
  40492. geometryId: geometryId,
  40493. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  40494. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  40495. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  40496. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  40497. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  40498. subMeshes: submeshes,
  40499. checkCollisions: mesh.checkCollisions
  40500. };
  40501. };
  40502. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  40503. return {
  40504. id: geometry.id,
  40505. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  40506. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  40507. indices: new Uint32Array(geometry.getIndices() || []),
  40508. };
  40509. };
  40510. return CollisionCoordinatorWorker;
  40511. }());
  40512. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  40513. var CollisionCoordinatorLegacy = (function () {
  40514. function CollisionCoordinatorLegacy() {
  40515. this._scaledPosition = BABYLON.Vector3.Zero();
  40516. this._scaledVelocity = BABYLON.Vector3.Zero();
  40517. this._finalPosition = BABYLON.Vector3.Zero();
  40518. }
  40519. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  40520. position.divideToRef(collider.radius, this._scaledPosition);
  40521. displacement.divideToRef(collider.radius, this._scaledVelocity);
  40522. collider.collidedMesh = null;
  40523. collider.retry = 0;
  40524. collider.initialVelocity = this._scaledVelocity;
  40525. collider.initialPosition = this._scaledPosition;
  40526. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  40527. this._finalPosition.multiplyInPlace(collider.radius);
  40528. //run the callback
  40529. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  40530. };
  40531. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  40532. this._scene = scene;
  40533. };
  40534. CollisionCoordinatorLegacy.prototype.destroy = function () {
  40535. //Legacy need no destruction method.
  40536. };
  40537. //No update in legacy mode
  40538. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  40539. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  40540. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  40541. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  40542. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  40543. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  40544. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  40545. if (excludedMesh === void 0) { excludedMesh = null; }
  40546. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  40547. if (collider.retry >= maximumRetry) {
  40548. finalPosition.copyFrom(position);
  40549. return;
  40550. }
  40551. // Check if this is a mesh else camera or -1
  40552. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  40553. collider._initialize(position, velocity, closeDistance);
  40554. // Check all meshes
  40555. for (var index = 0; index < this._scene.meshes.length; index++) {
  40556. var mesh = this._scene.meshes[index];
  40557. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  40558. mesh._checkCollision(collider);
  40559. }
  40560. }
  40561. if (!collider.collisionFound) {
  40562. position.addToRef(velocity, finalPosition);
  40563. return;
  40564. }
  40565. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  40566. collider._getResponse(position, velocity);
  40567. }
  40568. if (velocity.length() <= closeDistance) {
  40569. finalPosition.copyFrom(position);
  40570. return;
  40571. }
  40572. collider.retry++;
  40573. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  40574. };
  40575. return CollisionCoordinatorLegacy;
  40576. }());
  40577. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  40578. })(BABYLON || (BABYLON = {}));
  40579. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  40580. var BABYLON;
  40581. (function (BABYLON) {
  40582. var Particle = (function () {
  40583. function Particle(particleSystem, cellIndex, invertU, invertV, _loopAnimation, _fromIndex, _toIndex, _delay, _sheetDirection, _time, disposeWhenFinishedAnimating) {
  40584. if (cellIndex === void 0) { cellIndex = 0; }
  40585. if (invertU === void 0) { invertU = 0; }
  40586. if (invertV === void 0) { invertV = 0; }
  40587. if (_loopAnimation === void 0) { _loopAnimation = false; }
  40588. if (_fromIndex === void 0) { _fromIndex = 0; }
  40589. if (_toIndex === void 0) { _toIndex = 0; }
  40590. if (_delay === void 0) { _delay = 0; }
  40591. if (_sheetDirection === void 0) { _sheetDirection = 1; }
  40592. if (_time === void 0) { _time = 0; }
  40593. if (disposeWhenFinishedAnimating === void 0) { disposeWhenFinishedAnimating = false; }
  40594. this.particleSystem = particleSystem;
  40595. this.cellIndex = cellIndex;
  40596. this.invertU = invertU;
  40597. this.invertV = invertV;
  40598. this._loopAnimation = _loopAnimation;
  40599. this._fromIndex = _fromIndex;
  40600. this._toIndex = _toIndex;
  40601. this._delay = _delay;
  40602. this._sheetDirection = _sheetDirection;
  40603. this._time = _time;
  40604. this.disposeWhenFinishedAnimating = disposeWhenFinishedAnimating;
  40605. this.position = BABYLON.Vector3.Zero();
  40606. this.direction = BABYLON.Vector3.Zero();
  40607. this.color = new BABYLON.Color4(0, 0, 0, 0);
  40608. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  40609. this.lifeTime = 1.0;
  40610. this.age = 0;
  40611. this.size = 0;
  40612. this.angle = 0;
  40613. this.angularSpeed = 0;
  40614. }
  40615. Particle.prototype.updateCellIndex = function (deltaTime) {
  40616. this._time += deltaTime;
  40617. if (this._time > this._delay) {
  40618. this._time = this._time % this._delay;
  40619. this.cellIndex += this._sheetDirection;
  40620. if (this.cellIndex > this._toIndex) {
  40621. if (this._loopAnimation) {
  40622. this.cellIndex = this._fromIndex;
  40623. }
  40624. else {
  40625. this.cellIndex = this._toIndex;
  40626. if (this.disposeWhenFinishedAnimating) {
  40627. this.readyForRecycling();
  40628. }
  40629. }
  40630. }
  40631. }
  40632. };
  40633. Particle.prototype.copyTo = function (other) {
  40634. other.position.copyFrom(this.position);
  40635. other.direction.copyFrom(this.direction);
  40636. other.color.copyFrom(this.color);
  40637. other.colorStep.copyFrom(this.colorStep);
  40638. other.lifeTime = this.lifeTime;
  40639. other.age = this.age;
  40640. other.size = this.size;
  40641. other.angle = this.angle;
  40642. other.angularSpeed = this.angularSpeed;
  40643. other.particleSystem = this.particleSystem;
  40644. other.cellIndex = this.cellIndex;
  40645. other.invertU = this.invertU;
  40646. other.invertV = this.invertV;
  40647. other._loopAnimation = this._loopAnimation;
  40648. other._fromIndex = this._fromIndex;
  40649. other._toIndex = this._toIndex;
  40650. other._delay = this._delay;
  40651. other._sheetDirection = this._sheetDirection;
  40652. other._time = this._time;
  40653. other.disposeWhenFinishedAnimating = this.disposeWhenFinishedAnimating;
  40654. };
  40655. Particle.prototype.readyForRecycling = function () {
  40656. this.age = this.lifeTime;
  40657. };
  40658. return Particle;
  40659. }());
  40660. BABYLON.Particle = Particle;
  40661. })(BABYLON || (BABYLON = {}));
  40662. //# sourceMappingURL=babylon.particle.js.map
  40663. var BABYLON;
  40664. (function (BABYLON) {
  40665. var randomNumber = function (min, max) {
  40666. if (min === max) {
  40667. return (min);
  40668. }
  40669. var random = Math.random();
  40670. return ((random * (max - min)) + min);
  40671. };
  40672. var ParticleSystem = (function () {
  40673. // end of sheet animation
  40674. function ParticleSystem(name, capacity, scene, customEffect, cellSize, epsilon) {
  40675. if (epsilon === void 0) { epsilon = 0.01; }
  40676. var _this = this;
  40677. this.name = name;
  40678. this.cellSize = cellSize;
  40679. // Members
  40680. this.animations = [];
  40681. this.renderingGroupId = 0;
  40682. this.emitter = null;
  40683. this.emitRate = 10;
  40684. this.manualEmitCount = -1;
  40685. this.updateSpeed = 0.01;
  40686. this.targetStopDuration = 0;
  40687. this.disposeOnStop = false;
  40688. this.minEmitPower = 1;
  40689. this.maxEmitPower = 1;
  40690. this.minLifeTime = 1;
  40691. this.maxLifeTime = 1;
  40692. this.minSize = 1;
  40693. this.maxSize = 1;
  40694. this.minAngularSpeed = 0;
  40695. this.maxAngularSpeed = 0;
  40696. this.layerMask = 0x0FFFFFFF;
  40697. this.customShader = null;
  40698. this.preventAutoStart = false;
  40699. this.disposeParticlesWhenFinishedAnimating = false;
  40700. /**
  40701. * An event triggered when the system is disposed.
  40702. * @type {BABYLON.Observable}
  40703. */
  40704. this.onDisposeObservable = new BABYLON.Observable();
  40705. this.onAnimationEnd = null;
  40706. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  40707. this.forceDepthWrite = false;
  40708. this.gravity = BABYLON.Vector3.Zero();
  40709. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  40710. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  40711. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  40712. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  40713. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  40714. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  40715. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  40716. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  40717. this.particles = new Array();
  40718. this._stockParticles = new Array();
  40719. this._newPartsExcess = 0;
  40720. this._vertexBuffers = {};
  40721. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  40722. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  40723. this._scaledDirection = BABYLON.Vector3.Zero();
  40724. this._scaledGravity = BABYLON.Vector3.Zero();
  40725. this._currentRenderId = -1;
  40726. this._started = false;
  40727. this._stopped = false;
  40728. this._actualFrame = 0;
  40729. // sheet animation
  40730. this._animationStarted = false;
  40731. this._loopAnimation = false;
  40732. this._fromIndex = 0;
  40733. this._toIndex = 0;
  40734. this._delay = 0;
  40735. this._sheetDirection = 1;
  40736. this._time = 0;
  40737. this._vertexBufferSize = 11;
  40738. this.appendParticleVertexes = null;
  40739. this.id = name;
  40740. this._capacity = capacity;
  40741. this._epsilon = epsilon;
  40742. if (cellSize) {
  40743. this._vertexBufferSize = 15;
  40744. if (cellSize.width && cellSize.height) {
  40745. this.cellWidth = cellSize.width;
  40746. this.cellHeight = cellSize.height;
  40747. }
  40748. else {
  40749. this.cellWidth = cellSize;
  40750. this.cellHeight = cellSize;
  40751. }
  40752. }
  40753. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  40754. this._customEffect = customEffect;
  40755. scene.particleSystems.push(this);
  40756. this._createIndexBuffer();
  40757. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  40758. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  40759. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  40760. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  40761. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  40762. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  40763. if (this.cellSize) {
  40764. var cellInfo = this._vertexBuffer.createVertexBuffer("cellInfo", 11, 4);
  40765. this._vertexBuffers["cellInfo"] = cellInfo;
  40766. }
  40767. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  40768. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  40769. this._vertexBuffers["options"] = options;
  40770. // Default behaviors
  40771. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  40772. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  40773. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  40774. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  40775. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  40776. };
  40777. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  40778. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  40779. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  40780. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  40781. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  40782. };
  40783. this.updateFunction = function (particles) {
  40784. var deltaTime = _this._scene.getEngine().getDeltaTime();
  40785. for (var index = 0; index < particles.length; index++) {
  40786. var particle = particles[index];
  40787. particle.age += _this._scaledUpdateSpeed;
  40788. if (particle.age >= particle.lifeTime) {
  40789. _this.recycleParticle(particle);
  40790. index--;
  40791. continue;
  40792. }
  40793. else {
  40794. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  40795. particle.color.addInPlace(_this._scaledColorStep);
  40796. if (particle.color.a < 0)
  40797. particle.color.a = 0;
  40798. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  40799. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  40800. particle.position.addInPlace(_this._scaledDirection);
  40801. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  40802. particle.direction.addInPlace(_this._scaledGravity);
  40803. if (_this.cellSize && _this._animationStarted) {
  40804. particle.updateCellIndex(deltaTime);
  40805. }
  40806. }
  40807. }
  40808. };
  40809. }
  40810. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  40811. set: function (callback) {
  40812. if (this._onDisposeObserver) {
  40813. this.onDisposeObservable.remove(this._onDisposeObserver);
  40814. }
  40815. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  40816. },
  40817. enumerable: true,
  40818. configurable: true
  40819. });
  40820. ParticleSystem.prototype._createIndexBuffer = function () {
  40821. var indices = [];
  40822. var index = 0;
  40823. for (var count = 0; count < this._capacity; count++) {
  40824. indices.push(index);
  40825. indices.push(index + 1);
  40826. indices.push(index + 2);
  40827. indices.push(index);
  40828. indices.push(index + 2);
  40829. indices.push(index + 3);
  40830. index += 4;
  40831. }
  40832. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40833. };
  40834. ParticleSystem.prototype.recycleParticle = function (particle) {
  40835. var lastParticle = this.particles.pop();
  40836. if (lastParticle !== particle) {
  40837. lastParticle.copyTo(particle);
  40838. this._stockParticles.push(lastParticle);
  40839. }
  40840. };
  40841. ParticleSystem.prototype.getCapacity = function () {
  40842. return this._capacity;
  40843. };
  40844. ParticleSystem.prototype.isAlive = function () {
  40845. return this._alive;
  40846. };
  40847. ParticleSystem.prototype.isStarted = function () {
  40848. return this._started;
  40849. };
  40850. ParticleSystem.prototype.start = function () {
  40851. this._started = true;
  40852. this._stopped = false;
  40853. this._actualFrame = 0;
  40854. };
  40855. ParticleSystem.prototype.stop = function () {
  40856. this._stopped = true;
  40857. };
  40858. // animation sheet
  40859. ParticleSystem.prototype.playAnimation = function (from, to, loop, delay) {
  40860. this._fromIndex = from;
  40861. this._toIndex = to;
  40862. this._loopAnimation = loop;
  40863. this._delay = delay;
  40864. this._animationStarted = true;
  40865. this._sheetDirection = from < to ? 1 : -1;
  40866. this.cellIndex = from;
  40867. this._time = 0;
  40868. };
  40869. ParticleSystem.prototype.stopAnimation = function () {
  40870. this._animationStarted = false;
  40871. };
  40872. // animation sheet
  40873. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  40874. var offset = index * this._vertexBufferSize;
  40875. this._vertexData[offset] = particle.position.x;
  40876. this._vertexData[offset + 1] = particle.position.y;
  40877. this._vertexData[offset + 2] = particle.position.z;
  40878. this._vertexData[offset + 3] = particle.color.r;
  40879. this._vertexData[offset + 4] = particle.color.g;
  40880. this._vertexData[offset + 5] = particle.color.b;
  40881. this._vertexData[offset + 6] = particle.color.a;
  40882. this._vertexData[offset + 7] = particle.angle;
  40883. this._vertexData[offset + 8] = particle.size;
  40884. this._vertexData[offset + 9] = offsetX;
  40885. this._vertexData[offset + 10] = offsetY;
  40886. };
  40887. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY, rowSize) {
  40888. if (offsetX === 0)
  40889. offsetX = this._epsilon;
  40890. else if (offsetX === 1)
  40891. offsetX = 1 - this._epsilon;
  40892. if (offsetY === 0)
  40893. offsetY = this._epsilon;
  40894. else if (offsetY === 1)
  40895. offsetY = 1 - this._epsilon;
  40896. var rowOffset = (particle.cellIndex / rowSize) >> 0;
  40897. var columnOffset = particle.cellIndex - rowOffset * rowSize;
  40898. var intertU = particle.invertU ? 1 : 0;
  40899. var interV = particle.invertV ? 1 : 0;
  40900. var offset = index * this._vertexBufferSize;
  40901. this._vertexData[offset] = particle.position.x;
  40902. this._vertexData[offset + 1] = particle.position.y;
  40903. this._vertexData[offset + 2] = particle.position.z;
  40904. this._vertexData[offset + 3] = particle.color.r;
  40905. this._vertexData[offset + 4] = particle.color.g;
  40906. this._vertexData[offset + 5] = particle.color.b;
  40907. this._vertexData[offset + 6] = particle.color.a;
  40908. this._vertexData[offset + 7] = particle.angle;
  40909. this._vertexData[offset + 8] = particle.size;
  40910. this._vertexData[offset + 9] = offsetX;
  40911. this._vertexData[offset + 10] = offsetY;
  40912. this._vertexData[offset + 11] = intertU;
  40913. this._vertexData[offset + 12] = interV;
  40914. this._vertexData[offset + 13] = columnOffset;
  40915. this._vertexData[offset + 14] = rowOffset;
  40916. };
  40917. ParticleSystem.prototype._update = function (newParticles) {
  40918. // Update current
  40919. this._alive = this.particles.length > 0;
  40920. this.updateFunction(this.particles);
  40921. // Add new ones
  40922. var worldMatrix;
  40923. if (this.emitter.position) {
  40924. var emitterMesh = this.emitter;
  40925. worldMatrix = emitterMesh.getWorldMatrix();
  40926. }
  40927. else {
  40928. var emitterPosition = this.emitter;
  40929. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  40930. }
  40931. var particle;
  40932. for (var index = 0; index < newParticles; index++) {
  40933. if (this.particles.length === this._capacity) {
  40934. break;
  40935. }
  40936. if (this._stockParticles.length !== 0) {
  40937. particle = this._stockParticles.pop();
  40938. particle.age = 0;
  40939. particle.cellIndex = this._fromIndex;
  40940. }
  40941. else {
  40942. if (this.cellSize) {
  40943. particle = new BABYLON.Particle(this, this.cellIndex, this.invertU, this.invertV, this._loopAnimation, this._fromIndex, this._toIndex, this._delay, this._sheetDirection, this._time, this.disposeParticlesWhenFinishedAnimating);
  40944. }
  40945. else {
  40946. particle = new BABYLON.Particle(this);
  40947. }
  40948. }
  40949. this.particles.push(particle);
  40950. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  40951. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  40952. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  40953. particle.size = randomNumber(this.minSize, this.maxSize);
  40954. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  40955. this.startPositionFunction(worldMatrix, particle.position, particle);
  40956. var step = randomNumber(0, 1.0);
  40957. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  40958. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  40959. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  40960. }
  40961. };
  40962. ParticleSystem.prototype._getEffect = function () {
  40963. if (this._customEffect) {
  40964. return this._customEffect;
  40965. }
  40966. ;
  40967. var defines = [];
  40968. if (this._scene.clipPlane) {
  40969. defines.push("#define CLIPPLANE");
  40970. }
  40971. if (this.cellSize) {
  40972. defines.push("#define ANIMATESHEET");
  40973. }
  40974. // Effect
  40975. var join = defines.join("\n");
  40976. if (this._cachedDefines !== join) {
  40977. this._cachedDefines = join;
  40978. var attributesNamesOrOptions;
  40979. var effectCreationOption;
  40980. if (this.cellSize) {
  40981. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellInfo"];
  40982. effectCreationOption = ["invView", "view", "projection", "textureInfos", "vClipPlane", "textureMask"];
  40983. }
  40984. else {
  40985. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  40986. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  40987. }
  40988. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  40989. }
  40990. return this._effect;
  40991. };
  40992. ParticleSystem.prototype.animate = function () {
  40993. if (!this._started)
  40994. return;
  40995. var effect = this._getEffect();
  40996. // Check
  40997. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  40998. return;
  40999. if (this._currentRenderId === this._scene.getRenderId()) {
  41000. return;
  41001. }
  41002. this._currentRenderId = this._scene.getRenderId();
  41003. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  41004. // determine the number of particles we need to create
  41005. var newParticles;
  41006. if (this.manualEmitCount > -1) {
  41007. newParticles = this.manualEmitCount;
  41008. this._newPartsExcess = 0;
  41009. this.manualEmitCount = 0;
  41010. }
  41011. else {
  41012. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  41013. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  41014. }
  41015. if (this._newPartsExcess > 1.0) {
  41016. newParticles += this._newPartsExcess >> 0;
  41017. this._newPartsExcess -= this._newPartsExcess >> 0;
  41018. }
  41019. this._alive = false;
  41020. if (!this._stopped) {
  41021. this._actualFrame += this._scaledUpdateSpeed;
  41022. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  41023. this.stop();
  41024. }
  41025. else {
  41026. newParticles = 0;
  41027. }
  41028. this._update(newParticles);
  41029. // Stopped?
  41030. if (this._stopped) {
  41031. if (!this._alive) {
  41032. this._started = false;
  41033. if (this.onAnimationEnd) {
  41034. this.onAnimationEnd();
  41035. }
  41036. if (this.disposeOnStop) {
  41037. this._scene._toBeDisposed.push(this);
  41038. }
  41039. }
  41040. }
  41041. // Animation sheet
  41042. var rowSize = 0;
  41043. if (this.cellSize) {
  41044. var baseSize = this.particleTexture.getBaseSize();
  41045. rowSize = baseSize.width / this.cellWidth;
  41046. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  41047. }
  41048. else {
  41049. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  41050. }
  41051. // Update VBO
  41052. var offset = 0;
  41053. for (var index = 0; index < this.particles.length; index++) {
  41054. var particle = this.particles[index];
  41055. this.appendParticleVertexes(offset, particle, rowSize);
  41056. offset += 4;
  41057. }
  41058. this._vertexBuffer.update(this._vertexData);
  41059. };
  41060. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle, rowSize) {
  41061. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0, rowSize);
  41062. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0, rowSize);
  41063. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1, rowSize);
  41064. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1, rowSize);
  41065. };
  41066. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle, rowSize) {
  41067. this._appendParticleVertex(offset++, particle, 0, 0);
  41068. this._appendParticleVertex(offset++, particle, 1, 0);
  41069. this._appendParticleVertex(offset++, particle, 1, 1);
  41070. this._appendParticleVertex(offset++, particle, 0, 1);
  41071. };
  41072. ParticleSystem.prototype.rebuild = function () {
  41073. this._createIndexBuffer();
  41074. this._vertexBuffer._rebuild();
  41075. };
  41076. ParticleSystem.prototype.render = function () {
  41077. var effect = this._getEffect();
  41078. // Check
  41079. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  41080. return 0;
  41081. var engine = this._scene.getEngine();
  41082. // Render
  41083. engine.enableEffect(effect);
  41084. engine.setState(false);
  41085. var viewMatrix = this._scene.getViewMatrix();
  41086. effect.setTexture("diffuseSampler", this.particleTexture);
  41087. effect.setMatrix("view", viewMatrix);
  41088. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  41089. if (this.cellSize) {
  41090. var baseSize = this.particleTexture.getBaseSize();
  41091. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  41092. }
  41093. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  41094. if (this._scene.clipPlane) {
  41095. var clipPlane = this._scene.clipPlane;
  41096. var invView = viewMatrix.clone();
  41097. invView.invert();
  41098. effect.setMatrix("invView", invView);
  41099. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41100. }
  41101. // VBOs
  41102. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  41103. // Draw order
  41104. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  41105. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  41106. }
  41107. else {
  41108. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  41109. }
  41110. if (this.forceDepthWrite) {
  41111. engine.setDepthWrite(true);
  41112. }
  41113. engine.draw(true, 0, this.particles.length * 6);
  41114. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  41115. return this.particles.length;
  41116. };
  41117. ParticleSystem.prototype.dispose = function () {
  41118. if (this._vertexBuffer) {
  41119. this._vertexBuffer.dispose();
  41120. this._vertexBuffer = null;
  41121. }
  41122. if (this._indexBuffer) {
  41123. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  41124. this._indexBuffer = null;
  41125. }
  41126. if (this.particleTexture) {
  41127. this.particleTexture.dispose();
  41128. this.particleTexture = null;
  41129. }
  41130. // Remove from scene
  41131. var index = this._scene.particleSystems.indexOf(this);
  41132. if (index > -1) {
  41133. this._scene.particleSystems.splice(index, 1);
  41134. }
  41135. // Callback
  41136. this.onDisposeObservable.notifyObservers(this);
  41137. this.onDisposeObservable.clear();
  41138. };
  41139. // Clone
  41140. ParticleSystem.prototype.clone = function (name, newEmitter) {
  41141. var custom = null;
  41142. var program = null;
  41143. if (this.customShader != null) {
  41144. program = this.customShader;
  41145. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  41146. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  41147. }
  41148. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  41149. result.customShader = program;
  41150. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  41151. if (newEmitter === undefined) {
  41152. newEmitter = this.emitter;
  41153. }
  41154. result.emitter = newEmitter;
  41155. if (this.particleTexture) {
  41156. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  41157. }
  41158. if (!this.preventAutoStart) {
  41159. result.start();
  41160. }
  41161. return result;
  41162. };
  41163. ParticleSystem.prototype.serialize = function () {
  41164. var serializationObject = {};
  41165. serializationObject.name = this.name;
  41166. serializationObject.id = this.id;
  41167. // Emitter
  41168. if (this.emitter.position) {
  41169. var emitterMesh = this.emitter;
  41170. serializationObject.emitterId = emitterMesh.id;
  41171. }
  41172. else {
  41173. var emitterPosition = this.emitter;
  41174. serializationObject.emitter = emitterPosition.asArray();
  41175. }
  41176. serializationObject.capacity = this.getCapacity();
  41177. if (this.particleTexture) {
  41178. serializationObject.textureName = this.particleTexture.name;
  41179. }
  41180. // Animations
  41181. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  41182. // Particle system
  41183. serializationObject.minAngularSpeed = this.minAngularSpeed;
  41184. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  41185. serializationObject.minSize = this.minSize;
  41186. serializationObject.maxSize = this.maxSize;
  41187. serializationObject.minEmitPower = this.minEmitPower;
  41188. serializationObject.maxEmitPower = this.maxEmitPower;
  41189. serializationObject.minLifeTime = this.minLifeTime;
  41190. serializationObject.maxLifeTime = this.maxLifeTime;
  41191. serializationObject.emitRate = this.emitRate;
  41192. serializationObject.minEmitBox = this.minEmitBox.asArray();
  41193. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  41194. serializationObject.gravity = this.gravity.asArray();
  41195. serializationObject.direction1 = this.direction1.asArray();
  41196. serializationObject.direction2 = this.direction2.asArray();
  41197. serializationObject.color1 = this.color1.asArray();
  41198. serializationObject.color2 = this.color2.asArray();
  41199. serializationObject.colorDead = this.colorDead.asArray();
  41200. serializationObject.updateSpeed = this.updateSpeed;
  41201. serializationObject.targetStopDuration = this.targetStopDuration;
  41202. serializationObject.textureMask = this.textureMask.asArray();
  41203. serializationObject.blendMode = this.blendMode;
  41204. serializationObject.customShader = this.customShader;
  41205. serializationObject.preventAutoStart = this.preventAutoStart;
  41206. return serializationObject;
  41207. };
  41208. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  41209. var name = parsedParticleSystem.name;
  41210. var custom = null;
  41211. var program = null;
  41212. if (parsedParticleSystem.customShader) {
  41213. program = parsedParticleSystem.customShader;
  41214. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  41215. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  41216. }
  41217. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  41218. particleSystem.customShader = program;
  41219. if (parsedParticleSystem.id) {
  41220. particleSystem.id = parsedParticleSystem.id;
  41221. }
  41222. // Auto start
  41223. if (parsedParticleSystem.preventAutoStart) {
  41224. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  41225. }
  41226. // Texture
  41227. if (parsedParticleSystem.textureName) {
  41228. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  41229. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  41230. }
  41231. // Emitter
  41232. if (parsedParticleSystem.emitterId) {
  41233. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  41234. }
  41235. else {
  41236. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  41237. }
  41238. // Animations
  41239. if (parsedParticleSystem.animations) {
  41240. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  41241. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  41242. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  41243. }
  41244. }
  41245. if (parsedParticleSystem.autoAnimate) {
  41246. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  41247. }
  41248. // Particle system
  41249. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  41250. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  41251. particleSystem.minSize = parsedParticleSystem.minSize;
  41252. particleSystem.maxSize = parsedParticleSystem.maxSize;
  41253. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  41254. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  41255. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  41256. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  41257. particleSystem.emitRate = parsedParticleSystem.emitRate;
  41258. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  41259. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  41260. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  41261. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  41262. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  41263. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  41264. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  41265. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  41266. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  41267. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  41268. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  41269. particleSystem.blendMode = parsedParticleSystem.blendMode;
  41270. if (!particleSystem.preventAutoStart) {
  41271. particleSystem.start();
  41272. }
  41273. return particleSystem;
  41274. };
  41275. // Statics
  41276. ParticleSystem.BLENDMODE_ONEONE = 0;
  41277. ParticleSystem.BLENDMODE_STANDARD = 1;
  41278. return ParticleSystem;
  41279. }());
  41280. BABYLON.ParticleSystem = ParticleSystem;
  41281. })(BABYLON || (BABYLON = {}));
  41282. //# sourceMappingURL=babylon.particleSystem.js.map
  41283. var BABYLON;
  41284. (function (BABYLON) {
  41285. var SolidParticle = (function () {
  41286. /**
  41287. * Creates a Solid Particle object.
  41288. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  41289. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  41290. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  41291. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  41292. * `shapeId` (integer) is the model shape identifier in the SPS.
  41293. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  41294. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  41295. */
  41296. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  41297. this.idx = 0; // particle global index
  41298. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  41299. this.position = BABYLON.Vector3.Zero(); // position
  41300. this.rotation = BABYLON.Vector3.Zero(); // rotation
  41301. this.scaling = BABYLON.Vector3.One(); // scaling
  41302. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  41303. this.velocity = BABYLON.Vector3.Zero(); // velocity
  41304. this.alive = true; // alive
  41305. this.isVisible = true; // visibility
  41306. this._pos = 0; // index of this particle in the global "positions" array
  41307. this.shapeId = 0; // model shape id
  41308. this.idxInShape = 0; // index of the particle in its shape id
  41309. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  41310. this.idx = particleIndex;
  41311. this._pos = positionIndex;
  41312. this._model = model;
  41313. this.shapeId = shapeId;
  41314. this.idxInShape = idxInShape;
  41315. this._sps = sps;
  41316. if (modelBoundingInfo) {
  41317. this._modelBoundingInfo = modelBoundingInfo;
  41318. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  41319. }
  41320. }
  41321. Object.defineProperty(SolidParticle.prototype, "scale", {
  41322. /**
  41323. * legacy support, changed scale to scaling
  41324. */
  41325. get: function () {
  41326. return this.scaling;
  41327. },
  41328. set: function (scale) {
  41329. this.scaling = scale;
  41330. },
  41331. enumerable: true,
  41332. configurable: true
  41333. });
  41334. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  41335. /**
  41336. * legacy support, changed quaternion to rotationQuaternion
  41337. */
  41338. get: function () {
  41339. return this.rotationQuaternion;
  41340. },
  41341. set: function (q) {
  41342. this.rotationQuaternion = q;
  41343. },
  41344. enumerable: true,
  41345. configurable: true
  41346. });
  41347. /**
  41348. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  41349. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  41350. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  41351. */
  41352. SolidParticle.prototype.intersectsMesh = function (target) {
  41353. if (!this._boundingInfo || !target._boundingInfo) {
  41354. return false;
  41355. }
  41356. if (this._sps._bSphereOnly) {
  41357. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  41358. }
  41359. return this._boundingInfo.intersects(target._boundingInfo, false);
  41360. };
  41361. return SolidParticle;
  41362. }());
  41363. BABYLON.SolidParticle = SolidParticle;
  41364. var ModelShape = (function () {
  41365. /**
  41366. * 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.
  41367. * SPS internal tool, don't use it manually.
  41368. */
  41369. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  41370. this.shapeID = id;
  41371. this._shape = shape;
  41372. this._shapeUV = shapeUV;
  41373. this._positionFunction = posFunction;
  41374. this._vertexFunction = vtxFunction;
  41375. }
  41376. return ModelShape;
  41377. }());
  41378. BABYLON.ModelShape = ModelShape;
  41379. })(BABYLON || (BABYLON = {}));
  41380. //# sourceMappingURL=babylon.solidParticle.js.map
  41381. var BABYLON;
  41382. (function (BABYLON) {
  41383. /**
  41384. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  41385. */
  41386. var SolidParticleSystem = (function () {
  41387. /**
  41388. * Creates a SPS (Solid Particle System) object.
  41389. * `name` (String) is the SPS name, this will be the underlying mesh name.
  41390. * `scene` (Scene) is the scene in which the SPS is added.
  41391. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  41392. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  41393. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  41394. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  41395. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  41396. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  41397. */
  41398. function SolidParticleSystem(name, scene, options) {
  41399. // public members
  41400. /**
  41401. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  41402. * Example : var p = SPS.particles[i];
  41403. */
  41404. this.particles = new Array();
  41405. /**
  41406. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  41407. */
  41408. this.nbParticles = 0;
  41409. /**
  41410. * If the particles must ever face the camera (default false). Useful for planar particles.
  41411. */
  41412. this.billboard = false;
  41413. /**
  41414. * Recompute normals when adding a shape
  41415. */
  41416. this.recomputeNormals = true;
  41417. /**
  41418. * This a counter ofr your own usage. It's not set by any SPS functions.
  41419. */
  41420. this.counter = 0;
  41421. /**
  41422. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  41423. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  41424. */
  41425. this.vars = {};
  41426. this._positions = new Array();
  41427. this._indices = new Array();
  41428. this._normals = new Array();
  41429. this._colors = new Array();
  41430. this._uvs = new Array();
  41431. this._index = 0; // indices index
  41432. this._updatable = true;
  41433. this._pickable = false;
  41434. this._isVisibilityBoxLocked = false;
  41435. this._alwaysVisible = false;
  41436. this._shapeCounter = 0;
  41437. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  41438. this._color = new BABYLON.Color4(0, 0, 0, 0);
  41439. this._computeParticleColor = true;
  41440. this._computeParticleTexture = true;
  41441. this._computeParticleRotation = true;
  41442. this._computeParticleVertex = false;
  41443. this._computeBoundingBox = false;
  41444. this._cam_axisZ = BABYLON.Vector3.Zero();
  41445. this._cam_axisY = BABYLON.Vector3.Zero();
  41446. this._cam_axisX = BABYLON.Vector3.Zero();
  41447. this._axisX = BABYLON.Axis.X;
  41448. this._axisY = BABYLON.Axis.Y;
  41449. this._axisZ = BABYLON.Axis.Z;
  41450. this._camDir = BABYLON.Vector3.Zero();
  41451. this._rotMatrix = new BABYLON.Matrix();
  41452. this._invertMatrix = new BABYLON.Matrix();
  41453. this._rotated = BABYLON.Vector3.Zero();
  41454. this._quaternion = new BABYLON.Quaternion();
  41455. this._vertex = BABYLON.Vector3.Zero();
  41456. this._normal = BABYLON.Vector3.Zero();
  41457. this._yaw = 0.0;
  41458. this._pitch = 0.0;
  41459. this._roll = 0.0;
  41460. this._halfroll = 0.0;
  41461. this._halfpitch = 0.0;
  41462. this._halfyaw = 0.0;
  41463. this._sinRoll = 0.0;
  41464. this._cosRoll = 0.0;
  41465. this._sinPitch = 0.0;
  41466. this._cosPitch = 0.0;
  41467. this._sinYaw = 0.0;
  41468. this._cosYaw = 0.0;
  41469. this._w = 0.0;
  41470. this._mustUnrotateFixedNormals = false;
  41471. this._minimum = BABYLON.Tmp.Vector3[0];
  41472. this._maximum = BABYLON.Tmp.Vector3[1];
  41473. this._scale = BABYLON.Tmp.Vector3[2];
  41474. this._translation = BABYLON.Tmp.Vector3[3];
  41475. this._minBbox = BABYLON.Tmp.Vector3[4];
  41476. this._maxBbox = BABYLON.Tmp.Vector3[5];
  41477. this._particlesIntersect = false;
  41478. this._bSphereOnly = false;
  41479. this._bSphereRadiusFactor = 1.0;
  41480. this.name = name;
  41481. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  41482. this._camera = scene.activeCamera;
  41483. this._pickable = options ? options.isPickable : false;
  41484. this._particlesIntersect = options ? options.particleIntersection : false;
  41485. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  41486. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  41487. if (options && options.updatable) {
  41488. this._updatable = options.updatable;
  41489. }
  41490. else {
  41491. this._updatable = true;
  41492. }
  41493. if (this._pickable) {
  41494. this.pickedParticles = [];
  41495. }
  41496. }
  41497. /**
  41498. * Builds the SPS underlying mesh. Returns a standard Mesh.
  41499. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  41500. */
  41501. SolidParticleSystem.prototype.buildMesh = function () {
  41502. if (this.nbParticles === 0) {
  41503. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  41504. this.addShape(triangle, 1);
  41505. triangle.dispose();
  41506. }
  41507. this._positions32 = new Float32Array(this._positions);
  41508. this._uvs32 = new Float32Array(this._uvs);
  41509. this._colors32 = new Float32Array(this._colors);
  41510. if (this.recomputeNormals) {
  41511. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  41512. }
  41513. this._normals32 = new Float32Array(this._normals);
  41514. this._fixedNormal32 = new Float32Array(this._normals);
  41515. if (this._mustUnrotateFixedNormals) {
  41516. this._unrotateFixedNormals();
  41517. }
  41518. var vertexData = new BABYLON.VertexData();
  41519. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  41520. vertexData.indices = this._indices;
  41521. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  41522. if (this._uvs32) {
  41523. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  41524. ;
  41525. }
  41526. if (this._colors32) {
  41527. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  41528. }
  41529. var mesh = new BABYLON.Mesh(this.name, this._scene);
  41530. vertexData.applyToMesh(mesh, this._updatable);
  41531. this.mesh = mesh;
  41532. this.mesh.isPickable = this._pickable;
  41533. // free memory
  41534. this._positions = null;
  41535. this._normals = null;
  41536. this._uvs = null;
  41537. this._colors = null;
  41538. if (!this._updatable) {
  41539. this.particles.length = 0;
  41540. }
  41541. return mesh;
  41542. };
  41543. /**
  41544. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  41545. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  41546. * Thus the particles generated from `digest()` have their property `position` set yet.
  41547. * `mesh` ( Mesh ) is the mesh to be digested
  41548. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  41549. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  41550. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  41551. */
  41552. SolidParticleSystem.prototype.digest = function (mesh, options) {
  41553. var size = (options && options.facetNb) || 1;
  41554. var number = (options && options.number);
  41555. var delta = (options && options.delta) || 0;
  41556. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41557. var meshInd = mesh.getIndices();
  41558. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41559. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41560. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41561. var f = 0; // facet counter
  41562. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  41563. // compute size from number
  41564. if (number) {
  41565. number = (number > totalFacets) ? totalFacets : number;
  41566. size = Math.round(totalFacets / number);
  41567. delta = 0;
  41568. }
  41569. else {
  41570. size = (size > totalFacets) ? totalFacets : size;
  41571. }
  41572. var facetPos = []; // submesh positions
  41573. var facetInd = []; // submesh indices
  41574. var facetUV = []; // submesh UV
  41575. var facetCol = []; // submesh colors
  41576. var barycenter = BABYLON.Tmp.Vector3[0];
  41577. var rand;
  41578. var sizeO = size;
  41579. while (f < totalFacets) {
  41580. size = sizeO + Math.floor((1 + delta) * Math.random());
  41581. if (f > totalFacets - size) {
  41582. size = totalFacets - f;
  41583. }
  41584. // reset temp arrays
  41585. facetPos.length = 0;
  41586. facetInd.length = 0;
  41587. facetUV.length = 0;
  41588. facetCol.length = 0;
  41589. // iterate over "size" facets
  41590. var fi = 0;
  41591. for (var j = f * 3; j < (f + size) * 3; j++) {
  41592. facetInd.push(fi);
  41593. var i = meshInd[j];
  41594. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  41595. if (meshUV) {
  41596. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  41597. }
  41598. if (meshCol) {
  41599. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  41600. }
  41601. fi++;
  41602. }
  41603. // create a model shape for each single particle
  41604. var idx = this.nbParticles;
  41605. var shape = this._posToShape(facetPos);
  41606. var shapeUV = this._uvsToShapeUV(facetUV);
  41607. // compute the barycenter of the shape
  41608. var v;
  41609. for (v = 0; v < shape.length; v++) {
  41610. barycenter.addInPlace(shape[v]);
  41611. }
  41612. barycenter.scaleInPlace(1 / shape.length);
  41613. // shift the shape from its barycenter to the origin
  41614. for (v = 0; v < shape.length; v++) {
  41615. shape[v].subtractInPlace(barycenter);
  41616. }
  41617. var bInfo;
  41618. if (this._particlesIntersect) {
  41619. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  41620. }
  41621. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  41622. // add the particle in the SPS
  41623. var currentPos = this._positions.length;
  41624. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  41625. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  41626. // initialize the particle position
  41627. this.particles[this.nbParticles].position.addInPlace(barycenter);
  41628. this._index += shape.length;
  41629. idx++;
  41630. this.nbParticles++;
  41631. this._shapeCounter++;
  41632. f += size;
  41633. }
  41634. return this;
  41635. };
  41636. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  41637. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  41638. var index = 0;
  41639. var idx = 0;
  41640. for (var p = 0; p < this.particles.length; p++) {
  41641. this._particle = this.particles[p];
  41642. this._shape = this._particle._model._shape;
  41643. if (this._particle.rotationQuaternion) {
  41644. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  41645. }
  41646. else {
  41647. this._yaw = this._particle.rotation.y;
  41648. this._pitch = this._particle.rotation.x;
  41649. this._roll = this._particle.rotation.z;
  41650. this._quaternionRotationYPR();
  41651. }
  41652. this._quaternionToRotationMatrix();
  41653. this._rotMatrix.invertToRef(this._invertMatrix);
  41654. for (var pt = 0; pt < this._shape.length; pt++) {
  41655. idx = index + pt * 3;
  41656. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  41657. this._fixedNormal32[idx] = this._normal.x;
  41658. this._fixedNormal32[idx + 1] = this._normal.y;
  41659. this._fixedNormal32[idx + 2] = this._normal.z;
  41660. }
  41661. index = idx + 3;
  41662. }
  41663. };
  41664. //reset copy
  41665. SolidParticleSystem.prototype._resetCopy = function () {
  41666. this._copy.position.x = 0;
  41667. this._copy.position.y = 0;
  41668. this._copy.position.z = 0;
  41669. this._copy.rotation.x = 0;
  41670. this._copy.rotation.y = 0;
  41671. this._copy.rotation.z = 0;
  41672. this._copy.rotationQuaternion = null;
  41673. this._copy.scaling.x = 1;
  41674. this._copy.scaling.y = 1;
  41675. this._copy.scaling.z = 1;
  41676. this._copy.uvs.x = 0;
  41677. this._copy.uvs.y = 0;
  41678. this._copy.uvs.z = 1;
  41679. this._copy.uvs.w = 1;
  41680. this._copy.color = null;
  41681. };
  41682. // _meshBuilder : inserts the shape model in the global SPS mesh
  41683. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  41684. var i;
  41685. var u = 0;
  41686. var c = 0;
  41687. var n = 0;
  41688. this._resetCopy();
  41689. if (options && options.positionFunction) {
  41690. options.positionFunction(this._copy, idx, idxInShape);
  41691. this._mustUnrotateFixedNormals = true;
  41692. }
  41693. if (this._copy.rotationQuaternion) {
  41694. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41695. }
  41696. else {
  41697. this._yaw = this._copy.rotation.y;
  41698. this._pitch = this._copy.rotation.x;
  41699. this._roll = this._copy.rotation.z;
  41700. this._quaternionRotationYPR();
  41701. }
  41702. this._quaternionToRotationMatrix();
  41703. for (i = 0; i < shape.length; i++) {
  41704. this._vertex.x = shape[i].x;
  41705. this._vertex.y = shape[i].y;
  41706. this._vertex.z = shape[i].z;
  41707. if (options && options.vertexFunction) {
  41708. options.vertexFunction(this._copy, this._vertex, i);
  41709. }
  41710. this._vertex.x *= this._copy.scaling.x;
  41711. this._vertex.y *= this._copy.scaling.y;
  41712. this._vertex.z *= this._copy.scaling.z;
  41713. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41714. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  41715. if (meshUV) {
  41716. 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);
  41717. u += 2;
  41718. }
  41719. if (this._copy.color) {
  41720. this._color = this._copy.color;
  41721. }
  41722. else if (meshCol && meshCol[c] !== undefined) {
  41723. this._color.r = meshCol[c];
  41724. this._color.g = meshCol[c + 1];
  41725. this._color.b = meshCol[c + 2];
  41726. this._color.a = meshCol[c + 3];
  41727. }
  41728. else {
  41729. this._color.r = 1;
  41730. this._color.g = 1;
  41731. this._color.b = 1;
  41732. this._color.a = 1;
  41733. }
  41734. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  41735. c += 4;
  41736. if (!this.recomputeNormals && meshNor) {
  41737. this._normal.x = meshNor[n];
  41738. this._normal.y = meshNor[n + 1];
  41739. this._normal.z = meshNor[n + 2];
  41740. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  41741. normals.push(this._normal.x, this._normal.y, this._normal.z);
  41742. n += 3;
  41743. }
  41744. }
  41745. for (i = 0; i < meshInd.length; i++) {
  41746. indices.push(p + meshInd[i]);
  41747. }
  41748. if (this._pickable) {
  41749. var nbfaces = meshInd.length / 3;
  41750. for (i = 0; i < nbfaces; i++) {
  41751. this.pickedParticles.push({ idx: idx, faceId: i });
  41752. }
  41753. }
  41754. return this._copy;
  41755. };
  41756. // returns a shape array from positions array
  41757. SolidParticleSystem.prototype._posToShape = function (positions) {
  41758. var shape = [];
  41759. for (var i = 0; i < positions.length; i += 3) {
  41760. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  41761. }
  41762. return shape;
  41763. };
  41764. // returns a shapeUV array from a Vector4 uvs
  41765. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  41766. var shapeUV = [];
  41767. if (uvs) {
  41768. for (var i = 0; i < uvs.length; i++)
  41769. shapeUV.push(uvs[i]);
  41770. }
  41771. return shapeUV;
  41772. };
  41773. // adds a new particle object in the particles array
  41774. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  41775. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  41776. this.particles.push(sp);
  41777. return sp;
  41778. };
  41779. /**
  41780. * Adds some particles to the SPS from the model shape. Returns the shape id.
  41781. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  41782. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  41783. * `nb` (positive integer) the number of particles to be created from this model
  41784. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  41785. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  41786. */
  41787. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  41788. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41789. var meshInd = mesh.getIndices();
  41790. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41791. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41792. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41793. var bbInfo;
  41794. if (this._particlesIntersect) {
  41795. bbInfo = mesh.getBoundingInfo();
  41796. }
  41797. var shape = this._posToShape(meshPos);
  41798. var shapeUV = this._uvsToShapeUV(meshUV);
  41799. var posfunc = options ? options.positionFunction : null;
  41800. var vtxfunc = options ? options.vertexFunction : null;
  41801. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  41802. // particles
  41803. var sp;
  41804. var currentCopy;
  41805. var idx = this.nbParticles;
  41806. for (var i = 0; i < nb; i++) {
  41807. var currentPos = this._positions.length;
  41808. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  41809. if (this._updatable) {
  41810. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  41811. sp.position.copyFrom(currentCopy.position);
  41812. sp.rotation.copyFrom(currentCopy.rotation);
  41813. if (currentCopy.rotationQuaternion) {
  41814. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  41815. }
  41816. if (currentCopy.color) {
  41817. sp.color.copyFrom(currentCopy.color);
  41818. }
  41819. sp.scaling.copyFrom(currentCopy.scaling);
  41820. sp.uvs.copyFrom(currentCopy.uvs);
  41821. }
  41822. this._index += shape.length;
  41823. idx++;
  41824. }
  41825. this.nbParticles += nb;
  41826. this._shapeCounter++;
  41827. return this._shapeCounter - 1;
  41828. };
  41829. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  41830. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  41831. this._resetCopy();
  41832. if (particle._model._positionFunction) {
  41833. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  41834. }
  41835. if (this._copy.rotationQuaternion) {
  41836. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41837. }
  41838. else {
  41839. this._yaw = this._copy.rotation.y;
  41840. this._pitch = this._copy.rotation.x;
  41841. this._roll = this._copy.rotation.z;
  41842. this._quaternionRotationYPR();
  41843. }
  41844. this._quaternionToRotationMatrix();
  41845. this._shape = particle._model._shape;
  41846. for (var pt = 0; pt < this._shape.length; pt++) {
  41847. this._vertex.x = this._shape[pt].x;
  41848. this._vertex.y = this._shape[pt].y;
  41849. this._vertex.z = this._shape[pt].z;
  41850. if (particle._model._vertexFunction) {
  41851. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  41852. }
  41853. this._vertex.x *= this._copy.scaling.x;
  41854. this._vertex.y *= this._copy.scaling.y;
  41855. this._vertex.z *= this._copy.scaling.z;
  41856. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41857. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  41858. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  41859. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  41860. }
  41861. particle.position.x = 0.0;
  41862. particle.position.y = 0.0;
  41863. particle.position.z = 0.0;
  41864. particle.rotation.x = 0.0;
  41865. particle.rotation.y = 0.0;
  41866. particle.rotation.z = 0.0;
  41867. particle.rotationQuaternion = null;
  41868. particle.scaling.x = 1.0;
  41869. particle.scaling.y = 1.0;
  41870. particle.scaling.z = 1.0;
  41871. };
  41872. /**
  41873. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  41874. * Returns the SPS.
  41875. */
  41876. SolidParticleSystem.prototype.rebuildMesh = function () {
  41877. for (var p = 0; p < this.particles.length; p++) {
  41878. this._rebuildParticle(this.particles[p]);
  41879. }
  41880. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  41881. return this;
  41882. };
  41883. /**
  41884. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  41885. * This method calls `updateParticle()` for each particle of the SPS.
  41886. * For an animated SPS, it is usually called within the render loop.
  41887. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  41888. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  41889. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  41890. * Returns the SPS.
  41891. */
  41892. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  41893. if (start === void 0) { start = 0; }
  41894. if (end === void 0) { end = this.nbParticles - 1; }
  41895. if (update === void 0) { update = true; }
  41896. if (!this._updatable) {
  41897. return;
  41898. }
  41899. // custom beforeUpdate
  41900. this.beforeUpdateParticles(start, end, update);
  41901. this._cam_axisX.x = 1.0;
  41902. this._cam_axisX.y = 0.0;
  41903. this._cam_axisX.z = 0.0;
  41904. this._cam_axisY.x = 0.0;
  41905. this._cam_axisY.y = 1.0;
  41906. this._cam_axisY.z = 0.0;
  41907. this._cam_axisZ.x = 0.0;
  41908. this._cam_axisZ.y = 0.0;
  41909. this._cam_axisZ.z = 1.0;
  41910. // if the particles will always face the camera
  41911. if (this.billboard) {
  41912. this.mesh.computeWorldMatrix(true);
  41913. // compute the camera position and un-rotate it by the current mesh rotation
  41914. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  41915. this._quaternionToRotationMatrix();
  41916. this._rotMatrix.invertToRef(this._invertMatrix);
  41917. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  41918. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  41919. this._cam_axisZ.normalize();
  41920. // same for camera up vector extracted from the cam view matrix
  41921. var view = this._camera.getViewMatrix(true);
  41922. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  41923. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  41924. this._cam_axisY.normalize();
  41925. this._cam_axisX.normalize();
  41926. }
  41927. }
  41928. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  41929. var idx = 0; // current position index in the global array positions32
  41930. var index = 0; // position start index in the global array positions32 of the current particle
  41931. var colidx = 0; // current color index in the global array colors32
  41932. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  41933. var uvidx = 0; // current uv index in the global array uvs32
  41934. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  41935. var pt = 0; // current index in the particle model shape
  41936. if (this.mesh.isFacetDataEnabled) {
  41937. this._computeBoundingBox = true;
  41938. }
  41939. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  41940. if (this._computeBoundingBox) {
  41941. if (start == 0 && end == this.nbParticles - 1) {
  41942. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  41943. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  41944. }
  41945. else {
  41946. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  41947. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  41948. }
  41949. }
  41950. // particle loop
  41951. index = this.particles[start]._pos;
  41952. var vpos = (index / 3) | 0;
  41953. colorIndex = vpos * 4;
  41954. uvIndex = vpos * 2;
  41955. for (var p = start; p <= end; p++) {
  41956. this._particle = this.particles[p];
  41957. this._shape = this._particle._model._shape;
  41958. this._shapeUV = this._particle._model._shapeUV;
  41959. // call to custom user function to update the particle properties
  41960. this.updateParticle(this._particle);
  41961. // skip the computations for inactive or already invisible particles
  41962. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  41963. // increment indexes for the next particle
  41964. pt = this._shape.length;
  41965. index += pt * 3;
  41966. colorIndex += pt * 4;
  41967. uvIndex += pt * 2;
  41968. continue;
  41969. }
  41970. if (this._particle.isVisible) {
  41971. this._particle._stillInvisible = false; // un-mark permanent invisibility
  41972. // particle rotation matrix
  41973. if (this.billboard) {
  41974. this._particle.rotation.x = 0.0;
  41975. this._particle.rotation.y = 0.0;
  41976. }
  41977. if (this._computeParticleRotation || this.billboard) {
  41978. if (this._particle.rotationQuaternion) {
  41979. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  41980. }
  41981. else {
  41982. this._yaw = this._particle.rotation.y;
  41983. this._pitch = this._particle.rotation.x;
  41984. this._roll = this._particle.rotation.z;
  41985. this._quaternionRotationYPR();
  41986. }
  41987. this._quaternionToRotationMatrix();
  41988. }
  41989. // particle vertex loop
  41990. for (pt = 0; pt < this._shape.length; pt++) {
  41991. idx = index + pt * 3;
  41992. colidx = colorIndex + pt * 4;
  41993. uvidx = uvIndex + pt * 2;
  41994. this._vertex.x = this._shape[pt].x;
  41995. this._vertex.y = this._shape[pt].y;
  41996. this._vertex.z = this._shape[pt].z;
  41997. if (this._computeParticleVertex) {
  41998. this.updateParticleVertex(this._particle, this._vertex, pt);
  41999. }
  42000. // positions
  42001. this._vertex.x *= this._particle.scaling.x;
  42002. this._vertex.y *= this._particle.scaling.y;
  42003. this._vertex.z *= this._particle.scaling.z;
  42004. this._w = (this._vertex.x * this._rotMatrix.m[3]) + (this._vertex.y * this._rotMatrix.m[7]) + (this._vertex.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  42005. this._rotated.x = ((this._vertex.x * this._rotMatrix.m[0]) + (this._vertex.y * this._rotMatrix.m[4]) + (this._vertex.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  42006. this._rotated.y = ((this._vertex.x * this._rotMatrix.m[1]) + (this._vertex.y * this._rotMatrix.m[5]) + (this._vertex.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  42007. this._rotated.z = ((this._vertex.x * this._rotMatrix.m[2]) + (this._vertex.y * this._rotMatrix.m[6]) + (this._vertex.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  42008. 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;
  42009. 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;
  42010. 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;
  42011. if (this._computeBoundingBox) {
  42012. if (this._positions32[idx] < this._minimum.x) {
  42013. this._minimum.x = this._positions32[idx];
  42014. }
  42015. if (this._positions32[idx] > this._maximum.x) {
  42016. this._maximum.x = this._positions32[idx];
  42017. }
  42018. if (this._positions32[idx + 1] < this._minimum.y) {
  42019. this._minimum.y = this._positions32[idx + 1];
  42020. }
  42021. if (this._positions32[idx + 1] > this._maximum.y) {
  42022. this._maximum.y = this._positions32[idx + 1];
  42023. }
  42024. if (this._positions32[idx + 2] < this._minimum.z) {
  42025. this._minimum.z = this._positions32[idx + 2];
  42026. }
  42027. if (this._positions32[idx + 2] > this._maximum.z) {
  42028. this._maximum.z = this._positions32[idx + 2];
  42029. }
  42030. }
  42031. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  42032. if (!this._computeParticleVertex) {
  42033. this._normal.x = this._fixedNormal32[idx];
  42034. this._normal.y = this._fixedNormal32[idx + 1];
  42035. this._normal.z = this._fixedNormal32[idx + 2];
  42036. this._rotated.x = ((this._normal.x * this._rotMatrix.m[0]) + (this._normal.y * this._rotMatrix.m[4]) + (this._normal.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]);
  42037. this._rotated.y = ((this._normal.x * this._rotMatrix.m[1]) + (this._normal.y * this._rotMatrix.m[5]) + (this._normal.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]);
  42038. this._rotated.z = ((this._normal.x * this._rotMatrix.m[2]) + (this._normal.y * this._rotMatrix.m[6]) + (this._normal.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]);
  42039. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  42040. 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;
  42041. 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;
  42042. }
  42043. if (this._computeParticleColor) {
  42044. this._colors32[colidx] = this._particle.color.r;
  42045. this._colors32[colidx + 1] = this._particle.color.g;
  42046. this._colors32[colidx + 2] = this._particle.color.b;
  42047. this._colors32[colidx + 3] = this._particle.color.a;
  42048. }
  42049. if (this._computeParticleTexture) {
  42050. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  42051. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  42052. }
  42053. }
  42054. }
  42055. else {
  42056. this._particle._stillInvisible = true; // mark the particle as invisible
  42057. for (pt = 0; pt < this._shape.length; pt++) {
  42058. idx = index + pt * 3;
  42059. colidx = colorIndex + pt * 4;
  42060. uvidx = uvIndex + pt * 2;
  42061. this._positions32[idx] = 0.0;
  42062. this._positions32[idx + 1] = 0.0;
  42063. this._positions32[idx + 2] = 0.0;
  42064. this._normals32[idx] = 0.0;
  42065. this._normals32[idx + 1] = 0.0;
  42066. this._normals32[idx + 2] = 0.0;
  42067. if (this._computeParticleColor) {
  42068. this._colors32[colidx] = this._particle.color.r;
  42069. this._colors32[colidx + 1] = this._particle.color.g;
  42070. this._colors32[colidx + 2] = this._particle.color.b;
  42071. this._colors32[colidx + 3] = this._particle.color.a;
  42072. }
  42073. if (this._computeParticleTexture) {
  42074. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  42075. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  42076. }
  42077. }
  42078. }
  42079. // if the particle intersections must be computed : update the bbInfo
  42080. if (this._particlesIntersect) {
  42081. var bInfo = this._particle._boundingInfo;
  42082. var bBox = bInfo.boundingBox;
  42083. var bSphere = bInfo.boundingSphere;
  42084. if (!this._bSphereOnly) {
  42085. // place, scale and rotate the particle bbox within the SPS local system, then update it
  42086. for (var b = 0; b < bBox.vectors.length; b++) {
  42087. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  42088. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  42089. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  42090. this._w = (this._vertex.x * this._rotMatrix.m[3]) + (this._vertex.y * this._rotMatrix.m[7]) + (this._vertex.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  42091. this._rotated.x = ((this._vertex.x * this._rotMatrix.m[0]) + (this._vertex.y * this._rotMatrix.m[4]) + (this._vertex.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  42092. this._rotated.y = ((this._vertex.x * this._rotMatrix.m[1]) + (this._vertex.y * this._rotMatrix.m[5]) + (this._vertex.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  42093. this._rotated.z = ((this._vertex.x * this._rotMatrix.m[2]) + (this._vertex.y * this._rotMatrix.m[6]) + (this._vertex.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  42094. 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;
  42095. 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;
  42096. 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;
  42097. }
  42098. bBox._update(this.mesh._worldMatrix);
  42099. }
  42100. // place and scale the particle bouding sphere in the SPS local system, then update it
  42101. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  42102. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  42103. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  42104. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  42105. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  42106. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  42107. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  42108. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  42109. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  42110. 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));
  42111. bSphere._update(this.mesh._worldMatrix);
  42112. }
  42113. // increment indexes for the next particle
  42114. index = idx + 3;
  42115. colorIndex = colidx + 4;
  42116. uvIndex = uvidx + 2;
  42117. }
  42118. // if the VBO must be updated
  42119. if (update) {
  42120. if (this._computeParticleColor) {
  42121. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  42122. }
  42123. if (this._computeParticleTexture) {
  42124. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  42125. }
  42126. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  42127. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  42128. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  42129. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  42130. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  42131. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  42132. for (var i = 0; i < this._normals32.length; i++) {
  42133. this._fixedNormal32[i] = this._normals32[i];
  42134. }
  42135. }
  42136. if (!this.mesh.areNormalsFrozen) {
  42137. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  42138. }
  42139. }
  42140. }
  42141. if (this._computeBoundingBox) {
  42142. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  42143. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  42144. }
  42145. this.afterUpdateParticles(start, end, update);
  42146. return this;
  42147. };
  42148. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  42149. this._halfroll = this._roll * 0.5;
  42150. this._halfpitch = this._pitch * 0.5;
  42151. this._halfyaw = this._yaw * 0.5;
  42152. this._sinRoll = Math.sin(this._halfroll);
  42153. this._cosRoll = Math.cos(this._halfroll);
  42154. this._sinPitch = Math.sin(this._halfpitch);
  42155. this._cosPitch = Math.cos(this._halfpitch);
  42156. this._sinYaw = Math.sin(this._halfyaw);
  42157. this._cosYaw = Math.cos(this._halfyaw);
  42158. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  42159. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  42160. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  42161. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  42162. };
  42163. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  42164. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  42165. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  42166. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  42167. this._rotMatrix.m[3] = 0;
  42168. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  42169. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  42170. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  42171. this._rotMatrix.m[7] = 0;
  42172. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  42173. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  42174. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  42175. this._rotMatrix.m[11] = 0;
  42176. this._rotMatrix.m[12] = 0;
  42177. this._rotMatrix.m[13] = 0;
  42178. this._rotMatrix.m[14] = 0;
  42179. this._rotMatrix.m[15] = 1.0;
  42180. };
  42181. /**
  42182. * Disposes the SPS.
  42183. * Returns nothing.
  42184. */
  42185. SolidParticleSystem.prototype.dispose = function () {
  42186. this.mesh.dispose();
  42187. this.vars = null;
  42188. // drop references to internal big arrays for the GC
  42189. this._positions = null;
  42190. this._indices = null;
  42191. this._normals = null;
  42192. this._uvs = null;
  42193. this._colors = null;
  42194. this._positions32 = null;
  42195. this._normals32 = null;
  42196. this._fixedNormal32 = null;
  42197. this._uvs32 = null;
  42198. this._colors32 = null;
  42199. this.pickedParticles = null;
  42200. };
  42201. /**
  42202. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  42203. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42204. * Returns the SPS.
  42205. */
  42206. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  42207. if (!this._isVisibilityBoxLocked) {
  42208. this.mesh.refreshBoundingInfo();
  42209. }
  42210. return this;
  42211. };
  42212. /**
  42213. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  42214. * @param size the size (float) of the visibility box
  42215. * note : this doesn't lock the SPS mesh bounding box.
  42216. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42217. */
  42218. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  42219. var vis = size / 2;
  42220. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  42221. };
  42222. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  42223. // getter and setter
  42224. get: function () {
  42225. return this._alwaysVisible;
  42226. },
  42227. /**
  42228. * Sets the SPS as always visible or not
  42229. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42230. */
  42231. set: function (val) {
  42232. this._alwaysVisible = val;
  42233. this.mesh.alwaysSelectAsActiveMesh = val;
  42234. },
  42235. enumerable: true,
  42236. configurable: true
  42237. });
  42238. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  42239. get: function () {
  42240. return this._isVisibilityBoxLocked;
  42241. },
  42242. /**
  42243. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  42244. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  42245. */
  42246. set: function (val) {
  42247. this._isVisibilityBoxLocked = val;
  42248. this.mesh.getBoundingInfo().isLocked = val;
  42249. },
  42250. enumerable: true,
  42251. configurable: true
  42252. });
  42253. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  42254. // getters
  42255. get: function () {
  42256. return this._computeParticleRotation;
  42257. },
  42258. // Optimizer setters
  42259. /**
  42260. * Tells to `setParticles()` to compute the particle rotations or not.
  42261. * Default value : true. The SPS is faster when it's set to false.
  42262. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  42263. */
  42264. set: function (val) {
  42265. this._computeParticleRotation = val;
  42266. },
  42267. enumerable: true,
  42268. configurable: true
  42269. });
  42270. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  42271. get: function () {
  42272. return this._computeParticleColor;
  42273. },
  42274. /**
  42275. * Tells to `setParticles()` to compute the particle colors or not.
  42276. * Default value : true. The SPS is faster when it's set to false.
  42277. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  42278. */
  42279. set: function (val) {
  42280. this._computeParticleColor = val;
  42281. },
  42282. enumerable: true,
  42283. configurable: true
  42284. });
  42285. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  42286. get: function () {
  42287. return this._computeParticleTexture;
  42288. },
  42289. /**
  42290. * Tells to `setParticles()` to compute the particle textures or not.
  42291. * Default value : true. The SPS is faster when it's set to false.
  42292. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  42293. */
  42294. set: function (val) {
  42295. this._computeParticleTexture = val;
  42296. },
  42297. enumerable: true,
  42298. configurable: true
  42299. });
  42300. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  42301. get: function () {
  42302. return this._computeParticleVertex;
  42303. },
  42304. /**
  42305. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  42306. * Default value : false. The SPS is faster when it's set to false.
  42307. * Note : the particle custom vertex positions aren't stored values.
  42308. */
  42309. set: function (val) {
  42310. this._computeParticleVertex = val;
  42311. },
  42312. enumerable: true,
  42313. configurable: true
  42314. });
  42315. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  42316. get: function () {
  42317. return this._computeBoundingBox;
  42318. },
  42319. /**
  42320. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  42321. */
  42322. set: function (val) {
  42323. this._computeBoundingBox = val;
  42324. },
  42325. enumerable: true,
  42326. configurable: true
  42327. });
  42328. // =======================================================================
  42329. // Particle behavior logic
  42330. // these following methods may be overwritten by the user to fit his needs
  42331. /**
  42332. * This function does nothing. It may be overwritten to set all the particle first values.
  42333. * The SPS doesn't call this function, you may have to call it by your own.
  42334. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  42335. */
  42336. SolidParticleSystem.prototype.initParticles = function () {
  42337. };
  42338. /**
  42339. * This function does nothing. It may be overwritten to recycle a particle.
  42340. * The SPS doesn't call this function, you may have to call it by your own.
  42341. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  42342. */
  42343. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  42344. return particle;
  42345. };
  42346. /**
  42347. * Updates a particle : this function should be overwritten by the user.
  42348. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  42349. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  42350. * ex : just set a particle position or velocity and recycle conditions
  42351. */
  42352. SolidParticleSystem.prototype.updateParticle = function (particle) {
  42353. return particle;
  42354. };
  42355. /**
  42356. * Updates a vertex of a particle : it can be overwritten by the user.
  42357. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  42358. * @param particle the current particle
  42359. * @param vertex the current index of the current particle
  42360. * @param pt the index of the current vertex in the particle shape
  42361. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  42362. * ex : just set a vertex particle position
  42363. */
  42364. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  42365. return vertex;
  42366. };
  42367. /**
  42368. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  42369. * This does nothing and may be overwritten by the user.
  42370. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42371. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42372. * @param update the boolean update value actually passed to setParticles()
  42373. */
  42374. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  42375. };
  42376. /**
  42377. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  42378. * This will be passed three parameters.
  42379. * This does nothing and may be overwritten by the user.
  42380. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42381. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42382. * @param update the boolean update value actually passed to setParticles()
  42383. */
  42384. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  42385. };
  42386. return SolidParticleSystem;
  42387. }());
  42388. BABYLON.SolidParticleSystem = SolidParticleSystem;
  42389. })(BABYLON || (BABYLON = {}));
  42390. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  42391. /// <reference path="babylon.mesh.ts" />
  42392. var BABYLON;
  42393. (function (BABYLON) {
  42394. var GroundMesh = (function (_super) {
  42395. __extends(GroundMesh, _super);
  42396. function GroundMesh(name, scene) {
  42397. var _this = _super.call(this, name, scene) || this;
  42398. _this.generateOctree = false;
  42399. _this._worldInverse = new BABYLON.Matrix();
  42400. return _this;
  42401. }
  42402. GroundMesh.prototype.getClassName = function () {
  42403. return "GroundMesh";
  42404. };
  42405. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  42406. get: function () {
  42407. return Math.min(this._subdivisionsX, this._subdivisionsY);
  42408. },
  42409. enumerable: true,
  42410. configurable: true
  42411. });
  42412. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  42413. get: function () {
  42414. return this._subdivisionsX;
  42415. },
  42416. enumerable: true,
  42417. configurable: true
  42418. });
  42419. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  42420. get: function () {
  42421. return this._subdivisionsY;
  42422. },
  42423. enumerable: true,
  42424. configurable: true
  42425. });
  42426. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  42427. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  42428. this._subdivisionsX = chunksCount;
  42429. this._subdivisionsY = chunksCount;
  42430. this.subdivide(chunksCount);
  42431. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  42432. };
  42433. /**
  42434. * Returns a height (y) value in the Worl system :
  42435. * the ground altitude at the coordinates (x, z) expressed in the World system.
  42436. * Returns the ground y position if (x, z) are outside the ground surface.
  42437. */
  42438. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  42439. var world = this.getWorldMatrix();
  42440. var invMat = BABYLON.Tmp.Matrix[5];
  42441. world.invertToRef(invMat);
  42442. var tmpVect = BABYLON.Tmp.Vector3[8];
  42443. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  42444. x = tmpVect.x;
  42445. z = tmpVect.z;
  42446. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  42447. return this.position.y;
  42448. }
  42449. if (!this._heightQuads || this._heightQuads.length == 0) {
  42450. this._initHeightQuads();
  42451. this._computeHeightQuads();
  42452. }
  42453. var facet = this._getFacetAt(x, z);
  42454. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  42455. // return y in the World system
  42456. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  42457. return tmpVect.y;
  42458. };
  42459. /**
  42460. * Returns a normalized vector (Vector3) orthogonal to the ground
  42461. * at the ground coordinates (x, z) expressed in the World system.
  42462. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  42463. */
  42464. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  42465. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  42466. this.getNormalAtCoordinatesToRef(x, z, normal);
  42467. return normal;
  42468. };
  42469. /**
  42470. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  42471. * at the ground coordinates (x, z) expressed in the World system.
  42472. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  42473. * Returns the GroundMesh.
  42474. */
  42475. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  42476. var world = this.getWorldMatrix();
  42477. var tmpMat = BABYLON.Tmp.Matrix[5];
  42478. world.invertToRef(tmpMat);
  42479. var tmpVect = BABYLON.Tmp.Vector3[8];
  42480. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  42481. x = tmpVect.x;
  42482. z = tmpVect.z;
  42483. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  42484. return this;
  42485. }
  42486. if (!this._heightQuads || this._heightQuads.length == 0) {
  42487. this._initHeightQuads();
  42488. this._computeHeightQuads();
  42489. }
  42490. var facet = this._getFacetAt(x, z);
  42491. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  42492. return this;
  42493. };
  42494. /**
  42495. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  42496. * if the ground has been updated.
  42497. * This can be used in the render loop.
  42498. * Returns the GroundMesh.
  42499. */
  42500. GroundMesh.prototype.updateCoordinateHeights = function () {
  42501. if (!this._heightQuads || this._heightQuads.length == 0) {
  42502. this._initHeightQuads();
  42503. }
  42504. this._computeHeightQuads();
  42505. return this;
  42506. };
  42507. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  42508. GroundMesh.prototype._getFacetAt = function (x, z) {
  42509. // retrieve col and row from x, z coordinates in the ground local system
  42510. var subdivisionsX = this._subdivisionsX;
  42511. var subdivisionsY = this._subdivisionsY;
  42512. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  42513. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  42514. var quad = this._heightQuads[row * this._subdivisionsX + col];
  42515. var facet;
  42516. if (z < quad.slope.x * x + quad.slope.y) {
  42517. facet = quad.facet1;
  42518. }
  42519. else {
  42520. facet = quad.facet2;
  42521. }
  42522. return facet;
  42523. };
  42524. // Creates and populates the heightMap array with "facet" elements :
  42525. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  42526. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  42527. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  42528. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  42529. // Returns the GroundMesh.
  42530. GroundMesh.prototype._initHeightQuads = function () {
  42531. var subdivisionsX = this._subdivisionsX;
  42532. var subdivisionsY = this._subdivisionsY;
  42533. this._heightQuads = new Array();
  42534. for (var row = 0; row < subdivisionsY; row++) {
  42535. for (var col = 0; col < subdivisionsX; col++) {
  42536. 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) };
  42537. this._heightQuads[row * subdivisionsX + col] = quad;
  42538. }
  42539. }
  42540. return this;
  42541. };
  42542. // Compute each quad element values and update the the heightMap array :
  42543. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  42544. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  42545. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  42546. // Returns the GroundMesh.
  42547. GroundMesh.prototype._computeHeightQuads = function () {
  42548. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42549. var v1 = BABYLON.Tmp.Vector3[3];
  42550. var v2 = BABYLON.Tmp.Vector3[2];
  42551. var v3 = BABYLON.Tmp.Vector3[1];
  42552. var v4 = BABYLON.Tmp.Vector3[0];
  42553. var v1v2 = BABYLON.Tmp.Vector3[4];
  42554. var v1v3 = BABYLON.Tmp.Vector3[5];
  42555. var v1v4 = BABYLON.Tmp.Vector3[6];
  42556. var norm1 = BABYLON.Tmp.Vector3[7];
  42557. var norm2 = BABYLON.Tmp.Vector3[8];
  42558. var i = 0;
  42559. var j = 0;
  42560. var k = 0;
  42561. var cd = 0; // 2D slope coefficient : z = cd * x + h
  42562. var h = 0;
  42563. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  42564. var d2 = 0;
  42565. var subdivisionsX = this._subdivisionsX;
  42566. var subdivisionsY = this._subdivisionsY;
  42567. for (var row = 0; row < subdivisionsY; row++) {
  42568. for (var col = 0; col < subdivisionsX; col++) {
  42569. i = col * 3;
  42570. j = row * (subdivisionsX + 1) * 3;
  42571. k = (row + 1) * (subdivisionsX + 1) * 3;
  42572. v1.x = positions[j + i];
  42573. v1.y = positions[j + i + 1];
  42574. v1.z = positions[j + i + 2];
  42575. v2.x = positions[j + i + 3];
  42576. v2.y = positions[j + i + 4];
  42577. v2.z = positions[j + i + 5];
  42578. v3.x = positions[k + i];
  42579. v3.y = positions[k + i + 1];
  42580. v3.z = positions[k + i + 2];
  42581. v4.x = positions[k + i + 3];
  42582. v4.y = positions[k + i + 4];
  42583. v4.z = positions[k + i + 5];
  42584. // 2D slope V1V4
  42585. cd = (v4.z - v1.z) / (v4.x - v1.x);
  42586. h = v1.z - cd * v1.x; // v1 belongs to the slope
  42587. // facet equations :
  42588. // we compute each facet normal vector
  42589. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  42590. // we compute the value d by applying the equation to v1 which belongs to the plane
  42591. // then we store the facet equation in a Vector4
  42592. v2.subtractToRef(v1, v1v2);
  42593. v3.subtractToRef(v1, v1v3);
  42594. v4.subtractToRef(v1, v1v4);
  42595. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  42596. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  42597. norm1.normalize();
  42598. norm2.normalize();
  42599. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  42600. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  42601. var quad = this._heightQuads[row * subdivisionsX + col];
  42602. quad.slope.copyFromFloats(cd, h);
  42603. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  42604. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  42605. }
  42606. }
  42607. return this;
  42608. };
  42609. GroundMesh.prototype.serialize = function (serializationObject) {
  42610. _super.prototype.serialize.call(this, serializationObject);
  42611. serializationObject.subdivisionsX = this._subdivisionsX;
  42612. serializationObject.subdivisionsY = this._subdivisionsY;
  42613. serializationObject.minX = this._minX;
  42614. serializationObject.maxX = this._maxX;
  42615. serializationObject.minZ = this._minZ;
  42616. serializationObject.maxZ = this._maxZ;
  42617. serializationObject.width = this._width;
  42618. serializationObject.height = this._height;
  42619. };
  42620. GroundMesh.Parse = function (parsedMesh, scene) {
  42621. var result = new GroundMesh(parsedMesh.name, scene);
  42622. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  42623. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  42624. result._minX = parsedMesh.minX;
  42625. result._maxX = parsedMesh.maxX;
  42626. result._minZ = parsedMesh.minZ;
  42627. result._maxZ = parsedMesh.maxZ;
  42628. result._width = parsedMesh.width;
  42629. result._height = parsedMesh.height;
  42630. return result;
  42631. };
  42632. return GroundMesh;
  42633. }(BABYLON.Mesh));
  42634. BABYLON.GroundMesh = GroundMesh;
  42635. })(BABYLON || (BABYLON = {}));
  42636. //# sourceMappingURL=babylon.groundMesh.js.map
  42637. var BABYLON;
  42638. (function (BABYLON) {
  42639. /**
  42640. * Creates an instance based on a source mesh.
  42641. */
  42642. var InstancedMesh = (function (_super) {
  42643. __extends(InstancedMesh, _super);
  42644. function InstancedMesh(name, source) {
  42645. var _this = _super.call(this, name, source.getScene()) || this;
  42646. source.instances.push(_this);
  42647. _this._sourceMesh = source;
  42648. _this.position.copyFrom(source.position);
  42649. _this.rotation.copyFrom(source.rotation);
  42650. _this.scaling.copyFrom(source.scaling);
  42651. if (source.rotationQuaternion) {
  42652. _this.rotationQuaternion = source.rotationQuaternion.clone();
  42653. }
  42654. _this.infiniteDistance = source.infiniteDistance;
  42655. _this.setPivotMatrix(source.getPivotMatrix());
  42656. _this.refreshBoundingInfo();
  42657. _this._syncSubMeshes();
  42658. return _this;
  42659. }
  42660. /**
  42661. * Returns the string "InstancedMesh".
  42662. */
  42663. InstancedMesh.prototype.getClassName = function () {
  42664. return "InstancedMesh";
  42665. };
  42666. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  42667. // Methods
  42668. get: function () {
  42669. return this._sourceMesh.receiveShadows;
  42670. },
  42671. enumerable: true,
  42672. configurable: true
  42673. });
  42674. Object.defineProperty(InstancedMesh.prototype, "material", {
  42675. get: function () {
  42676. return this._sourceMesh.material;
  42677. },
  42678. enumerable: true,
  42679. configurable: true
  42680. });
  42681. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  42682. get: function () {
  42683. return this._sourceMesh.visibility;
  42684. },
  42685. enumerable: true,
  42686. configurable: true
  42687. });
  42688. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  42689. get: function () {
  42690. return this._sourceMesh.skeleton;
  42691. },
  42692. enumerable: true,
  42693. configurable: true
  42694. });
  42695. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  42696. get: function () {
  42697. return this._sourceMesh.renderingGroupId;
  42698. },
  42699. enumerable: true,
  42700. configurable: true
  42701. });
  42702. /**
  42703. * Returns the total number of vertices (integer).
  42704. */
  42705. InstancedMesh.prototype.getTotalVertices = function () {
  42706. return this._sourceMesh.getTotalVertices();
  42707. };
  42708. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  42709. get: function () {
  42710. return this._sourceMesh;
  42711. },
  42712. enumerable: true,
  42713. configurable: true
  42714. });
  42715. /**
  42716. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  42717. */
  42718. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  42719. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  42720. };
  42721. /**
  42722. * Sets the vertex data of the mesh geometry for the requested `kind`.
  42723. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  42724. * The `data` are either a numeric array either a Float32Array.
  42725. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  42726. * 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).
  42727. * Note that a new underlying VertexBuffer object is created each call.
  42728. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  42729. *
  42730. * Possible `kind` values :
  42731. * - BABYLON.VertexBuffer.PositionKind
  42732. * - BABYLON.VertexBuffer.UVKind
  42733. * - BABYLON.VertexBuffer.UV2Kind
  42734. * - BABYLON.VertexBuffer.UV3Kind
  42735. * - BABYLON.VertexBuffer.UV4Kind
  42736. * - BABYLON.VertexBuffer.UV5Kind
  42737. * - BABYLON.VertexBuffer.UV6Kind
  42738. * - BABYLON.VertexBuffer.ColorKind
  42739. * - BABYLON.VertexBuffer.MatricesIndicesKind
  42740. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  42741. * - BABYLON.VertexBuffer.MatricesWeightsKind
  42742. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  42743. *
  42744. * Returns the Mesh.
  42745. */
  42746. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  42747. if (this.sourceMesh) {
  42748. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  42749. }
  42750. return this.sourceMesh;
  42751. };
  42752. /**
  42753. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  42754. * If the mesh has no geometry, it is simply returned as it is.
  42755. * The `data` are either a numeric array either a Float32Array.
  42756. * No new underlying VertexBuffer object is created.
  42757. * 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.
  42758. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  42759. *
  42760. * Possible `kind` values :
  42761. * - BABYLON.VertexBuffer.PositionKind
  42762. * - BABYLON.VertexBuffer.UVKind
  42763. * - BABYLON.VertexBuffer.UV2Kind
  42764. * - BABYLON.VertexBuffer.UV3Kind
  42765. * - BABYLON.VertexBuffer.UV4Kind
  42766. * - BABYLON.VertexBuffer.UV5Kind
  42767. * - BABYLON.VertexBuffer.UV6Kind
  42768. * - BABYLON.VertexBuffer.ColorKind
  42769. * - BABYLON.VertexBuffer.MatricesIndicesKind
  42770. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  42771. * - BABYLON.VertexBuffer.MatricesWeightsKind
  42772. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  42773. *
  42774. * Returns the Mesh.
  42775. */
  42776. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  42777. if (this.sourceMesh) {
  42778. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  42779. }
  42780. return this.sourceMesh;
  42781. };
  42782. /**
  42783. * Sets the mesh indices.
  42784. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  42785. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  42786. * This method creates a new index buffer each call.
  42787. * Returns the Mesh.
  42788. */
  42789. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  42790. if (this.sourceMesh) {
  42791. this.sourceMesh.setIndices(indices, totalVertices);
  42792. }
  42793. return this.sourceMesh;
  42794. };
  42795. /**
  42796. * Boolean : True if the mesh owns the requested kind of data.
  42797. */
  42798. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  42799. return this._sourceMesh.isVerticesDataPresent(kind);
  42800. };
  42801. /**
  42802. * Returns an array of indices (IndicesArray).
  42803. */
  42804. InstancedMesh.prototype.getIndices = function () {
  42805. return this._sourceMesh.getIndices();
  42806. };
  42807. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  42808. get: function () {
  42809. return this._sourceMesh._positions;
  42810. },
  42811. enumerable: true,
  42812. configurable: true
  42813. });
  42814. /**
  42815. * Sets a new updated BoundingInfo to the mesh.
  42816. * Returns the mesh.
  42817. */
  42818. InstancedMesh.prototype.refreshBoundingInfo = function () {
  42819. var meshBB = this._sourceMesh.getBoundingInfo();
  42820. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  42821. this._updateBoundingInfo();
  42822. return this;
  42823. };
  42824. InstancedMesh.prototype._preActivate = function () {
  42825. if (this._currentLOD) {
  42826. this._currentLOD._preActivate();
  42827. }
  42828. return this;
  42829. };
  42830. InstancedMesh.prototype._activate = function (renderId) {
  42831. if (this._currentLOD) {
  42832. this._currentLOD._registerInstanceForRenderId(this, renderId);
  42833. }
  42834. return this;
  42835. };
  42836. /**
  42837. * Returns the current associated LOD AbstractMesh.
  42838. */
  42839. InstancedMesh.prototype.getLOD = function (camera) {
  42840. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  42841. if (this._currentLOD === this.sourceMesh) {
  42842. return this;
  42843. }
  42844. return this._currentLOD;
  42845. };
  42846. InstancedMesh.prototype._syncSubMeshes = function () {
  42847. this.releaseSubMeshes();
  42848. if (this._sourceMesh.subMeshes) {
  42849. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  42850. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  42851. }
  42852. }
  42853. return this;
  42854. };
  42855. InstancedMesh.prototype._generatePointsArray = function () {
  42856. return this._sourceMesh._generatePointsArray();
  42857. };
  42858. /**
  42859. * Creates a new InstancedMesh from the current mesh.
  42860. * - name (string) : the cloned mesh name
  42861. * - newParent (optional Node) : the optional Node to parent the clone to.
  42862. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  42863. *
  42864. * Returns the clone.
  42865. */
  42866. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  42867. var result = this._sourceMesh.createInstance(name);
  42868. // Deep copy
  42869. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  42870. // Bounding info
  42871. this.refreshBoundingInfo();
  42872. // Parent
  42873. if (newParent) {
  42874. result.parent = newParent;
  42875. }
  42876. if (!doNotCloneChildren) {
  42877. // Children
  42878. for (var index = 0; index < this.getScene().meshes.length; index++) {
  42879. var mesh = this.getScene().meshes[index];
  42880. if (mesh.parent === this) {
  42881. mesh.clone(mesh.name, result);
  42882. }
  42883. }
  42884. }
  42885. result.computeWorldMatrix(true);
  42886. return result;
  42887. };
  42888. /**
  42889. * Disposes the InstancedMesh.
  42890. * Returns nothing.
  42891. */
  42892. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  42893. // Remove from mesh
  42894. var index = this._sourceMesh.instances.indexOf(this);
  42895. this._sourceMesh.instances.splice(index, 1);
  42896. _super.prototype.dispose.call(this, doNotRecurse);
  42897. };
  42898. return InstancedMesh;
  42899. }(BABYLON.AbstractMesh));
  42900. BABYLON.InstancedMesh = InstancedMesh;
  42901. })(BABYLON || (BABYLON = {}));
  42902. //# sourceMappingURL=babylon.instancedMesh.js.map
  42903. /// <reference path="babylon.mesh.ts" />
  42904. var BABYLON;
  42905. (function (BABYLON) {
  42906. var LinesMesh = (function (_super) {
  42907. __extends(LinesMesh, _super);
  42908. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  42909. if (parent === void 0) { parent = null; }
  42910. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  42911. _this.useVertexColor = useVertexColor;
  42912. _this.color = new BABYLON.Color3(1, 1, 1);
  42913. _this.alpha = 1;
  42914. if (source) {
  42915. _this.color = source.color.clone();
  42916. _this.alpha = source.alpha;
  42917. _this.useVertexColor = source.useVertexColor;
  42918. }
  42919. _this._intersectionThreshold = 0.1;
  42920. var options = {
  42921. attributes: [BABYLON.VertexBuffer.PositionKind],
  42922. uniforms: ["world", "viewProjection"],
  42923. needAlphaBlending: false,
  42924. };
  42925. if (!useVertexColor) {
  42926. options.uniforms.push("color");
  42927. options.needAlphaBlending = true;
  42928. }
  42929. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  42930. return _this;
  42931. }
  42932. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  42933. /**
  42934. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  42935. * This margin is expressed in world space coordinates, so its value may vary.
  42936. * Default value is 0.1
  42937. * @returns the intersection Threshold value.
  42938. */
  42939. get: function () {
  42940. return this._intersectionThreshold;
  42941. },
  42942. /**
  42943. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  42944. * This margin is expressed in world space coordinates, so its value may vary.
  42945. * @param value the new threshold to apply
  42946. */
  42947. set: function (value) {
  42948. if (this._intersectionThreshold === value) {
  42949. return;
  42950. }
  42951. this._intersectionThreshold = value;
  42952. if (this.geometry) {
  42953. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  42954. }
  42955. },
  42956. enumerable: true,
  42957. configurable: true
  42958. });
  42959. /**
  42960. * Returns the string "LineMesh"
  42961. */
  42962. LinesMesh.prototype.getClassName = function () {
  42963. return "LinesMesh";
  42964. };
  42965. Object.defineProperty(LinesMesh.prototype, "material", {
  42966. get: function () {
  42967. return this._colorShader;
  42968. },
  42969. enumerable: true,
  42970. configurable: true
  42971. });
  42972. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  42973. get: function () {
  42974. return false;
  42975. },
  42976. enumerable: true,
  42977. configurable: true
  42978. });
  42979. LinesMesh.prototype.createInstance = function (name) {
  42980. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  42981. return null;
  42982. };
  42983. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  42984. // VBOs
  42985. this._geometry._bind(this._colorShader.getEffect());
  42986. // Color
  42987. if (!this.useVertexColor) {
  42988. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  42989. }
  42990. return this;
  42991. };
  42992. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  42993. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  42994. return this;
  42995. }
  42996. var engine = this.getScene().getEngine();
  42997. // Draw order
  42998. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  42999. return this;
  43000. };
  43001. LinesMesh.prototype.dispose = function (doNotRecurse) {
  43002. this._colorShader.dispose();
  43003. _super.prototype.dispose.call(this, doNotRecurse);
  43004. };
  43005. /**
  43006. * Returns a new LineMesh object cloned from the current one.
  43007. */
  43008. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  43009. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  43010. };
  43011. return LinesMesh;
  43012. }(BABYLON.Mesh));
  43013. BABYLON.LinesMesh = LinesMesh;
  43014. })(BABYLON || (BABYLON = {}));
  43015. //# sourceMappingURL=babylon.linesMesh.js.map
  43016. var BABYLON;
  43017. (function (BABYLON) {
  43018. var ShaderMaterial = (function (_super) {
  43019. __extends(ShaderMaterial, _super);
  43020. function ShaderMaterial(name, scene, shaderPath, options) {
  43021. var _this = _super.call(this, name, scene) || this;
  43022. _this._textures = {};
  43023. _this._textureArrays = {};
  43024. _this._floats = {};
  43025. _this._floatsArrays = {};
  43026. _this._colors3 = {};
  43027. _this._colors3Arrays = {};
  43028. _this._colors4 = {};
  43029. _this._vectors2 = {};
  43030. _this._vectors3 = {};
  43031. _this._vectors4 = {};
  43032. _this._matrices = {};
  43033. _this._matrices3x3 = {};
  43034. _this._matrices2x2 = {};
  43035. _this._vectors3Arrays = {};
  43036. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  43037. _this._shaderPath = shaderPath;
  43038. options.needAlphaBlending = options.needAlphaBlending || false;
  43039. options.needAlphaTesting = options.needAlphaTesting || false;
  43040. options.attributes = options.attributes || ["position", "normal", "uv"];
  43041. options.uniforms = options.uniforms || ["worldViewProjection"];
  43042. options.uniformBuffers = options.uniformBuffers || [];
  43043. options.samplers = options.samplers || [];
  43044. options.defines = options.defines || [];
  43045. _this._options = options;
  43046. return _this;
  43047. }
  43048. ShaderMaterial.prototype.getClassName = function () {
  43049. return "ShaderMaterial";
  43050. };
  43051. ShaderMaterial.prototype.needAlphaBlending = function () {
  43052. return this._options.needAlphaBlending;
  43053. };
  43054. ShaderMaterial.prototype.needAlphaTesting = function () {
  43055. return this._options.needAlphaTesting;
  43056. };
  43057. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  43058. if (this._options.uniforms.indexOf(uniformName) === -1) {
  43059. this._options.uniforms.push(uniformName);
  43060. }
  43061. };
  43062. ShaderMaterial.prototype.setTexture = function (name, texture) {
  43063. if (this._options.samplers.indexOf(name) === -1) {
  43064. this._options.samplers.push(name);
  43065. }
  43066. this._textures[name] = texture;
  43067. return this;
  43068. };
  43069. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  43070. if (this._options.samplers.indexOf(name) === -1) {
  43071. this._options.samplers.push(name);
  43072. }
  43073. this._checkUniform(name);
  43074. this._textureArrays[name] = textures;
  43075. return this;
  43076. };
  43077. ShaderMaterial.prototype.setFloat = function (name, value) {
  43078. this._checkUniform(name);
  43079. this._floats[name] = value;
  43080. return this;
  43081. };
  43082. ShaderMaterial.prototype.setFloats = function (name, value) {
  43083. this._checkUniform(name);
  43084. this._floatsArrays[name] = value;
  43085. return this;
  43086. };
  43087. ShaderMaterial.prototype.setColor3 = function (name, value) {
  43088. this._checkUniform(name);
  43089. this._colors3[name] = value;
  43090. return this;
  43091. };
  43092. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  43093. this._checkUniform(name);
  43094. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  43095. color.toArray(arr, arr.length);
  43096. return arr;
  43097. }, []);
  43098. return this;
  43099. };
  43100. ShaderMaterial.prototype.setColor4 = function (name, value) {
  43101. this._checkUniform(name);
  43102. this._colors4[name] = value;
  43103. return this;
  43104. };
  43105. ShaderMaterial.prototype.setVector2 = function (name, value) {
  43106. this._checkUniform(name);
  43107. this._vectors2[name] = value;
  43108. return this;
  43109. };
  43110. ShaderMaterial.prototype.setVector3 = function (name, value) {
  43111. this._checkUniform(name);
  43112. this._vectors3[name] = value;
  43113. return this;
  43114. };
  43115. ShaderMaterial.prototype.setVector4 = function (name, value) {
  43116. this._checkUniform(name);
  43117. this._vectors4[name] = value;
  43118. return this;
  43119. };
  43120. ShaderMaterial.prototype.setMatrix = function (name, value) {
  43121. this._checkUniform(name);
  43122. this._matrices[name] = value;
  43123. return this;
  43124. };
  43125. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  43126. this._checkUniform(name);
  43127. this._matrices3x3[name] = value;
  43128. return this;
  43129. };
  43130. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  43131. this._checkUniform(name);
  43132. this._matrices2x2[name] = value;
  43133. return this;
  43134. };
  43135. ShaderMaterial.prototype.setArray3 = function (name, value) {
  43136. this._checkUniform(name);
  43137. this._vectors3Arrays[name] = value;
  43138. return this;
  43139. };
  43140. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  43141. if (!mesh) {
  43142. return true;
  43143. }
  43144. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  43145. return false;
  43146. }
  43147. return false;
  43148. };
  43149. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  43150. var scene = this.getScene();
  43151. var engine = scene.getEngine();
  43152. if (!this.checkReadyOnEveryCall) {
  43153. if (this._renderId === scene.getRenderId()) {
  43154. if (this._checkCache(scene, mesh, useInstances)) {
  43155. return true;
  43156. }
  43157. }
  43158. }
  43159. // Instances
  43160. var defines = [];
  43161. var attribs = [];
  43162. var fallbacks = new BABYLON.EffectFallbacks();
  43163. if (useInstances) {
  43164. defines.push("#define INSTANCES");
  43165. }
  43166. for (var index = 0; index < this._options.defines.length; index++) {
  43167. defines.push(this._options.defines[index]);
  43168. }
  43169. for (var index = 0; index < this._options.attributes.length; index++) {
  43170. attribs.push(this._options.attributes[index]);
  43171. }
  43172. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  43173. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43174. defines.push("#define VERTEXCOLOR");
  43175. }
  43176. // Bones
  43177. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  43178. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  43179. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  43180. if (mesh.numBoneInfluencers > 4) {
  43181. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  43182. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  43183. }
  43184. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  43185. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  43186. fallbacks.addCPUSkinningFallback(0, mesh);
  43187. if (this._options.uniforms.indexOf("mBones") === -1) {
  43188. this._options.uniforms.push("mBones");
  43189. }
  43190. }
  43191. else {
  43192. defines.push("#define NUM_BONE_INFLUENCERS 0");
  43193. }
  43194. // Textures
  43195. for (var name in this._textures) {
  43196. if (!this._textures[name].isReady()) {
  43197. return false;
  43198. }
  43199. }
  43200. // Alpha test
  43201. if (engine.getAlphaTesting()) {
  43202. defines.push("#define ALPHATEST");
  43203. }
  43204. var previousEffect = this._effect;
  43205. var join = defines.join("\n");
  43206. this._effect = engine.createEffect(this._shaderPath, {
  43207. attributes: attribs,
  43208. uniformsNames: this._options.uniforms,
  43209. uniformBuffersNames: this._options.uniformBuffers,
  43210. samplers: this._options.samplers,
  43211. defines: join,
  43212. fallbacks: fallbacks,
  43213. onCompiled: this.onCompiled,
  43214. onError: this.onError
  43215. }, engine);
  43216. if (!this._effect.isReady()) {
  43217. return false;
  43218. }
  43219. if (previousEffect !== this._effect) {
  43220. scene.resetCachedMaterial();
  43221. }
  43222. this._renderId = scene.getRenderId();
  43223. return true;
  43224. };
  43225. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  43226. var scene = this.getScene();
  43227. if (this._options.uniforms.indexOf("world") !== -1) {
  43228. this._effect.setMatrix("world", world);
  43229. }
  43230. if (this._options.uniforms.indexOf("worldView") !== -1) {
  43231. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  43232. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  43233. }
  43234. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  43235. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  43236. }
  43237. };
  43238. ShaderMaterial.prototype.bind = function (world, mesh) {
  43239. // Std values
  43240. this.bindOnlyWorldMatrix(world);
  43241. if (this.getScene().getCachedMaterial() !== this) {
  43242. if (this._options.uniforms.indexOf("view") !== -1) {
  43243. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  43244. }
  43245. if (this._options.uniforms.indexOf("projection") !== -1) {
  43246. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  43247. }
  43248. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  43249. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  43250. }
  43251. // Bones
  43252. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  43253. var name;
  43254. // Texture
  43255. for (name in this._textures) {
  43256. this._effect.setTexture(name, this._textures[name]);
  43257. }
  43258. // Texture arrays
  43259. for (name in this._textureArrays) {
  43260. this._effect.setTextureArray(name, this._textureArrays[name]);
  43261. }
  43262. // Float
  43263. for (name in this._floats) {
  43264. this._effect.setFloat(name, this._floats[name]);
  43265. }
  43266. // Float s
  43267. for (name in this._floatsArrays) {
  43268. this._effect.setArray(name, this._floatsArrays[name]);
  43269. }
  43270. // Color3
  43271. for (name in this._colors3) {
  43272. this._effect.setColor3(name, this._colors3[name]);
  43273. }
  43274. for (name in this._colors3Arrays) {
  43275. this._effect.setArray3(name, this._colors3Arrays[name]);
  43276. }
  43277. // Color4
  43278. for (name in this._colors4) {
  43279. var color = this._colors4[name];
  43280. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  43281. }
  43282. // Vector2
  43283. for (name in this._vectors2) {
  43284. this._effect.setVector2(name, this._vectors2[name]);
  43285. }
  43286. // Vector3
  43287. for (name in this._vectors3) {
  43288. this._effect.setVector3(name, this._vectors3[name]);
  43289. }
  43290. // Vector4
  43291. for (name in this._vectors4) {
  43292. this._effect.setVector4(name, this._vectors4[name]);
  43293. }
  43294. // Matrix
  43295. for (name in this._matrices) {
  43296. this._effect.setMatrix(name, this._matrices[name]);
  43297. }
  43298. // Matrix 3x3
  43299. for (name in this._matrices3x3) {
  43300. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  43301. }
  43302. // Matrix 2x2
  43303. for (name in this._matrices2x2) {
  43304. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  43305. }
  43306. // Vector3Array
  43307. for (name in this._vectors3Arrays) {
  43308. this._effect.setArray3(name, this._vectors3Arrays[name]);
  43309. }
  43310. }
  43311. this._afterBind(mesh);
  43312. };
  43313. ShaderMaterial.prototype.getActiveTextures = function () {
  43314. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43315. for (var name in this._textures) {
  43316. activeTextures.push(this._textures[name]);
  43317. }
  43318. for (var name in this._textureArrays) {
  43319. var array = this._textureArrays[name];
  43320. for (var index = 0; index < array.length; index++) {
  43321. activeTextures.push(array[index]);
  43322. }
  43323. }
  43324. return activeTextures;
  43325. };
  43326. ShaderMaterial.prototype.hasTexture = function (texture) {
  43327. if (_super.prototype.hasTexture.call(this, texture)) {
  43328. return true;
  43329. }
  43330. for (var name in this._textures) {
  43331. if (this._textures[name] === texture) {
  43332. return true;
  43333. }
  43334. }
  43335. for (var name in this._textureArrays) {
  43336. var array = this._textureArrays[name];
  43337. for (var index = 0; index < array.length; index++) {
  43338. if (array[index] === texture) {
  43339. return true;
  43340. }
  43341. }
  43342. }
  43343. return false;
  43344. };
  43345. ShaderMaterial.prototype.clone = function (name) {
  43346. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  43347. return newShaderMaterial;
  43348. };
  43349. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43350. if (forceDisposeTextures) {
  43351. var name;
  43352. for (name in this._textures) {
  43353. this._textures[name].dispose();
  43354. }
  43355. for (name in this._textureArrays) {
  43356. var array = this._textureArrays[name];
  43357. for (var index = 0; index < array.length; index++) {
  43358. array[index].dispose();
  43359. }
  43360. }
  43361. }
  43362. this._textures = {};
  43363. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43364. };
  43365. ShaderMaterial.prototype.serialize = function () {
  43366. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43367. serializationObject.customType = "BABYLON.ShaderMaterial";
  43368. serializationObject.options = this._options;
  43369. serializationObject.shaderPath = this._shaderPath;
  43370. var name;
  43371. // Texture
  43372. serializationObject.textures = {};
  43373. for (name in this._textures) {
  43374. serializationObject.textures[name] = this._textures[name].serialize();
  43375. }
  43376. // Texture arrays
  43377. serializationObject.textureArrays = {};
  43378. for (name in this._textureArrays) {
  43379. serializationObject.textureArrays[name] = [];
  43380. var array = this._textureArrays[name];
  43381. for (var index = 0; index < array.length; index++) {
  43382. serializationObject.textureArrays[name].push(array[index].serialize());
  43383. }
  43384. }
  43385. // Float
  43386. serializationObject.floats = {};
  43387. for (name in this._floats) {
  43388. serializationObject.floats[name] = this._floats[name];
  43389. }
  43390. // Float s
  43391. serializationObject.floatArrays = {};
  43392. for (name in this._floatsArrays) {
  43393. serializationObject.floatArrays[name] = this._floatsArrays[name];
  43394. }
  43395. // Color3
  43396. serializationObject.colors3 = {};
  43397. for (name in this._colors3) {
  43398. serializationObject.colors3[name] = this._colors3[name].asArray();
  43399. }
  43400. // Color3 array
  43401. serializationObject.colors3Arrays = {};
  43402. for (name in this._colors3Arrays) {
  43403. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  43404. }
  43405. // Color4
  43406. serializationObject.colors4 = {};
  43407. for (name in this._colors4) {
  43408. serializationObject.colors4[name] = this._colors4[name].asArray();
  43409. }
  43410. // Vector2
  43411. serializationObject.vectors2 = {};
  43412. for (name in this._vectors2) {
  43413. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  43414. }
  43415. // Vector3
  43416. serializationObject.vectors3 = {};
  43417. for (name in this._vectors3) {
  43418. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  43419. }
  43420. // Vector4
  43421. serializationObject.vectors4 = {};
  43422. for (name in this._vectors4) {
  43423. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  43424. }
  43425. // Matrix
  43426. serializationObject.matrices = {};
  43427. for (name in this._matrices) {
  43428. serializationObject.matrices[name] = this._matrices[name].asArray();
  43429. }
  43430. // Matrix 3x3
  43431. serializationObject.matrices3x3 = {};
  43432. for (name in this._matrices3x3) {
  43433. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  43434. }
  43435. // Matrix 2x2
  43436. serializationObject.matrices2x2 = {};
  43437. for (name in this._matrices2x2) {
  43438. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  43439. }
  43440. // Vector3Array
  43441. serializationObject.vectors3Arrays = {};
  43442. for (name in this._vectors3Arrays) {
  43443. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  43444. }
  43445. return serializationObject;
  43446. };
  43447. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  43448. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  43449. var name;
  43450. // Texture
  43451. for (name in source.textures) {
  43452. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  43453. }
  43454. // Texture arrays
  43455. for (name in source.textureArrays) {
  43456. var array = source.textureArrays[name];
  43457. var textureArray = new Array();
  43458. for (var index = 0; index < array.length; index++) {
  43459. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  43460. }
  43461. material.setTextureArray(name, textureArray);
  43462. }
  43463. // Float
  43464. for (name in source.floats) {
  43465. material.setFloat(name, source.floats[name]);
  43466. }
  43467. // Float s
  43468. for (name in source.floatsArrays) {
  43469. material.setFloats(name, source.floatsArrays[name]);
  43470. }
  43471. // Color3
  43472. for (name in source.colors3) {
  43473. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  43474. }
  43475. // Color3 arrays
  43476. for (name in source.colors3Arrays) {
  43477. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  43478. if (i % 3 === 0) {
  43479. arr.push([num]);
  43480. }
  43481. else {
  43482. arr[arr.length - 1].push(num);
  43483. }
  43484. return arr;
  43485. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  43486. material.setColor3Array(name, colors);
  43487. }
  43488. // Color4
  43489. for (name in source.colors4) {
  43490. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  43491. }
  43492. // Vector2
  43493. for (name in source.vectors2) {
  43494. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  43495. }
  43496. // Vector3
  43497. for (name in source.vectors3) {
  43498. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  43499. }
  43500. // Vector4
  43501. for (name in source.vectors4) {
  43502. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  43503. }
  43504. // Matrix
  43505. for (name in source.matrices) {
  43506. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  43507. }
  43508. // Matrix 3x3
  43509. for (name in source.matrices3x3) {
  43510. material.setMatrix3x3(name, source.matrices3x3[name]);
  43511. }
  43512. // Matrix 2x2
  43513. for (name in source.matrices2x2) {
  43514. material.setMatrix2x2(name, source.matrices2x2[name]);
  43515. }
  43516. // Vector3Array
  43517. for (name in source.vectors3Arrays) {
  43518. material.setArray3(name, source.vectors3Arrays[name]);
  43519. }
  43520. return material;
  43521. };
  43522. return ShaderMaterial;
  43523. }(BABYLON.Material));
  43524. BABYLON.ShaderMaterial = ShaderMaterial;
  43525. })(BABYLON || (BABYLON = {}));
  43526. //# sourceMappingURL=babylon.shaderMaterial.js.map
  43527. var BABYLON;
  43528. (function (BABYLON) {
  43529. var MeshBuilder = (function () {
  43530. function MeshBuilder() {
  43531. }
  43532. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  43533. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  43534. return BABYLON.Mesh.DOUBLESIDE;
  43535. }
  43536. if (orientation === undefined || orientation === null) {
  43537. return BABYLON.Mesh.FRONTSIDE;
  43538. }
  43539. return orientation;
  43540. };
  43541. /**
  43542. * Creates a box mesh.
  43543. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  43544. * The parameter `size` sets the size (float) of each box side (default 1).
  43545. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  43546. * 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).
  43547. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  43548. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43549. * 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).
  43550. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43551. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43552. */
  43553. MeshBuilder.CreateBox = function (name, options, scene) {
  43554. var box = new BABYLON.Mesh(name, scene);
  43555. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43556. box.sideOrientation = options.sideOrientation;
  43557. var vertexData = BABYLON.VertexData.CreateBox(options);
  43558. vertexData.applyToMesh(box, options.updatable);
  43559. return box;
  43560. };
  43561. /**
  43562. * Creates a sphere mesh.
  43563. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  43564. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  43565. * 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`).
  43566. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  43567. * 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
  43568. * 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).
  43569. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43570. * 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).
  43571. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43572. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43573. */
  43574. MeshBuilder.CreateSphere = function (name, options, scene) {
  43575. var sphere = new BABYLON.Mesh(name, scene);
  43576. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43577. sphere.sideOrientation = options.sideOrientation;
  43578. var vertexData = BABYLON.VertexData.CreateSphere(options);
  43579. vertexData.applyToMesh(sphere, options.updatable);
  43580. return sphere;
  43581. };
  43582. /**
  43583. * Creates a plane polygonal mesh. By default, this is a disc.
  43584. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  43585. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  43586. * 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.
  43587. * 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
  43588. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43589. * 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).
  43590. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43591. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43592. */
  43593. MeshBuilder.CreateDisc = function (name, options, scene) {
  43594. var disc = new BABYLON.Mesh(name, scene);
  43595. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43596. disc.sideOrientation = options.sideOrientation;
  43597. var vertexData = BABYLON.VertexData.CreateDisc(options);
  43598. vertexData.applyToMesh(disc, options.updatable);
  43599. return disc;
  43600. };
  43601. /**
  43602. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  43603. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  43604. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  43605. * 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`).
  43606. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  43607. * 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.
  43608. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43609. * 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).
  43610. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43611. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43612. */
  43613. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  43614. var sphere = new BABYLON.Mesh(name, scene);
  43615. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43616. sphere.sideOrientation = options.sideOrientation;
  43617. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  43618. vertexData.applyToMesh(sphere, options.updatable);
  43619. return sphere;
  43620. };
  43621. ;
  43622. /**
  43623. * Creates a ribbon mesh.
  43624. * 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.
  43625. *
  43626. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  43627. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  43628. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  43629. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  43630. * 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.
  43631. * 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.
  43632. * 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
  43633. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43634. * 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).
  43635. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43636. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  43637. * 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.
  43638. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  43639. * 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
  43640. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  43641. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  43642. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43643. */
  43644. MeshBuilder.CreateRibbon = function (name, options, scene) {
  43645. var pathArray = options.pathArray;
  43646. var closeArray = options.closeArray;
  43647. var closePath = options.closePath;
  43648. var offset = options.offset;
  43649. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43650. var instance = options.instance;
  43651. var updatable = options.updatable;
  43652. if (instance) {
  43653. // positionFunction : ribbon case
  43654. // only pathArray and sideOrientation parameters are taken into account for positions update
  43655. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  43656. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  43657. var positionFunction = function (positions) {
  43658. var minlg = pathArray[0].length;
  43659. var i = 0;
  43660. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  43661. for (var si = 1; si <= ns; si++) {
  43662. for (var p = 0; p < pathArray.length; p++) {
  43663. var path = pathArray[p];
  43664. var l = path.length;
  43665. minlg = (minlg < l) ? minlg : l;
  43666. var j = 0;
  43667. while (j < minlg) {
  43668. positions[i] = path[j].x;
  43669. positions[i + 1] = path[j].y;
  43670. positions[i + 2] = path[j].z;
  43671. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  43672. BABYLON.Tmp.Vector3[0].x = path[j].x;
  43673. }
  43674. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  43675. BABYLON.Tmp.Vector3[1].x = path[j].x;
  43676. }
  43677. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  43678. BABYLON.Tmp.Vector3[0].y = path[j].y;
  43679. }
  43680. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  43681. BABYLON.Tmp.Vector3[1].y = path[j].y;
  43682. }
  43683. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  43684. BABYLON.Tmp.Vector3[0].z = path[j].z;
  43685. }
  43686. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  43687. BABYLON.Tmp.Vector3[1].z = path[j].z;
  43688. }
  43689. j++;
  43690. i += 3;
  43691. }
  43692. if (instance._closePath) {
  43693. positions[i] = path[0].x;
  43694. positions[i + 1] = path[0].y;
  43695. positions[i + 2] = path[0].z;
  43696. i += 3;
  43697. }
  43698. }
  43699. }
  43700. };
  43701. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43702. positionFunction(positions);
  43703. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  43704. instance._boundingInfo.update(instance._worldMatrix);
  43705. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  43706. if (options.colors) {
  43707. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  43708. for (var c = 0; c < options.colors.length; c++) {
  43709. colors[c * 4] = options.colors[c].r;
  43710. colors[c * 4 + 1] = options.colors[c].g;
  43711. colors[c * 4 + 2] = options.colors[c].b;
  43712. colors[c * 4 + 3] = options.colors[c].a;
  43713. }
  43714. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  43715. }
  43716. if (options.uvs) {
  43717. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43718. for (var i = 0; i < options.uvs.length; i++) {
  43719. uvs[i * 2] = options.uvs[i].x;
  43720. uvs[i * 2 + 1] = options.uvs[i].y;
  43721. }
  43722. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  43723. }
  43724. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  43725. var indices = instance.getIndices();
  43726. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43727. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  43728. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  43729. if (instance._closePath) {
  43730. var indexFirst = 0;
  43731. var indexLast = 0;
  43732. for (var p = 0; p < pathArray.length; p++) {
  43733. indexFirst = instance._idx[p] * 3;
  43734. if (p + 1 < pathArray.length) {
  43735. indexLast = (instance._idx[p + 1] - 1) * 3;
  43736. }
  43737. else {
  43738. indexLast = normals.length - 3;
  43739. }
  43740. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  43741. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  43742. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  43743. normals[indexLast] = normals[indexFirst];
  43744. normals[indexLast + 1] = normals[indexFirst + 1];
  43745. normals[indexLast + 2] = normals[indexFirst + 2];
  43746. }
  43747. }
  43748. if (!(instance.areNormalsFrozen)) {
  43749. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  43750. }
  43751. }
  43752. return instance;
  43753. }
  43754. else {
  43755. var ribbon = new BABYLON.Mesh(name, scene);
  43756. ribbon.sideOrientation = sideOrientation;
  43757. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  43758. if (closePath) {
  43759. ribbon._idx = vertexData._idx;
  43760. }
  43761. ribbon._closePath = closePath;
  43762. ribbon._closeArray = closeArray;
  43763. vertexData.applyToMesh(ribbon, updatable);
  43764. return ribbon;
  43765. }
  43766. };
  43767. /**
  43768. * Creates a cylinder or a cone mesh.
  43769. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  43770. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  43771. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  43772. * 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.
  43773. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  43774. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  43775. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  43776. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  43777. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  43778. * 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).
  43779. * 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
  43780. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  43781. * 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
  43782. * 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.
  43783. * If `enclose` is false, a ring surface is one element.
  43784. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  43785. * 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
  43786. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43787. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  43788. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43789. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43790. */
  43791. MeshBuilder.CreateCylinder = function (name, options, scene) {
  43792. var cylinder = new BABYLON.Mesh(name, scene);
  43793. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43794. cylinder.sideOrientation = options.sideOrientation;
  43795. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  43796. vertexData.applyToMesh(cylinder, options.updatable);
  43797. return cylinder;
  43798. };
  43799. /**
  43800. * Creates a torus mesh.
  43801. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  43802. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  43803. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  43804. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  43805. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43806. * 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).
  43807. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43808. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43809. */
  43810. MeshBuilder.CreateTorus = function (name, options, scene) {
  43811. var torus = new BABYLON.Mesh(name, scene);
  43812. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43813. torus.sideOrientation = options.sideOrientation;
  43814. var vertexData = BABYLON.VertexData.CreateTorus(options);
  43815. vertexData.applyToMesh(torus, options.updatable);
  43816. return torus;
  43817. };
  43818. /**
  43819. * Creates a torus knot mesh.
  43820. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  43821. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  43822. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  43823. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  43824. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  43825. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43826. * 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).
  43827. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43828. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43829. */
  43830. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  43831. var torusKnot = new BABYLON.Mesh(name, scene);
  43832. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43833. torusKnot.sideOrientation = options.sideOrientation;
  43834. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  43835. vertexData.applyToMesh(torusKnot, options.updatable);
  43836. return torusKnot;
  43837. };
  43838. /**
  43839. * Creates a line system mesh.
  43840. * A line system is a pool of many lines gathered in a single mesh.
  43841. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  43842. * 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.
  43843. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  43844. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  43845. * 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
  43846. * 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
  43847. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  43848. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43849. */
  43850. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  43851. var instance = options.instance;
  43852. var lines = options.lines;
  43853. if (instance) {
  43854. var positionFunction = function (positions) {
  43855. var i = 0;
  43856. for (var l = 0; l < lines.length; l++) {
  43857. var points = lines[l];
  43858. for (var p = 0; p < points.length; p++) {
  43859. positions[i] = points[p].x;
  43860. positions[i + 1] = points[p].y;
  43861. positions[i + 2] = points[p].z;
  43862. i += 3;
  43863. }
  43864. }
  43865. };
  43866. instance.updateMeshPositions(positionFunction, false);
  43867. return instance;
  43868. }
  43869. // line system creation
  43870. var lineSystem = new BABYLON.LinesMesh(name, scene);
  43871. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  43872. vertexData.applyToMesh(lineSystem, options.updatable);
  43873. return lineSystem;
  43874. };
  43875. /**
  43876. * Creates a line mesh.
  43877. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  43878. * 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.
  43879. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  43880. * The parameter `points` is an array successive Vector3.
  43881. * 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
  43882. * When updating an instance, remember that only point positions can change, not the number of points.
  43883. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43884. */
  43885. MeshBuilder.CreateLines = function (name, options, scene) {
  43886. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  43887. return lines;
  43888. };
  43889. /**
  43890. * Creates a dashed line mesh.
  43891. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  43892. * 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.
  43893. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  43894. * The parameter `points` is an array successive Vector3.
  43895. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  43896. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  43897. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  43898. * 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
  43899. * When updating an instance, remember that only point positions can change, not the number of points.
  43900. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43901. */
  43902. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  43903. var points = options.points;
  43904. var instance = options.instance;
  43905. var gapSize = options.gapSize;
  43906. var dashNb = options.dashNb;
  43907. var dashSize = options.dashSize;
  43908. if (instance) {
  43909. var positionFunction = function (positions) {
  43910. var curvect = BABYLON.Vector3.Zero();
  43911. var nbSeg = positions.length / 6;
  43912. var lg = 0;
  43913. var nb = 0;
  43914. var shft = 0;
  43915. var dashshft = 0;
  43916. var curshft = 0;
  43917. var p = 0;
  43918. var i = 0;
  43919. var j = 0;
  43920. for (i = 0; i < points.length - 1; i++) {
  43921. points[i + 1].subtractToRef(points[i], curvect);
  43922. lg += curvect.length();
  43923. }
  43924. shft = lg / nbSeg;
  43925. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  43926. for (i = 0; i < points.length - 1; i++) {
  43927. points[i + 1].subtractToRef(points[i], curvect);
  43928. nb = Math.floor(curvect.length() / shft);
  43929. curvect.normalize();
  43930. j = 0;
  43931. while (j < nb && p < positions.length) {
  43932. curshft = shft * j;
  43933. positions[p] = points[i].x + curshft * curvect.x;
  43934. positions[p + 1] = points[i].y + curshft * curvect.y;
  43935. positions[p + 2] = points[i].z + curshft * curvect.z;
  43936. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  43937. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  43938. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  43939. p += 6;
  43940. j++;
  43941. }
  43942. }
  43943. while (p < positions.length) {
  43944. positions[p] = points[i].x;
  43945. positions[p + 1] = points[i].y;
  43946. positions[p + 2] = points[i].z;
  43947. p += 3;
  43948. }
  43949. };
  43950. instance.updateMeshPositions(positionFunction, false);
  43951. return instance;
  43952. }
  43953. // dashed lines creation
  43954. var dashedLines = new BABYLON.LinesMesh(name, scene);
  43955. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  43956. vertexData.applyToMesh(dashedLines, options.updatable);
  43957. dashedLines.dashSize = dashSize;
  43958. dashedLines.gapSize = gapSize;
  43959. return dashedLines;
  43960. };
  43961. /**
  43962. * Creates an extruded shape mesh.
  43963. * 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.
  43964. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  43965. *
  43966. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  43967. * 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
  43968. * extruded along the Z axis.
  43969. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  43970. * 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.
  43971. * The parameter `scale` (float, default 1) is the value to scale the shape.
  43972. * 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
  43973. * 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
  43974. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  43975. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43976. * 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).
  43977. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43978. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  43979. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43980. */
  43981. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  43982. var path = options.path;
  43983. var shape = options.shape;
  43984. var scale = options.scale || 1;
  43985. var rotation = options.rotation || 0;
  43986. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  43987. var updatable = options.updatable;
  43988. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43989. var instance = options.instance;
  43990. var invertUV = options.invertUV || false;
  43991. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  43992. };
  43993. /**
  43994. * Creates an custom extruded shape mesh.
  43995. * 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.
  43996. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  43997. *
  43998. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  43999. * 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
  44000. * extruded along the Z axis.
  44001. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  44002. * 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
  44003. * and the distance of this point from the begining of the path :
  44004. * ```javascript
  44005. * var rotationFunction = function(i, distance) {
  44006. * // do things
  44007. * return rotationValue; }
  44008. * ```
  44009. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  44010. * 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
  44011. * and the distance of this point from the begining of the path :
  44012. * ```javascript
  44013. * var scaleFunction = function(i, distance) {
  44014. * // do things
  44015. * return scaleValue;}
  44016. * ```
  44017. * It must returns a float value that will be the scale value applied to the shape on each path point.
  44018. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  44019. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  44020. * 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
  44021. * 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
  44022. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  44023. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44024. * 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).
  44025. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44026. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  44027. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44028. */
  44029. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  44030. var path = options.path;
  44031. var shape = options.shape;
  44032. var scaleFunction = options.scaleFunction || (function () { return 1; });
  44033. var rotationFunction = options.rotationFunction || (function () { return 0; });
  44034. var ribbonCloseArray = options.ribbonCloseArray || false;
  44035. var ribbonClosePath = options.ribbonClosePath || false;
  44036. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  44037. var updatable = options.updatable;
  44038. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44039. var instance = options.instance;
  44040. var invertUV = options.invertUV || false;
  44041. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  44042. };
  44043. /**
  44044. * Creates lathe mesh.
  44045. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  44046. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  44047. *
  44048. * 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
  44049. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  44050. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  44051. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  44052. * 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.
  44053. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  44054. * 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
  44055. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44056. * 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).
  44057. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44058. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  44059. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44060. */
  44061. MeshBuilder.CreateLathe = function (name, options, scene) {
  44062. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  44063. var closed = (options.closed === undefined) ? true : options.closed;
  44064. var shape = options.shape;
  44065. var radius = options.radius || 1;
  44066. var tessellation = options.tessellation || 64;
  44067. var updatable = options.updatable;
  44068. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44069. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  44070. var pi2 = Math.PI * 2;
  44071. var paths = new Array();
  44072. var invertUV = options.invertUV || false;
  44073. var i = 0;
  44074. var p = 0;
  44075. var step = pi2 / tessellation * arc;
  44076. var rotated;
  44077. var path = new Array();
  44078. ;
  44079. for (i = 0; i <= tessellation; i++) {
  44080. var path = [];
  44081. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  44082. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  44083. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  44084. }
  44085. for (p = 0; p < shape.length; p++) {
  44086. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  44087. path.push(rotated);
  44088. }
  44089. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  44090. 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));
  44091. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  44092. }
  44093. paths.push(path);
  44094. }
  44095. // lathe ribbon
  44096. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  44097. return lathe;
  44098. };
  44099. /**
  44100. * Creates a plane mesh.
  44101. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  44102. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  44103. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  44104. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  44105. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44106. * 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).
  44107. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44108. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44109. */
  44110. MeshBuilder.CreatePlane = function (name, options, scene) {
  44111. var plane = new BABYLON.Mesh(name, scene);
  44112. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44113. plane.sideOrientation = options.sideOrientation;
  44114. var vertexData = BABYLON.VertexData.CreatePlane(options);
  44115. vertexData.applyToMesh(plane, options.updatable);
  44116. if (options.sourcePlane) {
  44117. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  44118. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  44119. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  44120. plane.rotate(vectorProduct, product);
  44121. }
  44122. return plane;
  44123. };
  44124. /**
  44125. * Creates a ground mesh.
  44126. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  44127. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  44128. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  44129. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44130. */
  44131. MeshBuilder.CreateGround = function (name, options, scene) {
  44132. var ground = new BABYLON.GroundMesh(name, scene);
  44133. ground._setReady(false);
  44134. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  44135. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  44136. ground._width = options.width || 1;
  44137. ground._height = options.height || 1;
  44138. ground._maxX = ground._width / 2;
  44139. ground._maxZ = ground._height / 2;
  44140. ground._minX = -ground._maxX;
  44141. ground._minZ = -ground._maxZ;
  44142. var vertexData = BABYLON.VertexData.CreateGround(options);
  44143. vertexData.applyToMesh(ground, options.updatable);
  44144. ground._setReady(true);
  44145. return ground;
  44146. };
  44147. /**
  44148. * Creates a tiled ground mesh.
  44149. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  44150. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  44151. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  44152. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  44153. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  44154. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  44155. * numbers of subdivisions on the ground width and height of each tile.
  44156. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44157. */
  44158. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  44159. var tiledGround = new BABYLON.Mesh(name, scene);
  44160. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  44161. vertexData.applyToMesh(tiledGround, options.updatable);
  44162. return tiledGround;
  44163. };
  44164. /**
  44165. * Creates a ground mesh from a height map.
  44166. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  44167. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  44168. * The parameter `url` sets the URL of the height map image resource.
  44169. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  44170. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  44171. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  44172. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  44173. * 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.
  44174. * 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).
  44175. * This function is passed the newly built mesh :
  44176. * ```javascript
  44177. * function(mesh) { // do things
  44178. * return; }
  44179. * ```
  44180. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44181. */
  44182. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  44183. var width = options.width || 10.0;
  44184. var height = options.height || 10.0;
  44185. var subdivisions = options.subdivisions || 1 | 0;
  44186. var minHeight = options.minHeight || 0.0;
  44187. var maxHeight = options.maxHeight || 10.0;
  44188. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  44189. var updatable = options.updatable;
  44190. var onReady = options.onReady;
  44191. var ground = new BABYLON.GroundMesh(name, scene);
  44192. ground._subdivisionsX = subdivisions;
  44193. ground._subdivisionsY = subdivisions;
  44194. ground._width = width;
  44195. ground._height = height;
  44196. ground._maxX = ground._width / 2.0;
  44197. ground._maxZ = ground._height / 2.0;
  44198. ground._minX = -ground._maxX;
  44199. ground._minZ = -ground._maxZ;
  44200. ground._setReady(false);
  44201. var onload = function (img) {
  44202. // Getting height map data
  44203. var canvas = document.createElement("canvas");
  44204. var context = canvas.getContext("2d");
  44205. var bufferWidth = img.width;
  44206. var bufferHeight = img.height;
  44207. canvas.width = bufferWidth;
  44208. canvas.height = bufferHeight;
  44209. context.drawImage(img, 0, 0);
  44210. // Create VertexData from map data
  44211. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  44212. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  44213. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  44214. width: width, height: height,
  44215. subdivisions: subdivisions,
  44216. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  44217. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  44218. });
  44219. vertexData.applyToMesh(ground, updatable);
  44220. ground._setReady(true);
  44221. //execute ready callback, if set
  44222. if (onReady) {
  44223. onReady(ground);
  44224. }
  44225. };
  44226. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  44227. return ground;
  44228. };
  44229. /**
  44230. * Creates a polygon mesh.
  44231. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  44232. * 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.
  44233. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44234. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44235. * 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).
  44236. * Remember you can only change the shape positions, not their number when updating a polygon.
  44237. */
  44238. MeshBuilder.CreatePolygon = function (name, options, scene) {
  44239. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44240. var shape = options.shape;
  44241. var holes = options.holes || [];
  44242. var depth = options.depth || 0;
  44243. var contours = [];
  44244. var hole = [];
  44245. for (var i = 0; i < shape.length; i++) {
  44246. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  44247. }
  44248. var epsilon = 0.00000001;
  44249. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  44250. contours.pop();
  44251. }
  44252. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  44253. for (var hNb = 0; hNb < holes.length; hNb++) {
  44254. hole = [];
  44255. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  44256. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  44257. }
  44258. polygonTriangulation.addHole(hole);
  44259. }
  44260. var polygon = polygonTriangulation.build(options.updatable, depth);
  44261. polygon.sideOrientation = options.sideOrientation;
  44262. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  44263. vertexData.applyToMesh(polygon, options.updatable);
  44264. return polygon;
  44265. };
  44266. ;
  44267. /**
  44268. * Creates an extruded polygon mesh, with depth in the Y direction.
  44269. * 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).
  44270. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  44271. */
  44272. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  44273. return MeshBuilder.CreatePolygon(name, options, scene);
  44274. };
  44275. ;
  44276. /**
  44277. * Creates a tube mesh.
  44278. * 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.
  44279. *
  44280. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  44281. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  44282. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  44283. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  44284. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  44285. * 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.
  44286. * It must return a radius value (positive float) :
  44287. * ```javascript
  44288. * var radiusFunction = function(i, distance) {
  44289. * // do things
  44290. * return radius; }
  44291. * ```
  44292. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  44293. * 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
  44294. * 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
  44295. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44296. * 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).
  44297. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44298. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  44299. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44300. */
  44301. MeshBuilder.CreateTube = function (name, options, scene) {
  44302. var path = options.path;
  44303. var radius = options.radius || 1.0;
  44304. var tessellation = options.tessellation || 64 | 0;
  44305. var radiusFunction = options.radiusFunction;
  44306. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  44307. var invertUV = options.invertUV || false;
  44308. var updatable = options.updatable;
  44309. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44310. var instance = options.instance;
  44311. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  44312. // tube geometry
  44313. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  44314. var tangents = path3D.getTangents();
  44315. var normals = path3D.getNormals();
  44316. var distances = path3D.getDistances();
  44317. var pi2 = Math.PI * 2;
  44318. var step = pi2 / tessellation * arc;
  44319. var returnRadius = function () { return radius; };
  44320. var radiusFunctionFinal = radiusFunction || returnRadius;
  44321. var circlePath;
  44322. var rad;
  44323. var normal;
  44324. var rotated;
  44325. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  44326. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  44327. for (var i = 0; i < path.length; i++) {
  44328. rad = radiusFunctionFinal(i, distances[i]); // current radius
  44329. circlePath = Array(); // current circle array
  44330. normal = normals[i]; // current normal
  44331. for (var t = 0; t < tessellation; t++) {
  44332. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  44333. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  44334. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  44335. rotated.scaleInPlace(rad).addInPlace(path[i]);
  44336. circlePath[t] = rotated;
  44337. }
  44338. circlePaths[index] = circlePath;
  44339. index++;
  44340. }
  44341. // cap
  44342. var capPath = function (nbPoints, pathIndex) {
  44343. var pointCap = Array();
  44344. for (var i = 0; i < nbPoints; i++) {
  44345. pointCap.push(path[pathIndex]);
  44346. }
  44347. return pointCap;
  44348. };
  44349. switch (cap) {
  44350. case BABYLON.Mesh.NO_CAP:
  44351. break;
  44352. case BABYLON.Mesh.CAP_START:
  44353. circlePaths[0] = capPath(tessellation, 0);
  44354. circlePaths[1] = circlePaths[2].slice(0);
  44355. break;
  44356. case BABYLON.Mesh.CAP_END:
  44357. circlePaths[index] = circlePaths[index - 1].slice(0);
  44358. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  44359. break;
  44360. case BABYLON.Mesh.CAP_ALL:
  44361. circlePaths[0] = capPath(tessellation, 0);
  44362. circlePaths[1] = circlePaths[2].slice(0);
  44363. circlePaths[index] = circlePaths[index - 1].slice(0);
  44364. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  44365. break;
  44366. default:
  44367. break;
  44368. }
  44369. return circlePaths;
  44370. };
  44371. var path3D;
  44372. var pathArray;
  44373. if (instance) {
  44374. var arc = options.arc || instance.arc;
  44375. path3D = (instance.path3D).update(path);
  44376. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  44377. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  44378. instance.path3D = path3D;
  44379. instance.pathArray = pathArray;
  44380. instance.arc = arc;
  44381. return instance;
  44382. }
  44383. // tube creation
  44384. path3D = new BABYLON.Path3D(path);
  44385. var newPathArray = new Array();
  44386. cap = (cap < 0 || cap > 3) ? 0 : cap;
  44387. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  44388. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  44389. tube.pathArray = pathArray;
  44390. tube.path3D = path3D;
  44391. tube.tessellation = tessellation;
  44392. tube.cap = cap;
  44393. tube.arc = options.arc;
  44394. return tube;
  44395. };
  44396. /**
  44397. * Creates a polyhedron mesh.
  44398. *
  44399. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  44400. * 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
  44401. * to choose the wanted type.
  44402. * The parameter `size` (positive float, default 1) sets the polygon size.
  44403. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  44404. * 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`.
  44405. * 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
  44406. * 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)`).
  44407. * 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
  44408. * 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.
  44409. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  44410. * 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).
  44411. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  44412. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  44413. */
  44414. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  44415. var polyhedron = new BABYLON.Mesh(name, scene);
  44416. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  44417. polyhedron.sideOrientation = options.sideOrientation;
  44418. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  44419. vertexData.applyToMesh(polyhedron, options.updatable);
  44420. return polyhedron;
  44421. };
  44422. /**
  44423. * Creates a decal mesh.
  44424. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  44425. * 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.
  44426. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  44427. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  44428. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  44429. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  44430. */
  44431. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  44432. var indices = sourceMesh.getIndices();
  44433. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44434. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44435. var position = options.position || BABYLON.Vector3.Zero();
  44436. var normal = options.normal || BABYLON.Vector3.Up();
  44437. var size = options.size || BABYLON.Vector3.One();
  44438. var angle = options.angle || 0;
  44439. // Getting correct rotation
  44440. if (!normal) {
  44441. var target = new BABYLON.Vector3(0, 0, 1);
  44442. var camera = sourceMesh.getScene().activeCamera;
  44443. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  44444. normal = camera.globalPosition.subtract(cameraWorldTarget);
  44445. }
  44446. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  44447. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  44448. var pitch = Math.atan2(normal.y, len);
  44449. // Matrix
  44450. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  44451. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  44452. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  44453. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  44454. var vertexData = new BABYLON.VertexData();
  44455. vertexData.indices = [];
  44456. vertexData.positions = [];
  44457. vertexData.normals = [];
  44458. vertexData.uvs = [];
  44459. var currentVertexDataIndex = 0;
  44460. var extractDecalVector3 = function (indexId) {
  44461. var vertexId = indices[indexId];
  44462. var result = new BABYLON.PositionNormalVertex();
  44463. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  44464. // Send vector to decal local world
  44465. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  44466. // Get normal
  44467. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  44468. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  44469. return result;
  44470. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  44471. var clip = function (vertices, axis) {
  44472. if (vertices.length === 0) {
  44473. return vertices;
  44474. }
  44475. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  44476. var clipVertices = function (v0, v1) {
  44477. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  44478. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  44479. };
  44480. var result = new Array();
  44481. for (var index = 0; index < vertices.length; index += 3) {
  44482. var v1Out;
  44483. var v2Out;
  44484. var v3Out;
  44485. var total = 0;
  44486. var nV1, nV2, nV3, nV4;
  44487. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  44488. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  44489. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  44490. v1Out = d1 > 0;
  44491. v2Out = d2 > 0;
  44492. v3Out = d3 > 0;
  44493. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  44494. switch (total) {
  44495. case 0:
  44496. result.push(vertices[index]);
  44497. result.push(vertices[index + 1]);
  44498. result.push(vertices[index + 2]);
  44499. break;
  44500. case 1:
  44501. if (v1Out) {
  44502. nV1 = vertices[index + 1];
  44503. nV2 = vertices[index + 2];
  44504. nV3 = clipVertices(vertices[index], nV1);
  44505. nV4 = clipVertices(vertices[index], nV2);
  44506. }
  44507. if (v2Out) {
  44508. nV1 = vertices[index];
  44509. nV2 = vertices[index + 2];
  44510. nV3 = clipVertices(vertices[index + 1], nV1);
  44511. nV4 = clipVertices(vertices[index + 1], nV2);
  44512. result.push(nV3);
  44513. result.push(nV2.clone());
  44514. result.push(nV1.clone());
  44515. result.push(nV2.clone());
  44516. result.push(nV3.clone());
  44517. result.push(nV4);
  44518. break;
  44519. }
  44520. if (v3Out) {
  44521. nV1 = vertices[index];
  44522. nV2 = vertices[index + 1];
  44523. nV3 = clipVertices(vertices[index + 2], nV1);
  44524. nV4 = clipVertices(vertices[index + 2], nV2);
  44525. }
  44526. result.push(nV1.clone());
  44527. result.push(nV2.clone());
  44528. result.push(nV3);
  44529. result.push(nV4);
  44530. result.push(nV3.clone());
  44531. result.push(nV2.clone());
  44532. break;
  44533. case 2:
  44534. if (!v1Out) {
  44535. nV1 = vertices[index].clone();
  44536. nV2 = clipVertices(nV1, vertices[index + 1]);
  44537. nV3 = clipVertices(nV1, vertices[index + 2]);
  44538. result.push(nV1);
  44539. result.push(nV2);
  44540. result.push(nV3);
  44541. }
  44542. if (!v2Out) {
  44543. nV1 = vertices[index + 1].clone();
  44544. nV2 = clipVertices(nV1, vertices[index + 2]);
  44545. nV3 = clipVertices(nV1, vertices[index]);
  44546. result.push(nV1);
  44547. result.push(nV2);
  44548. result.push(nV3);
  44549. }
  44550. if (!v3Out) {
  44551. nV1 = vertices[index + 2].clone();
  44552. nV2 = clipVertices(nV1, vertices[index]);
  44553. nV3 = clipVertices(nV1, vertices[index + 1]);
  44554. result.push(nV1);
  44555. result.push(nV2);
  44556. result.push(nV3);
  44557. }
  44558. break;
  44559. case 3:
  44560. break;
  44561. }
  44562. }
  44563. return result;
  44564. };
  44565. for (var index = 0; index < indices.length; index += 3) {
  44566. var faceVertices = new Array();
  44567. faceVertices.push(extractDecalVector3(index));
  44568. faceVertices.push(extractDecalVector3(index + 1));
  44569. faceVertices.push(extractDecalVector3(index + 2));
  44570. // Clip
  44571. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  44572. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  44573. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  44574. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  44575. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  44576. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  44577. if (faceVertices.length === 0) {
  44578. continue;
  44579. }
  44580. // Add UVs and get back to world
  44581. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  44582. var vertex = faceVertices[vIndex];
  44583. //TODO check for Int32Array | Uint32Array | Uint16Array
  44584. vertexData.indices.push(currentVertexDataIndex);
  44585. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  44586. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  44587. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  44588. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  44589. currentVertexDataIndex++;
  44590. }
  44591. }
  44592. // Return mesh
  44593. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  44594. vertexData.applyToMesh(decal);
  44595. decal.position = position.clone();
  44596. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  44597. return decal;
  44598. };
  44599. // Privates
  44600. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  44601. // extrusion geometry
  44602. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  44603. var tangents = path3D.getTangents();
  44604. var normals = path3D.getNormals();
  44605. var binormals = path3D.getBinormals();
  44606. var distances = path3D.getDistances();
  44607. var angle = 0;
  44608. var returnScale = function () { return scale; };
  44609. var returnRotation = function () { return rotation; };
  44610. var rotate = custom ? rotateFunction : returnRotation;
  44611. var scl = custom ? scaleFunction : returnScale;
  44612. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  44613. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  44614. for (var i = 0; i < curve.length; i++) {
  44615. var shapePath = new Array();
  44616. var angleStep = rotate(i, distances[i]);
  44617. var scaleRatio = scl(i, distances[i]);
  44618. for (var p = 0; p < shape.length; p++) {
  44619. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  44620. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  44621. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  44622. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  44623. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  44624. shapePath[p] = rotated;
  44625. }
  44626. shapePaths[index] = shapePath;
  44627. angle += angleStep;
  44628. index++;
  44629. }
  44630. // cap
  44631. var capPath = function (shapePath) {
  44632. var pointCap = Array();
  44633. var barycenter = BABYLON.Vector3.Zero();
  44634. var i;
  44635. for (i = 0; i < shapePath.length; i++) {
  44636. barycenter.addInPlace(shapePath[i]);
  44637. }
  44638. barycenter.scaleInPlace(1.0 / shapePath.length);
  44639. for (i = 0; i < shapePath.length; i++) {
  44640. pointCap.push(barycenter);
  44641. }
  44642. return pointCap;
  44643. };
  44644. switch (cap) {
  44645. case BABYLON.Mesh.NO_CAP:
  44646. break;
  44647. case BABYLON.Mesh.CAP_START:
  44648. shapePaths[0] = capPath(shapePaths[2]);
  44649. shapePaths[1] = shapePaths[2];
  44650. break;
  44651. case BABYLON.Mesh.CAP_END:
  44652. shapePaths[index] = shapePaths[index - 1];
  44653. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  44654. break;
  44655. case BABYLON.Mesh.CAP_ALL:
  44656. shapePaths[0] = capPath(shapePaths[2]);
  44657. shapePaths[1] = shapePaths[2];
  44658. shapePaths[index] = shapePaths[index - 1];
  44659. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  44660. break;
  44661. default:
  44662. break;
  44663. }
  44664. return shapePaths;
  44665. };
  44666. var path3D;
  44667. var pathArray;
  44668. if (instance) {
  44669. path3D = (instance.path3D).update(curve);
  44670. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  44671. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  44672. return instance;
  44673. }
  44674. // extruded shape creation
  44675. path3D = new BABYLON.Path3D(curve);
  44676. var newShapePaths = new Array();
  44677. cap = (cap < 0 || cap > 3) ? 0 : cap;
  44678. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  44679. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  44680. extrudedGeneric.pathArray = pathArray;
  44681. extrudedGeneric.path3D = path3D;
  44682. extrudedGeneric.cap = cap;
  44683. return extrudedGeneric;
  44684. };
  44685. return MeshBuilder;
  44686. }());
  44687. BABYLON.MeshBuilder = MeshBuilder;
  44688. })(BABYLON || (BABYLON = {}));
  44689. //# sourceMappingURL=babylon.meshBuilder.js.map
  44690. var BABYLON;
  44691. (function (BABYLON) {
  44692. var AudioEngine = (function () {
  44693. function AudioEngine() {
  44694. this._audioContext = null;
  44695. this._audioContextInitialized = false;
  44696. this.canUseWebAudio = false;
  44697. this.WarnedWebAudioUnsupported = false;
  44698. this.unlocked = false;
  44699. this.isMP3supported = false;
  44700. this.isOGGsupported = false;
  44701. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  44702. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  44703. this.canUseWebAudio = true;
  44704. }
  44705. var audioElem = document.createElement('audio');
  44706. try {
  44707. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  44708. this.isMP3supported = true;
  44709. }
  44710. }
  44711. catch (e) {
  44712. // protect error during capability check.
  44713. }
  44714. try {
  44715. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  44716. this.isOGGsupported = true;
  44717. }
  44718. }
  44719. catch (e) {
  44720. // protect error during capability check.
  44721. }
  44722. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  44723. this._unlockiOSaudio();
  44724. }
  44725. else {
  44726. this.unlocked = true;
  44727. }
  44728. }
  44729. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  44730. get: function () {
  44731. if (!this._audioContextInitialized) {
  44732. this._initializeAudioContext();
  44733. }
  44734. return this._audioContext;
  44735. },
  44736. enumerable: true,
  44737. configurable: true
  44738. });
  44739. AudioEngine.prototype._unlockiOSaudio = function () {
  44740. var _this = this;
  44741. var unlockaudio = function () {
  44742. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  44743. var source = _this.audioContext.createBufferSource();
  44744. source.buffer = buffer;
  44745. source.connect(_this.audioContext.destination);
  44746. source.start(0);
  44747. setTimeout(function () {
  44748. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  44749. _this.unlocked = true;
  44750. window.removeEventListener('touchend', unlockaudio, false);
  44751. if (_this.onAudioUnlocked) {
  44752. _this.onAudioUnlocked();
  44753. }
  44754. }
  44755. }, 0);
  44756. };
  44757. window.addEventListener('touchend', unlockaudio, false);
  44758. };
  44759. AudioEngine.prototype._initializeAudioContext = function () {
  44760. try {
  44761. if (this.canUseWebAudio) {
  44762. this._audioContext = new AudioContext();
  44763. // create a global volume gain node
  44764. this.masterGain = this._audioContext.createGain();
  44765. this.masterGain.gain.value = 1;
  44766. this.masterGain.connect(this._audioContext.destination);
  44767. this._audioContextInitialized = true;
  44768. }
  44769. }
  44770. catch (e) {
  44771. this.canUseWebAudio = false;
  44772. BABYLON.Tools.Error("Web Audio: " + e.message);
  44773. }
  44774. };
  44775. AudioEngine.prototype.dispose = function () {
  44776. if (this.canUseWebAudio && this._audioContextInitialized) {
  44777. if (this._connectedAnalyser) {
  44778. this._connectedAnalyser.stopDebugCanvas();
  44779. this._connectedAnalyser.dispose();
  44780. this.masterGain.disconnect();
  44781. this.masterGain.connect(this._audioContext.destination);
  44782. this._connectedAnalyser = null;
  44783. }
  44784. this.masterGain.gain.value = 1;
  44785. }
  44786. this.WarnedWebAudioUnsupported = false;
  44787. };
  44788. AudioEngine.prototype.getGlobalVolume = function () {
  44789. if (this.canUseWebAudio && this._audioContextInitialized) {
  44790. return this.masterGain.gain.value;
  44791. }
  44792. else {
  44793. return -1;
  44794. }
  44795. };
  44796. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  44797. if (this.canUseWebAudio && this._audioContextInitialized) {
  44798. this.masterGain.gain.value = newVolume;
  44799. }
  44800. };
  44801. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  44802. if (this._connectedAnalyser) {
  44803. this._connectedAnalyser.stopDebugCanvas();
  44804. }
  44805. if (this.canUseWebAudio && this._audioContextInitialized) {
  44806. this._connectedAnalyser = analyser;
  44807. this.masterGain.disconnect();
  44808. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  44809. }
  44810. };
  44811. return AudioEngine;
  44812. }());
  44813. BABYLON.AudioEngine = AudioEngine;
  44814. })(BABYLON || (BABYLON = {}));
  44815. //# sourceMappingURL=babylon.audioEngine.js.map
  44816. var BABYLON;
  44817. (function (BABYLON) {
  44818. var Sound = (function () {
  44819. /**
  44820. * Create a sound and attach it to a scene
  44821. * @param name Name of your sound
  44822. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  44823. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  44824. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  44825. */
  44826. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  44827. var _this = this;
  44828. this.autoplay = false;
  44829. this.loop = false;
  44830. this.useCustomAttenuation = false;
  44831. this.spatialSound = false;
  44832. this.refDistance = 1;
  44833. this.rolloffFactor = 1;
  44834. this.maxDistance = 100;
  44835. this.distanceModel = "linear";
  44836. this._panningModel = "equalpower";
  44837. this._playbackRate = 1;
  44838. this._streaming = false;
  44839. this._startTime = 0;
  44840. this._startOffset = 0;
  44841. this._position = BABYLON.Vector3.Zero();
  44842. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  44843. this._volume = 1;
  44844. this._isLoaded = false;
  44845. this._isReadyToPlay = false;
  44846. this.isPlaying = false;
  44847. this.isPaused = false;
  44848. this._isDirectional = false;
  44849. // Used if you'd like to create a directional sound.
  44850. // If not set, the sound will be omnidirectional
  44851. this._coneInnerAngle = 360;
  44852. this._coneOuterAngle = 360;
  44853. this._coneOuterGain = 0;
  44854. this._isOutputConnected = false;
  44855. this._urlType = "Unknown";
  44856. this.name = name;
  44857. this._scene = scene;
  44858. this._readyToPlayCallback = readyToPlayCallback;
  44859. // Default custom attenuation function is a linear attenuation
  44860. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  44861. if (currentDistance < maxDistance) {
  44862. return currentVolume * (1 - currentDistance / maxDistance);
  44863. }
  44864. else {
  44865. return 0;
  44866. }
  44867. };
  44868. if (options) {
  44869. this.autoplay = options.autoplay || false;
  44870. this.loop = options.loop || false;
  44871. // if volume === 0, we need another way to check this option
  44872. if (options.volume !== undefined) {
  44873. this._volume = options.volume;
  44874. }
  44875. this.spatialSound = options.spatialSound || false;
  44876. this.maxDistance = options.maxDistance || 100;
  44877. this.useCustomAttenuation = options.useCustomAttenuation || false;
  44878. this.rolloffFactor = options.rolloffFactor || 1;
  44879. this.refDistance = options.refDistance || 1;
  44880. this.distanceModel = options.distanceModel || "linear";
  44881. this._playbackRate = options.playbackRate || 1;
  44882. this._streaming = options.streaming || false;
  44883. }
  44884. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44885. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  44886. this._soundGain.gain.value = this._volume;
  44887. this._inputAudioNode = this._soundGain;
  44888. this._ouputAudioNode = this._soundGain;
  44889. if (this.spatialSound) {
  44890. this._createSpatialParameters();
  44891. }
  44892. this._scene.mainSoundTrack.AddSound(this);
  44893. var validParameter = true;
  44894. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  44895. if (urlOrArrayBuffer) {
  44896. if (typeof (urlOrArrayBuffer) === "string")
  44897. this._urlType = "String";
  44898. if (Array.isArray(urlOrArrayBuffer))
  44899. this._urlType = "Array";
  44900. if (urlOrArrayBuffer instanceof ArrayBuffer)
  44901. this._urlType = "ArrayBuffer";
  44902. var urls = [];
  44903. var codecSupportedFound = false;
  44904. switch (this._urlType) {
  44905. case "ArrayBuffer":
  44906. if (urlOrArrayBuffer.byteLength > 0) {
  44907. codecSupportedFound = true;
  44908. this._soundLoaded(urlOrArrayBuffer);
  44909. }
  44910. break;
  44911. case "String":
  44912. urls.push(urlOrArrayBuffer);
  44913. case "Array":
  44914. if (urls.length === 0)
  44915. urls = urlOrArrayBuffer;
  44916. // If we found a supported format, we load it immediately and stop the loop
  44917. for (var i = 0; i < urls.length; i++) {
  44918. var url = urls[i];
  44919. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  44920. codecSupportedFound = true;
  44921. }
  44922. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  44923. codecSupportedFound = true;
  44924. }
  44925. if (url.indexOf(".wav", url.length - 4) !== -1) {
  44926. codecSupportedFound = true;
  44927. }
  44928. if (url.indexOf("blob:") !== -1) {
  44929. codecSupportedFound = true;
  44930. }
  44931. if (codecSupportedFound) {
  44932. // Loading sound using XHR2
  44933. if (!this._streaming) {
  44934. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  44935. }
  44936. else {
  44937. this._htmlAudioElement = new Audio(url);
  44938. this._htmlAudioElement.controls = false;
  44939. this._htmlAudioElement.loop = this.loop;
  44940. this._htmlAudioElement.crossOrigin = "anonymous";
  44941. this._htmlAudioElement.preload = "auto";
  44942. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  44943. _this._isReadyToPlay = true;
  44944. if (_this.autoplay) {
  44945. _this.play();
  44946. }
  44947. if (_this._readyToPlayCallback) {
  44948. _this._readyToPlayCallback();
  44949. }
  44950. });
  44951. document.body.appendChild(this._htmlAudioElement);
  44952. }
  44953. break;
  44954. }
  44955. }
  44956. break;
  44957. default:
  44958. validParameter = false;
  44959. break;
  44960. }
  44961. if (!validParameter) {
  44962. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  44963. }
  44964. else {
  44965. if (!codecSupportedFound) {
  44966. this._isReadyToPlay = true;
  44967. // Simulating a ready to play event to avoid breaking code path
  44968. if (this._readyToPlayCallback) {
  44969. window.setTimeout(function () {
  44970. _this._readyToPlayCallback();
  44971. }, 1000);
  44972. }
  44973. }
  44974. }
  44975. }
  44976. }
  44977. else {
  44978. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  44979. this._scene.mainSoundTrack.AddSound(this);
  44980. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  44981. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  44982. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  44983. }
  44984. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  44985. if (this._readyToPlayCallback) {
  44986. window.setTimeout(function () {
  44987. _this._readyToPlayCallback();
  44988. }, 1000);
  44989. }
  44990. }
  44991. }
  44992. Sound.prototype.dispose = function () {
  44993. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  44994. if (this.isPlaying) {
  44995. this.stop();
  44996. }
  44997. this._isReadyToPlay = false;
  44998. if (this.soundTrackId === -1) {
  44999. this._scene.mainSoundTrack.RemoveSound(this);
  45000. }
  45001. else {
  45002. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  45003. }
  45004. if (this._soundGain) {
  45005. this._soundGain.disconnect();
  45006. this._soundGain = null;
  45007. }
  45008. if (this._soundPanner) {
  45009. this._soundPanner.disconnect();
  45010. this._soundPanner = null;
  45011. }
  45012. if (this._soundSource) {
  45013. this._soundSource.disconnect();
  45014. this._soundSource = null;
  45015. }
  45016. this._audioBuffer = null;
  45017. if (this._htmlAudioElement) {
  45018. this._htmlAudioElement.pause();
  45019. this._htmlAudioElement.src = "";
  45020. document.body.removeChild(this._htmlAudioElement);
  45021. }
  45022. if (this._connectedMesh) {
  45023. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  45024. this._connectedMesh = null;
  45025. }
  45026. }
  45027. };
  45028. Sound.prototype.isReady = function () {
  45029. return this._isReadyToPlay;
  45030. };
  45031. Sound.prototype._soundLoaded = function (audioData) {
  45032. var _this = this;
  45033. this._isLoaded = true;
  45034. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  45035. _this._audioBuffer = buffer;
  45036. _this._isReadyToPlay = true;
  45037. if (_this.autoplay) {
  45038. _this.play();
  45039. }
  45040. if (_this._readyToPlayCallback) {
  45041. _this._readyToPlayCallback();
  45042. }
  45043. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  45044. };
  45045. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  45046. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45047. this._audioBuffer = audioBuffer;
  45048. this._isReadyToPlay = true;
  45049. }
  45050. };
  45051. Sound.prototype.updateOptions = function (options) {
  45052. if (options) {
  45053. this.loop = options.loop || this.loop;
  45054. this.maxDistance = options.maxDistance || this.maxDistance;
  45055. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  45056. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  45057. this.refDistance = options.refDistance || this.refDistance;
  45058. this.distanceModel = options.distanceModel || this.distanceModel;
  45059. this._playbackRate = options.playbackRate || this._playbackRate;
  45060. this._updateSpatialParameters();
  45061. if (this.isPlaying) {
  45062. if (this._streaming) {
  45063. this._htmlAudioElement.playbackRate = this._playbackRate;
  45064. }
  45065. else {
  45066. this._soundSource.playbackRate.value = this._playbackRate;
  45067. }
  45068. }
  45069. }
  45070. };
  45071. Sound.prototype._createSpatialParameters = function () {
  45072. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45073. if (this._scene.headphone) {
  45074. this._panningModel = "HRTF";
  45075. }
  45076. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  45077. this._updateSpatialParameters();
  45078. this._soundPanner.connect(this._ouputAudioNode);
  45079. this._inputAudioNode = this._soundPanner;
  45080. }
  45081. };
  45082. Sound.prototype._updateSpatialParameters = function () {
  45083. if (this.spatialSound) {
  45084. if (this.useCustomAttenuation) {
  45085. // Tricks to disable in a way embedded Web Audio attenuation
  45086. this._soundPanner.distanceModel = "linear";
  45087. this._soundPanner.maxDistance = Number.MAX_VALUE;
  45088. this._soundPanner.refDistance = 1;
  45089. this._soundPanner.rolloffFactor = 1;
  45090. this._soundPanner.panningModel = this._panningModel;
  45091. }
  45092. else {
  45093. this._soundPanner.distanceModel = this.distanceModel;
  45094. this._soundPanner.maxDistance = this.maxDistance;
  45095. this._soundPanner.refDistance = this.refDistance;
  45096. this._soundPanner.rolloffFactor = this.rolloffFactor;
  45097. this._soundPanner.panningModel = this._panningModel;
  45098. }
  45099. }
  45100. };
  45101. Sound.prototype.switchPanningModelToHRTF = function () {
  45102. this._panningModel = "HRTF";
  45103. this._switchPanningModel();
  45104. };
  45105. Sound.prototype.switchPanningModelToEqualPower = function () {
  45106. this._panningModel = "equalpower";
  45107. this._switchPanningModel();
  45108. };
  45109. Sound.prototype._switchPanningModel = function () {
  45110. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  45111. this._soundPanner.panningModel = this._panningModel;
  45112. }
  45113. };
  45114. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  45115. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45116. if (this._isOutputConnected) {
  45117. this._ouputAudioNode.disconnect();
  45118. }
  45119. this._ouputAudioNode.connect(soundTrackAudioNode);
  45120. this._isOutputConnected = true;
  45121. }
  45122. };
  45123. /**
  45124. * Transform this sound into a directional source
  45125. * @param coneInnerAngle Size of the inner cone in degree
  45126. * @param coneOuterAngle Size of the outer cone in degree
  45127. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  45128. */
  45129. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  45130. if (coneOuterAngle < coneInnerAngle) {
  45131. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  45132. return;
  45133. }
  45134. this._coneInnerAngle = coneInnerAngle;
  45135. this._coneOuterAngle = coneOuterAngle;
  45136. this._coneOuterGain = coneOuterGain;
  45137. this._isDirectional = true;
  45138. if (this.isPlaying && this.loop) {
  45139. this.stop();
  45140. this.play();
  45141. }
  45142. };
  45143. Sound.prototype.setPosition = function (newPosition) {
  45144. this._position = newPosition;
  45145. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  45146. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  45147. }
  45148. };
  45149. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  45150. this._localDirection = newLocalDirection;
  45151. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  45152. this._updateDirection();
  45153. }
  45154. };
  45155. Sound.prototype._updateDirection = function () {
  45156. var mat = this._connectedMesh.getWorldMatrix();
  45157. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  45158. direction.normalize();
  45159. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  45160. };
  45161. Sound.prototype.updateDistanceFromListener = function () {
  45162. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  45163. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  45164. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  45165. }
  45166. };
  45167. Sound.prototype.setAttenuationFunction = function (callback) {
  45168. this._customAttenuationFunction = callback;
  45169. };
  45170. /**
  45171. * Play the sound
  45172. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  45173. * @param offset (optional) Start the sound setting it at a specific time
  45174. */
  45175. Sound.prototype.play = function (time, offset) {
  45176. var _this = this;
  45177. if (this._isReadyToPlay && this._scene.audioEnabled) {
  45178. try {
  45179. if (this._startOffset < 0) {
  45180. time = -this._startOffset;
  45181. this._startOffset = 0;
  45182. }
  45183. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  45184. if (!this._soundSource || !this._streamingSource) {
  45185. if (this.spatialSound) {
  45186. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  45187. if (this._isDirectional) {
  45188. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  45189. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  45190. this._soundPanner.coneOuterGain = this._coneOuterGain;
  45191. if (this._connectedMesh) {
  45192. this._updateDirection();
  45193. }
  45194. else {
  45195. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  45196. }
  45197. }
  45198. }
  45199. }
  45200. if (this._streaming) {
  45201. if (!this._streamingSource) {
  45202. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  45203. this._htmlAudioElement.onended = function () { _this._onended(); };
  45204. this._htmlAudioElement.playbackRate = this._playbackRate;
  45205. }
  45206. this._streamingSource.disconnect();
  45207. this._streamingSource.connect(this._inputAudioNode);
  45208. this._htmlAudioElement.play();
  45209. }
  45210. else {
  45211. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  45212. this._soundSource.buffer = this._audioBuffer;
  45213. this._soundSource.connect(this._inputAudioNode);
  45214. this._soundSource.loop = this.loop;
  45215. this._soundSource.playbackRate.value = this._playbackRate;
  45216. this._soundSource.onended = function () { _this._onended(); };
  45217. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  45218. }
  45219. this._startTime = startTime;
  45220. this.isPlaying = true;
  45221. this.isPaused = false;
  45222. }
  45223. catch (ex) {
  45224. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  45225. }
  45226. }
  45227. };
  45228. Sound.prototype._onended = function () {
  45229. this.isPlaying = false;
  45230. if (this.onended) {
  45231. this.onended();
  45232. }
  45233. };
  45234. /**
  45235. * Stop the sound
  45236. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  45237. */
  45238. Sound.prototype.stop = function (time) {
  45239. if (this.isPlaying) {
  45240. if (this._streaming) {
  45241. this._htmlAudioElement.pause();
  45242. // Test needed for Firefox or it will generate an Invalid State Error
  45243. if (this._htmlAudioElement.currentTime > 0) {
  45244. this._htmlAudioElement.currentTime = 0;
  45245. }
  45246. }
  45247. else {
  45248. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  45249. this._soundSource.stop(stopTime);
  45250. this._soundSource.onended = null;
  45251. if (!this.isPaused) {
  45252. this._startOffset = 0;
  45253. }
  45254. }
  45255. this.isPlaying = false;
  45256. }
  45257. };
  45258. Sound.prototype.pause = function () {
  45259. if (this.isPlaying) {
  45260. this.isPaused = true;
  45261. if (this._streaming) {
  45262. this._htmlAudioElement.pause();
  45263. }
  45264. else {
  45265. this.stop(0);
  45266. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  45267. }
  45268. }
  45269. };
  45270. Sound.prototype.setVolume = function (newVolume, time) {
  45271. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45272. if (time) {
  45273. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  45274. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  45275. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  45276. }
  45277. else {
  45278. this._soundGain.gain.value = newVolume;
  45279. }
  45280. }
  45281. this._volume = newVolume;
  45282. };
  45283. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  45284. this._playbackRate = newPlaybackRate;
  45285. if (this.isPlaying) {
  45286. if (this._streaming) {
  45287. this._htmlAudioElement.playbackRate = this._playbackRate;
  45288. }
  45289. else {
  45290. this._soundSource.playbackRate.value = this._playbackRate;
  45291. }
  45292. }
  45293. };
  45294. Sound.prototype.getVolume = function () {
  45295. return this._volume;
  45296. };
  45297. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  45298. var _this = this;
  45299. if (this._connectedMesh) {
  45300. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  45301. this._registerFunc = null;
  45302. }
  45303. this._connectedMesh = meshToConnectTo;
  45304. if (!this.spatialSound) {
  45305. this.spatialSound = true;
  45306. this._createSpatialParameters();
  45307. if (this.isPlaying && this.loop) {
  45308. this.stop();
  45309. this.play();
  45310. }
  45311. }
  45312. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  45313. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  45314. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  45315. };
  45316. Sound.prototype.detachFromMesh = function () {
  45317. if (this._connectedMesh) {
  45318. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  45319. this._registerFunc = null;
  45320. this._connectedMesh = null;
  45321. }
  45322. };
  45323. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  45324. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  45325. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  45326. this._updateDirection();
  45327. }
  45328. };
  45329. Sound.prototype.clone = function () {
  45330. var _this = this;
  45331. if (!this._streaming) {
  45332. var setBufferAndRun = function () {
  45333. if (_this._isReadyToPlay) {
  45334. clonedSound._audioBuffer = _this.getAudioBuffer();
  45335. clonedSound._isReadyToPlay = true;
  45336. if (clonedSound.autoplay) {
  45337. clonedSound.play();
  45338. }
  45339. }
  45340. else {
  45341. window.setTimeout(setBufferAndRun, 300);
  45342. }
  45343. };
  45344. var currentOptions = {
  45345. autoplay: this.autoplay, loop: this.loop,
  45346. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  45347. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  45348. refDistance: this.refDistance, distanceModel: this.distanceModel
  45349. };
  45350. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  45351. if (this.useCustomAttenuation) {
  45352. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  45353. }
  45354. clonedSound.setPosition(this._position);
  45355. clonedSound.setPlaybackRate(this._playbackRate);
  45356. setBufferAndRun();
  45357. return clonedSound;
  45358. }
  45359. else {
  45360. return null;
  45361. }
  45362. };
  45363. Sound.prototype.getAudioBuffer = function () {
  45364. return this._audioBuffer;
  45365. };
  45366. Sound.prototype.serialize = function () {
  45367. var serializationObject = {
  45368. name: this.name,
  45369. url: this.name,
  45370. autoplay: this.autoplay,
  45371. loop: this.loop,
  45372. volume: this._volume,
  45373. spatialSound: this.spatialSound,
  45374. maxDistance: this.maxDistance,
  45375. rolloffFactor: this.rolloffFactor,
  45376. refDistance: this.refDistance,
  45377. distanceModel: this.distanceModel,
  45378. playbackRate: this._playbackRate,
  45379. panningModel: this._panningModel,
  45380. soundTrackId: this.soundTrackId
  45381. };
  45382. if (this.spatialSound) {
  45383. if (this._connectedMesh)
  45384. serializationObject.connectedMeshId = this._connectedMesh.id;
  45385. serializationObject.position = this._position.asArray();
  45386. serializationObject.refDistance = this.refDistance;
  45387. serializationObject.distanceModel = this.distanceModel;
  45388. serializationObject.isDirectional = this._isDirectional;
  45389. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  45390. serializationObject.coneInnerAngle = this._coneInnerAngle;
  45391. serializationObject.coneOuterAngle = this._coneOuterAngle;
  45392. serializationObject.coneOuterGain = this._coneOuterGain;
  45393. }
  45394. return serializationObject;
  45395. };
  45396. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  45397. var soundName = parsedSound.name;
  45398. var soundUrl;
  45399. if (parsedSound.url) {
  45400. soundUrl = rootUrl + parsedSound.url;
  45401. }
  45402. else {
  45403. soundUrl = rootUrl + soundName;
  45404. }
  45405. var options = {
  45406. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  45407. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  45408. rolloffFactor: parsedSound.rolloffFactor,
  45409. refDistance: parsedSound.refDistance,
  45410. distanceModel: parsedSound.distanceModel,
  45411. playbackRate: parsedSound.playbackRate
  45412. };
  45413. var newSound;
  45414. if (!sourceSound) {
  45415. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  45416. scene._addPendingData(newSound);
  45417. }
  45418. else {
  45419. var setBufferAndRun = function () {
  45420. if (sourceSound._isReadyToPlay) {
  45421. newSound._audioBuffer = sourceSound.getAudioBuffer();
  45422. newSound._isReadyToPlay = true;
  45423. if (newSound.autoplay) {
  45424. newSound.play();
  45425. }
  45426. }
  45427. else {
  45428. window.setTimeout(setBufferAndRun, 300);
  45429. }
  45430. };
  45431. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  45432. setBufferAndRun();
  45433. }
  45434. if (parsedSound.position) {
  45435. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  45436. newSound.setPosition(soundPosition);
  45437. }
  45438. if (parsedSound.isDirectional) {
  45439. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  45440. if (parsedSound.localDirectionToMesh) {
  45441. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  45442. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  45443. }
  45444. }
  45445. if (parsedSound.connectedMeshId) {
  45446. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  45447. if (connectedMesh) {
  45448. newSound.attachToMesh(connectedMesh);
  45449. }
  45450. }
  45451. return newSound;
  45452. };
  45453. return Sound;
  45454. }());
  45455. BABYLON.Sound = Sound;
  45456. })(BABYLON || (BABYLON = {}));
  45457. //# sourceMappingURL=babylon.sound.js.map
  45458. var BABYLON;
  45459. (function (BABYLON) {
  45460. var SoundTrack = (function () {
  45461. function SoundTrack(scene, options) {
  45462. this.id = -1;
  45463. this._isMainTrack = false;
  45464. this._isInitialized = false;
  45465. this._scene = scene;
  45466. this.soundCollection = new Array();
  45467. this._options = options;
  45468. if (!this._isMainTrack) {
  45469. this._scene.soundTracks.push(this);
  45470. this.id = this._scene.soundTracks.length - 1;
  45471. }
  45472. }
  45473. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  45474. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45475. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  45476. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  45477. if (this._options) {
  45478. if (this._options.volume) {
  45479. this._outputAudioNode.gain.value = this._options.volume;
  45480. }
  45481. if (this._options.mainTrack) {
  45482. this._isMainTrack = this._options.mainTrack;
  45483. }
  45484. }
  45485. this._isInitialized = true;
  45486. }
  45487. };
  45488. SoundTrack.prototype.dispose = function () {
  45489. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45490. if (this._connectedAnalyser) {
  45491. this._connectedAnalyser.stopDebugCanvas();
  45492. }
  45493. while (this.soundCollection.length) {
  45494. this.soundCollection[0].dispose();
  45495. }
  45496. if (this._outputAudioNode) {
  45497. this._outputAudioNode.disconnect();
  45498. }
  45499. this._outputAudioNode = null;
  45500. }
  45501. };
  45502. SoundTrack.prototype.AddSound = function (sound) {
  45503. if (!this._isInitialized) {
  45504. this._initializeSoundTrackAudioGraph();
  45505. }
  45506. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45507. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  45508. }
  45509. if (sound.soundTrackId) {
  45510. if (sound.soundTrackId === -1) {
  45511. this._scene.mainSoundTrack.RemoveSound(sound);
  45512. }
  45513. else {
  45514. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  45515. }
  45516. }
  45517. this.soundCollection.push(sound);
  45518. sound.soundTrackId = this.id;
  45519. };
  45520. SoundTrack.prototype.RemoveSound = function (sound) {
  45521. var index = this.soundCollection.indexOf(sound);
  45522. if (index !== -1) {
  45523. this.soundCollection.splice(index, 1);
  45524. }
  45525. };
  45526. SoundTrack.prototype.setVolume = function (newVolume) {
  45527. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45528. this._outputAudioNode.gain.value = newVolume;
  45529. }
  45530. };
  45531. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  45532. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45533. for (var i = 0; i < this.soundCollection.length; i++) {
  45534. this.soundCollection[i].switchPanningModelToHRTF();
  45535. }
  45536. }
  45537. };
  45538. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  45539. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45540. for (var i = 0; i < this.soundCollection.length; i++) {
  45541. this.soundCollection[i].switchPanningModelToEqualPower();
  45542. }
  45543. }
  45544. };
  45545. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  45546. if (this._connectedAnalyser) {
  45547. this._connectedAnalyser.stopDebugCanvas();
  45548. }
  45549. this._connectedAnalyser = analyser;
  45550. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  45551. this._outputAudioNode.disconnect();
  45552. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  45553. }
  45554. };
  45555. return SoundTrack;
  45556. }());
  45557. BABYLON.SoundTrack = SoundTrack;
  45558. })(BABYLON || (BABYLON = {}));
  45559. //# sourceMappingURL=babylon.soundtrack.js.map
  45560. var BABYLON;
  45561. (function (BABYLON) {
  45562. var Analyser = (function () {
  45563. function Analyser(scene) {
  45564. this.SMOOTHING = 0.75;
  45565. this.FFT_SIZE = 512;
  45566. this.BARGRAPHAMPLITUDE = 256;
  45567. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  45568. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  45569. this._scene = scene;
  45570. this._audioEngine = BABYLON.Engine.audioEngine;
  45571. if (this._audioEngine.canUseWebAudio) {
  45572. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  45573. this._webAudioAnalyser.minDecibels = -140;
  45574. this._webAudioAnalyser.maxDecibels = 0;
  45575. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  45576. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  45577. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  45578. }
  45579. }
  45580. Analyser.prototype.getFrequencyBinCount = function () {
  45581. if (this._audioEngine.canUseWebAudio) {
  45582. return this._webAudioAnalyser.frequencyBinCount;
  45583. }
  45584. else {
  45585. return 0;
  45586. }
  45587. };
  45588. Analyser.prototype.getByteFrequencyData = function () {
  45589. if (this._audioEngine.canUseWebAudio) {
  45590. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45591. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45592. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  45593. }
  45594. return this._byteFreqs;
  45595. };
  45596. Analyser.prototype.getByteTimeDomainData = function () {
  45597. if (this._audioEngine.canUseWebAudio) {
  45598. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45599. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45600. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  45601. }
  45602. return this._byteTime;
  45603. };
  45604. Analyser.prototype.getFloatFrequencyData = function () {
  45605. if (this._audioEngine.canUseWebAudio) {
  45606. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45607. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45608. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  45609. }
  45610. return this._floatFreqs;
  45611. };
  45612. Analyser.prototype.drawDebugCanvas = function () {
  45613. var _this = this;
  45614. if (this._audioEngine.canUseWebAudio) {
  45615. if (!this._debugCanvas) {
  45616. this._debugCanvas = document.createElement("canvas");
  45617. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  45618. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  45619. this._debugCanvas.style.position = "absolute";
  45620. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  45621. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  45622. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  45623. document.body.appendChild(this._debugCanvas);
  45624. this._registerFunc = function () {
  45625. _this.drawDebugCanvas();
  45626. };
  45627. this._scene.registerBeforeRender(this._registerFunc);
  45628. }
  45629. if (this._registerFunc) {
  45630. var workingArray = this.getByteFrequencyData();
  45631. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  45632. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  45633. // Draw the frequency domain chart.
  45634. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  45635. var value = workingArray[i];
  45636. var percent = value / this.BARGRAPHAMPLITUDE;
  45637. var height = this.DEBUGCANVASSIZE.height * percent;
  45638. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  45639. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  45640. var hue = i / this.getFrequencyBinCount() * 360;
  45641. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  45642. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  45643. }
  45644. }
  45645. }
  45646. };
  45647. Analyser.prototype.stopDebugCanvas = function () {
  45648. if (this._debugCanvas) {
  45649. this._scene.unregisterBeforeRender(this._registerFunc);
  45650. this._registerFunc = null;
  45651. document.body.removeChild(this._debugCanvas);
  45652. this._debugCanvas = null;
  45653. this._debugCanvasContext = null;
  45654. }
  45655. };
  45656. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  45657. if (this._audioEngine.canUseWebAudio) {
  45658. inputAudioNode.connect(this._webAudioAnalyser);
  45659. this._webAudioAnalyser.connect(outputAudioNode);
  45660. }
  45661. };
  45662. Analyser.prototype.dispose = function () {
  45663. if (this._audioEngine.canUseWebAudio) {
  45664. this._webAudioAnalyser.disconnect();
  45665. }
  45666. };
  45667. return Analyser;
  45668. }());
  45669. BABYLON.Analyser = Analyser;
  45670. })(BABYLON || (BABYLON = {}));
  45671. //# sourceMappingURL=babylon.analyser.js.map
  45672. var BABYLON;
  45673. (function (BABYLON) {
  45674. var CubeTexture = (function (_super) {
  45675. __extends(CubeTexture, _super);
  45676. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  45677. if (onLoad === void 0) { onLoad = null; }
  45678. if (onError === void 0) { onError = null; }
  45679. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  45680. if (prefiltered === void 0) { prefiltered = false; }
  45681. if (forcedExtension === void 0) { forcedExtension = null; }
  45682. var _this = _super.call(this, scene) || this;
  45683. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  45684. _this.name = rootUrl;
  45685. _this.url = rootUrl;
  45686. _this._noMipmap = noMipmap;
  45687. _this.hasAlpha = false;
  45688. _this._format = format;
  45689. _this._prefiltered = prefiltered;
  45690. _this.isCube = true;
  45691. _this._textureMatrix = BABYLON.Matrix.Identity();
  45692. if (prefiltered) {
  45693. _this.gammaSpace = false;
  45694. }
  45695. if (!rootUrl && !files) {
  45696. return _this;
  45697. }
  45698. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  45699. if (!files) {
  45700. if (!extensions) {
  45701. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  45702. }
  45703. files = [];
  45704. for (var index = 0; index < extensions.length; index++) {
  45705. files.push(rootUrl + extensions[index]);
  45706. }
  45707. _this._extensions = extensions;
  45708. }
  45709. _this._files = files;
  45710. if (!_this._texture) {
  45711. if (!scene.useDelayedTextureLoading) {
  45712. if (prefiltered) {
  45713. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  45714. }
  45715. else {
  45716. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  45717. }
  45718. }
  45719. else {
  45720. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  45721. }
  45722. }
  45723. else if (onLoad) {
  45724. if (_this._texture.isReady) {
  45725. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  45726. }
  45727. else {
  45728. _this._texture.onLoadedObservable.add(onLoad);
  45729. }
  45730. }
  45731. return _this;
  45732. }
  45733. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  45734. return new CubeTexture("", scene, null, noMipmap, files);
  45735. };
  45736. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  45737. if (forcedExtension === void 0) { forcedExtension = null; }
  45738. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  45739. };
  45740. // Methods
  45741. CubeTexture.prototype.delayLoad = function () {
  45742. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  45743. return;
  45744. }
  45745. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  45746. this._texture = this._getFromCache(this.url, this._noMipmap);
  45747. if (!this._texture) {
  45748. if (this._prefiltered) {
  45749. this._texture = this.getScene().getEngine().createPrefilteredCubeTexture(this.url, this.getScene(), this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  45750. }
  45751. else {
  45752. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  45753. }
  45754. }
  45755. };
  45756. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  45757. return this._textureMatrix;
  45758. };
  45759. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  45760. this._textureMatrix = value;
  45761. };
  45762. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  45763. var texture = BABYLON.SerializationHelper.Parse(function () {
  45764. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  45765. }, parsedTexture, scene);
  45766. // Animations
  45767. if (parsedTexture.animations) {
  45768. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  45769. var parsedAnimation = parsedTexture.animations[animationIndex];
  45770. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  45771. }
  45772. }
  45773. return texture;
  45774. };
  45775. CubeTexture.prototype.clone = function () {
  45776. var _this = this;
  45777. return BABYLON.SerializationHelper.Clone(function () {
  45778. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  45779. }, this);
  45780. };
  45781. return CubeTexture;
  45782. }(BABYLON.BaseTexture));
  45783. BABYLON.CubeTexture = CubeTexture;
  45784. })(BABYLON || (BABYLON = {}));
  45785. //# sourceMappingURL=babylon.cubeTexture.js.map
  45786. var BABYLON;
  45787. (function (BABYLON) {
  45788. var RenderTargetTexture = (function (_super) {
  45789. __extends(RenderTargetTexture, _super);
  45790. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  45791. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  45792. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  45793. if (isCube === void 0) { isCube = false; }
  45794. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45795. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  45796. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  45797. if (isMulti === void 0) { isMulti = false; }
  45798. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  45799. _this.isCube = isCube;
  45800. /**
  45801. * Use this list to define the list of mesh you want to render.
  45802. */
  45803. _this.renderList = new Array();
  45804. _this.renderParticles = true;
  45805. _this.renderSprites = false;
  45806. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  45807. _this.ignoreCameraViewport = false;
  45808. // Events
  45809. /**
  45810. * An event triggered when the texture is unbind.
  45811. * @type {BABYLON.Observable}
  45812. */
  45813. _this.onBeforeBindObservable = new BABYLON.Observable();
  45814. /**
  45815. * An event triggered when the texture is unbind.
  45816. * @type {BABYLON.Observable}
  45817. */
  45818. _this.onAfterUnbindObservable = new BABYLON.Observable();
  45819. /**
  45820. * An event triggered before rendering the texture
  45821. * @type {BABYLON.Observable}
  45822. */
  45823. _this.onBeforeRenderObservable = new BABYLON.Observable();
  45824. /**
  45825. * An event triggered after rendering the texture
  45826. * @type {BABYLON.Observable}
  45827. */
  45828. _this.onAfterRenderObservable = new BABYLON.Observable();
  45829. /**
  45830. * An event triggered after the texture clear
  45831. * @type {BABYLON.Observable}
  45832. */
  45833. _this.onClearObservable = new BABYLON.Observable();
  45834. _this._currentRefreshId = -1;
  45835. _this._refreshRate = 1;
  45836. _this._samples = 1;
  45837. scene = _this.getScene();
  45838. _this.name = name;
  45839. _this.isRenderTarget = true;
  45840. _this._size = size;
  45841. _this._generateMipMaps = generateMipMaps;
  45842. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  45843. // Rendering groups
  45844. _this._renderingManager = new BABYLON.RenderingManager(scene);
  45845. if (isMulti) {
  45846. return _this;
  45847. }
  45848. _this._renderTargetOptions = {
  45849. generateMipMaps: generateMipMaps,
  45850. type: type,
  45851. samplingMode: samplingMode,
  45852. generateDepthBuffer: generateDepthBuffer,
  45853. generateStencilBuffer: generateStencilBuffer
  45854. };
  45855. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  45856. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45857. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45858. }
  45859. if (isCube) {
  45860. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  45861. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  45862. _this._textureMatrix = BABYLON.Matrix.Identity();
  45863. }
  45864. else {
  45865. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  45866. }
  45867. return _this;
  45868. }
  45869. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  45870. get: function () {
  45871. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  45872. },
  45873. enumerable: true,
  45874. configurable: true
  45875. });
  45876. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  45877. get: function () {
  45878. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  45879. },
  45880. enumerable: true,
  45881. configurable: true
  45882. });
  45883. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  45884. get: function () {
  45885. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  45886. },
  45887. enumerable: true,
  45888. configurable: true
  45889. });
  45890. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  45891. set: function (callback) {
  45892. if (this._onAfterUnbindObserver) {
  45893. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  45894. }
  45895. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  45896. },
  45897. enumerable: true,
  45898. configurable: true
  45899. });
  45900. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  45901. set: function (callback) {
  45902. if (this._onBeforeRenderObserver) {
  45903. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  45904. }
  45905. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  45906. },
  45907. enumerable: true,
  45908. configurable: true
  45909. });
  45910. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  45911. set: function (callback) {
  45912. if (this._onAfterRenderObserver) {
  45913. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  45914. }
  45915. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  45916. },
  45917. enumerable: true,
  45918. configurable: true
  45919. });
  45920. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  45921. set: function (callback) {
  45922. if (this._onClearObserver) {
  45923. this.onClearObservable.remove(this._onClearObserver);
  45924. }
  45925. this._onClearObserver = this.onClearObservable.add(callback);
  45926. },
  45927. enumerable: true,
  45928. configurable: true
  45929. });
  45930. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  45931. get: function () {
  45932. return this._renderTargetOptions;
  45933. },
  45934. enumerable: true,
  45935. configurable: true
  45936. });
  45937. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  45938. get: function () {
  45939. return this._samples;
  45940. },
  45941. set: function (value) {
  45942. if (this._samples === value) {
  45943. return;
  45944. }
  45945. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  45946. },
  45947. enumerable: true,
  45948. configurable: true
  45949. });
  45950. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  45951. this._currentRefreshId = -1;
  45952. };
  45953. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  45954. get: function () {
  45955. return this._refreshRate;
  45956. },
  45957. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  45958. set: function (value) {
  45959. this._refreshRate = value;
  45960. this.resetRefreshCounter();
  45961. },
  45962. enumerable: true,
  45963. configurable: true
  45964. });
  45965. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  45966. if (!this._postProcessManager) {
  45967. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  45968. this._postProcesses = new Array();
  45969. }
  45970. this._postProcesses.push(postProcess);
  45971. this._postProcesses[0].autoClear = false;
  45972. };
  45973. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  45974. if (!this._postProcesses) {
  45975. return;
  45976. }
  45977. if (dispose) {
  45978. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  45979. var postProcess = _a[_i];
  45980. postProcess.dispose();
  45981. postProcess = null;
  45982. }
  45983. }
  45984. this._postProcesses = [];
  45985. };
  45986. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  45987. if (!this._postProcesses) {
  45988. return;
  45989. }
  45990. var index = this._postProcesses.indexOf(postProcess);
  45991. if (index === -1) {
  45992. return;
  45993. }
  45994. this._postProcesses.splice(index, 1);
  45995. if (this._postProcesses.length > 0) {
  45996. this._postProcesses[0].autoClear = false;
  45997. }
  45998. };
  45999. RenderTargetTexture.prototype._shouldRender = function () {
  46000. if (this._currentRefreshId === -1) {
  46001. this._currentRefreshId = 1;
  46002. return true;
  46003. }
  46004. if (this.refreshRate === this._currentRefreshId) {
  46005. this._currentRefreshId = 1;
  46006. return true;
  46007. }
  46008. this._currentRefreshId++;
  46009. return false;
  46010. };
  46011. RenderTargetTexture.prototype.getRenderSize = function () {
  46012. return this._size;
  46013. };
  46014. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  46015. get: function () {
  46016. return true;
  46017. },
  46018. enumerable: true,
  46019. configurable: true
  46020. });
  46021. RenderTargetTexture.prototype.scale = function (ratio) {
  46022. var newSize = this._size * ratio;
  46023. this.resize(newSize);
  46024. };
  46025. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  46026. if (this.isCube) {
  46027. return this._textureMatrix;
  46028. }
  46029. return _super.prototype.getReflectionTextureMatrix.call(this);
  46030. };
  46031. RenderTargetTexture.prototype.resize = function (size) {
  46032. this.releaseInternalTexture();
  46033. if (this.isCube) {
  46034. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  46035. }
  46036. else {
  46037. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  46038. }
  46039. };
  46040. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  46041. var scene = this.getScene();
  46042. var engine = scene.getEngine();
  46043. if (this.useCameraPostProcesses !== undefined) {
  46044. useCameraPostProcess = this.useCameraPostProcesses;
  46045. }
  46046. if (this._waitingRenderList) {
  46047. this.renderList = [];
  46048. for (var index = 0; index < this._waitingRenderList.length; index++) {
  46049. var id = this._waitingRenderList[index];
  46050. this.renderList.push(scene.getMeshByID(id));
  46051. }
  46052. delete this._waitingRenderList;
  46053. }
  46054. // Is predicate defined?
  46055. if (this.renderListPredicate) {
  46056. this.renderList.splice(0); // Clear previous renderList
  46057. var sceneMeshes = this.getScene().meshes;
  46058. for (var index = 0; index < sceneMeshes.length; index++) {
  46059. var mesh = sceneMeshes[index];
  46060. if (this.renderListPredicate(mesh)) {
  46061. this.renderList.push(mesh);
  46062. }
  46063. }
  46064. }
  46065. if (this.renderList && this.renderList.length === 0) {
  46066. return;
  46067. }
  46068. this.onBeforeBindObservable.notifyObservers(this);
  46069. // Set custom projection.
  46070. // Needs to be before binding to prevent changing the aspect ratio.
  46071. var camera;
  46072. if (this.activeCamera) {
  46073. camera = this.activeCamera;
  46074. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  46075. if (this.activeCamera !== scene.activeCamera) {
  46076. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  46077. }
  46078. }
  46079. else {
  46080. camera = scene.activeCamera;
  46081. engine.setViewport(scene.activeCamera.viewport, this._size, this._size);
  46082. }
  46083. // Prepare renderingManager
  46084. this._renderingManager.reset();
  46085. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  46086. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  46087. var sceneRenderId = scene.getRenderId();
  46088. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  46089. var mesh = currentRenderList[meshIndex];
  46090. if (mesh) {
  46091. if (!mesh.isReady()) {
  46092. // Reset _currentRefreshId
  46093. this.resetRefreshCounter();
  46094. continue;
  46095. }
  46096. mesh._preActivateForIntermediateRendering(sceneRenderId);
  46097. var isMasked = void 0;
  46098. if (!this.renderList) {
  46099. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  46100. }
  46101. else {
  46102. isMasked = false;
  46103. }
  46104. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  46105. mesh._activate(sceneRenderId);
  46106. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  46107. var subMesh = mesh.subMeshes[subIndex];
  46108. scene._activeIndices.addCount(subMesh.indexCount, false);
  46109. this._renderingManager.dispatch(subMesh);
  46110. }
  46111. }
  46112. }
  46113. }
  46114. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  46115. var particleSystem = scene.particleSystems[particleIndex];
  46116. var emitter = particleSystem.emitter;
  46117. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  46118. continue;
  46119. }
  46120. if (currentRenderList.indexOf(emitter) >= 0) {
  46121. this._renderingManager.dispatchParticles(particleSystem);
  46122. }
  46123. }
  46124. if (this.isCube) {
  46125. for (var face = 0; face < 6; face++) {
  46126. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  46127. scene.incrementRenderId();
  46128. scene.resetCachedMaterial();
  46129. }
  46130. }
  46131. else {
  46132. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  46133. }
  46134. this.onAfterUnbindObservable.notifyObservers(this);
  46135. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  46136. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  46137. }
  46138. engine.setViewport(scene.activeCamera.viewport);
  46139. scene.resetCachedMaterial();
  46140. };
  46141. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  46142. var _this = this;
  46143. var scene = this.getScene();
  46144. var engine = scene.getEngine();
  46145. // Bind
  46146. if (this._postProcessManager) {
  46147. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  46148. }
  46149. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  46150. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  46151. }
  46152. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  46153. // Clear
  46154. if (this.onClearObservable.hasObservers()) {
  46155. this.onClearObservable.notifyObservers(engine);
  46156. }
  46157. else {
  46158. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  46159. }
  46160. if (!this._doNotChangeAspectRatio) {
  46161. scene.updateTransformMatrix(true);
  46162. }
  46163. // Render
  46164. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  46165. if (this._postProcessManager) {
  46166. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  46167. }
  46168. else if (useCameraPostProcess) {
  46169. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  46170. }
  46171. if (!this._doNotChangeAspectRatio) {
  46172. scene.updateTransformMatrix(true);
  46173. }
  46174. // Dump ?
  46175. if (dumpForDebug) {
  46176. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  46177. }
  46178. // Unbind
  46179. if (!this.isCube || faceIndex === 5) {
  46180. if (this.isCube) {
  46181. if (faceIndex === 5) {
  46182. engine.generateMipMapsForCubemap(this._texture);
  46183. }
  46184. }
  46185. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  46186. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  46187. });
  46188. }
  46189. else {
  46190. this.onAfterRenderObservable.notifyObservers(faceIndex);
  46191. }
  46192. };
  46193. /**
  46194. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  46195. * This allowed control for front to back rendering or reversly depending of the special needs.
  46196. *
  46197. * @param renderingGroupId The rendering group id corresponding to its index
  46198. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  46199. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  46200. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  46201. */
  46202. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  46203. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  46204. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  46205. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  46206. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  46207. };
  46208. /**
  46209. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  46210. *
  46211. * @param renderingGroupId The rendering group id corresponding to its index
  46212. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  46213. */
  46214. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  46215. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  46216. };
  46217. RenderTargetTexture.prototype.clone = function () {
  46218. var textureSize = this.getSize();
  46219. 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);
  46220. // Base texture
  46221. newTexture.hasAlpha = this.hasAlpha;
  46222. newTexture.level = this.level;
  46223. // RenderTarget Texture
  46224. newTexture.coordinatesMode = this.coordinatesMode;
  46225. newTexture.renderList = this.renderList.slice(0);
  46226. return newTexture;
  46227. };
  46228. RenderTargetTexture.prototype.serialize = function () {
  46229. if (!this.name) {
  46230. return null;
  46231. }
  46232. var serializationObject = _super.prototype.serialize.call(this);
  46233. serializationObject.renderTargetSize = this.getRenderSize();
  46234. serializationObject.renderList = [];
  46235. for (var index = 0; index < this.renderList.length; index++) {
  46236. serializationObject.renderList.push(this.renderList[index].id);
  46237. }
  46238. return serializationObject;
  46239. };
  46240. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  46241. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  46242. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  46243. };
  46244. RenderTargetTexture.prototype.dispose = function () {
  46245. if (this._postProcessManager) {
  46246. this._postProcessManager.dispose();
  46247. this._postProcessManager = null;
  46248. }
  46249. this.clearPostProcesses(true);
  46250. this.renderList = null;
  46251. // Remove from custom render targets
  46252. var scene = this.getScene();
  46253. var index = scene.customRenderTargets.indexOf(this);
  46254. if (index >= 0) {
  46255. scene.customRenderTargets.splice(index, 1);
  46256. }
  46257. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  46258. var camera = _a[_i];
  46259. index = camera.customRenderTargets.indexOf(this);
  46260. if (index >= 0) {
  46261. camera.customRenderTargets.splice(index, 1);
  46262. }
  46263. }
  46264. _super.prototype.dispose.call(this);
  46265. };
  46266. RenderTargetTexture.prototype._rebuild = function () {
  46267. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  46268. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  46269. }
  46270. if (this._postProcessManager) {
  46271. this._postProcessManager._rebuild();
  46272. }
  46273. };
  46274. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  46275. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  46276. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  46277. return RenderTargetTexture;
  46278. }(BABYLON.Texture));
  46279. BABYLON.RenderTargetTexture = RenderTargetTexture;
  46280. })(BABYLON || (BABYLON = {}));
  46281. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  46282. var BABYLON;
  46283. (function (BABYLON) {
  46284. ;
  46285. var MultiRenderTarget = (function (_super) {
  46286. __extends(MultiRenderTarget, _super);
  46287. function MultiRenderTarget(name, size, count, scene, options) {
  46288. var _this = this;
  46289. options = options || {};
  46290. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  46291. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  46292. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  46293. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  46294. if (!_this.isSupported) {
  46295. _this.dispose();
  46296. return;
  46297. }
  46298. var types = [];
  46299. var samplingModes = [];
  46300. for (var i = 0; i < count; i++) {
  46301. if (options.types && options.types[i]) {
  46302. types.push(options.types[i]);
  46303. }
  46304. else {
  46305. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  46306. }
  46307. if (options.samplingModes && options.samplingModes[i]) {
  46308. samplingModes.push(options.samplingModes[i]);
  46309. }
  46310. else {
  46311. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46312. }
  46313. }
  46314. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  46315. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  46316. _this._count = count;
  46317. _this._size = size;
  46318. _this._multiRenderTargetOptions = {
  46319. samplingModes: samplingModes,
  46320. generateMipMaps: generateMipMaps,
  46321. generateDepthBuffer: generateDepthBuffer,
  46322. generateStencilBuffer: generateStencilBuffer,
  46323. generateDepthTexture: generateDepthTexture,
  46324. types: types,
  46325. textureCount: count
  46326. };
  46327. _this._createInternalTextures();
  46328. _this._createTextures();
  46329. return _this;
  46330. }
  46331. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  46332. get: function () {
  46333. var engine = this.getScene().getEngine();
  46334. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  46335. },
  46336. enumerable: true,
  46337. configurable: true
  46338. });
  46339. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  46340. get: function () {
  46341. return this._textures;
  46342. },
  46343. enumerable: true,
  46344. configurable: true
  46345. });
  46346. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  46347. get: function () {
  46348. return this._textures[this._textures.length - 1];
  46349. },
  46350. enumerable: true,
  46351. configurable: true
  46352. });
  46353. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  46354. set: function (wrap) {
  46355. if (this._textures) {
  46356. for (var i = 0; i < this._textures.length; i++) {
  46357. this._textures[i].wrapU = wrap;
  46358. }
  46359. }
  46360. },
  46361. enumerable: true,
  46362. configurable: true
  46363. });
  46364. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  46365. set: function (wrap) {
  46366. if (this._textures) {
  46367. for (var i = 0; i < this._textures.length; i++) {
  46368. this._textures[i].wrapV = wrap;
  46369. }
  46370. }
  46371. },
  46372. enumerable: true,
  46373. configurable: true
  46374. });
  46375. MultiRenderTarget.prototype._rebuild = function () {
  46376. this.releaseInternalTextures();
  46377. this._createInternalTextures();
  46378. for (var i = 0; i < this._internalTextures.length; i++) {
  46379. var texture = this._textures[i];
  46380. texture._texture = this._internalTextures[i];
  46381. }
  46382. // Keeps references to frame buffer and stencil/depth buffer
  46383. this._texture = this._internalTextures[0];
  46384. };
  46385. MultiRenderTarget.prototype._createInternalTextures = function () {
  46386. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  46387. };
  46388. MultiRenderTarget.prototype._createTextures = function () {
  46389. this._textures = [];
  46390. for (var i = 0; i < this._internalTextures.length; i++) {
  46391. var texture = new BABYLON.Texture(null, this.getScene());
  46392. texture._texture = this._internalTextures[i];
  46393. this._textures.push(texture);
  46394. }
  46395. // Keeps references to frame buffer and stencil/depth buffer
  46396. this._texture = this._internalTextures[0];
  46397. };
  46398. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  46399. get: function () {
  46400. return this._samples;
  46401. },
  46402. set: function (value) {
  46403. if (this._samples === value) {
  46404. return;
  46405. }
  46406. for (var i = 0; i < this._internalTextures.length; i++) {
  46407. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  46408. }
  46409. },
  46410. enumerable: true,
  46411. configurable: true
  46412. });
  46413. MultiRenderTarget.prototype.resize = function (size) {
  46414. this.releaseInternalTextures();
  46415. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  46416. this._createInternalTextures();
  46417. };
  46418. MultiRenderTarget.prototype.dispose = function () {
  46419. this.releaseInternalTextures();
  46420. _super.prototype.dispose.call(this);
  46421. };
  46422. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  46423. if (!this._internalTextures) {
  46424. return;
  46425. }
  46426. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  46427. if (this._internalTextures[i] !== undefined) {
  46428. this._internalTextures[i].dispose();
  46429. this._internalTextures.splice(i, 1);
  46430. }
  46431. }
  46432. };
  46433. return MultiRenderTarget;
  46434. }(BABYLON.RenderTargetTexture));
  46435. BABYLON.MultiRenderTarget = MultiRenderTarget;
  46436. })(BABYLON || (BABYLON = {}));
  46437. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  46438. /// <reference path="babylon.renderTargetTexture.ts" />
  46439. var BABYLON;
  46440. (function (BABYLON) {
  46441. var MirrorTexture = (function (_super) {
  46442. __extends(MirrorTexture, _super);
  46443. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  46444. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  46445. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  46446. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  46447. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  46448. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  46449. _this._transformMatrix = BABYLON.Matrix.Zero();
  46450. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  46451. _this._blurKernelX = 0;
  46452. _this._blurKernelY = 0;
  46453. _this._blurRatio = 1.0;
  46454. _this.ignoreCameraViewport = true;
  46455. _this.onBeforeRenderObservable.add(function () {
  46456. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  46457. _this._savedViewMatrix = scene.getViewMatrix();
  46458. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  46459. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  46460. scene.clipPlane = _this.mirrorPlane;
  46461. scene.getEngine().cullBackFaces = false;
  46462. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  46463. });
  46464. _this.onAfterRenderObservable.add(function () {
  46465. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  46466. scene.getEngine().cullBackFaces = true;
  46467. scene._mirroredCameraPosition = null;
  46468. delete scene.clipPlane;
  46469. });
  46470. return _this;
  46471. }
  46472. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  46473. get: function () {
  46474. return this._blurRatio;
  46475. },
  46476. set: function (value) {
  46477. if (this._blurRatio === value) {
  46478. return;
  46479. }
  46480. this._blurRatio = value;
  46481. this._preparePostProcesses();
  46482. },
  46483. enumerable: true,
  46484. configurable: true
  46485. });
  46486. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  46487. set: function (value) {
  46488. this.blurKernelX = value;
  46489. this.blurKernelY = value;
  46490. },
  46491. enumerable: true,
  46492. configurable: true
  46493. });
  46494. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  46495. get: function () {
  46496. return this._blurKernelX;
  46497. },
  46498. set: function (value) {
  46499. if (this._blurKernelX === value) {
  46500. return;
  46501. }
  46502. this._blurKernelX = value;
  46503. this._preparePostProcesses();
  46504. },
  46505. enumerable: true,
  46506. configurable: true
  46507. });
  46508. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  46509. get: function () {
  46510. return this._blurKernelY;
  46511. },
  46512. set: function (value) {
  46513. if (this._blurKernelY === value) {
  46514. return;
  46515. }
  46516. this._blurKernelY = value;
  46517. this._preparePostProcesses();
  46518. },
  46519. enumerable: true,
  46520. configurable: true
  46521. });
  46522. MirrorTexture.prototype._preparePostProcesses = function () {
  46523. this.clearPostProcesses(true);
  46524. if (this._blurKernelX && this._blurKernelY) {
  46525. var engine = this.getScene().getEngine();
  46526. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  46527. 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);
  46528. this._blurX.autoClear = false;
  46529. if (this._blurRatio === 1 && this.samples < 2) {
  46530. this._blurX.outputTexture = this._texture;
  46531. }
  46532. else {
  46533. this._blurX.alwaysForcePOT = true;
  46534. }
  46535. 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);
  46536. this._blurY.autoClear = false;
  46537. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  46538. this.addPostProcess(this._blurX);
  46539. this.addPostProcess(this._blurY);
  46540. }
  46541. };
  46542. MirrorTexture.prototype.clone = function () {
  46543. var textureSize = this.getSize();
  46544. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  46545. // Base texture
  46546. newTexture.hasAlpha = this.hasAlpha;
  46547. newTexture.level = this.level;
  46548. // Mirror Texture
  46549. newTexture.mirrorPlane = this.mirrorPlane.clone();
  46550. newTexture.renderList = this.renderList.slice(0);
  46551. return newTexture;
  46552. };
  46553. MirrorTexture.prototype.serialize = function () {
  46554. if (!this.name) {
  46555. return null;
  46556. }
  46557. var serializationObject = _super.prototype.serialize.call(this);
  46558. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  46559. return serializationObject;
  46560. };
  46561. return MirrorTexture;
  46562. }(BABYLON.RenderTargetTexture));
  46563. BABYLON.MirrorTexture = MirrorTexture;
  46564. })(BABYLON || (BABYLON = {}));
  46565. //# sourceMappingURL=babylon.mirrorTexture.js.map
  46566. /// <reference path="babylon.renderTargetTexture.ts" />
  46567. var BABYLON;
  46568. (function (BABYLON) {
  46569. /**
  46570. * Creates a refraction texture used by refraction channel of the standard material.
  46571. * @param name the texture name
  46572. * @param size size of the underlying texture
  46573. * @param scene root scene
  46574. */
  46575. var RefractionTexture = (function (_super) {
  46576. __extends(RefractionTexture, _super);
  46577. function RefractionTexture(name, size, scene, generateMipMaps) {
  46578. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  46579. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  46580. _this.depth = 2.0;
  46581. _this.onBeforeRenderObservable.add(function () {
  46582. scene.clipPlane = _this.refractionPlane;
  46583. });
  46584. _this.onAfterRenderObservable.add(function () {
  46585. delete scene.clipPlane;
  46586. });
  46587. return _this;
  46588. }
  46589. RefractionTexture.prototype.clone = function () {
  46590. var textureSize = this.getSize();
  46591. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  46592. // Base texture
  46593. newTexture.hasAlpha = this.hasAlpha;
  46594. newTexture.level = this.level;
  46595. // Refraction Texture
  46596. newTexture.refractionPlane = this.refractionPlane.clone();
  46597. newTexture.renderList = this.renderList.slice(0);
  46598. newTexture.depth = this.depth;
  46599. return newTexture;
  46600. };
  46601. RefractionTexture.prototype.serialize = function () {
  46602. if (!this.name) {
  46603. return null;
  46604. }
  46605. var serializationObject = _super.prototype.serialize.call(this);
  46606. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  46607. serializationObject.depth = this.depth;
  46608. return serializationObject;
  46609. };
  46610. return RefractionTexture;
  46611. }(BABYLON.RenderTargetTexture));
  46612. BABYLON.RefractionTexture = RefractionTexture;
  46613. })(BABYLON || (BABYLON = {}));
  46614. //# sourceMappingURL=babylon.refractionTexture.js.map
  46615. /// <reference path="babylon.texture.ts" />
  46616. var BABYLON;
  46617. (function (BABYLON) {
  46618. var DynamicTexture = (function (_super) {
  46619. __extends(DynamicTexture, _super);
  46620. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  46621. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46622. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  46623. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  46624. _this.name = name;
  46625. var engine = _this.getScene().getEngine();
  46626. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46627. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46628. _this._generateMipMaps = generateMipMaps;
  46629. if (options.getContext) {
  46630. _this._canvas = options;
  46631. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  46632. }
  46633. else {
  46634. _this._canvas = document.createElement("canvas");
  46635. if (options.width) {
  46636. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  46637. }
  46638. else {
  46639. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  46640. }
  46641. }
  46642. var textureSize = _this.getSize();
  46643. _this._canvas.width = textureSize.width;
  46644. _this._canvas.height = textureSize.height;
  46645. _this._context = _this._canvas.getContext("2d");
  46646. return _this;
  46647. }
  46648. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  46649. get: function () {
  46650. return true;
  46651. },
  46652. enumerable: true,
  46653. configurable: true
  46654. });
  46655. DynamicTexture.prototype._recreate = function (textureSize) {
  46656. this._canvas.width = textureSize.width;
  46657. this._canvas.height = textureSize.height;
  46658. this.releaseInternalTexture();
  46659. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  46660. };
  46661. DynamicTexture.prototype.scale = function (ratio) {
  46662. var textureSize = this.getSize();
  46663. textureSize.width *= ratio;
  46664. textureSize.height *= ratio;
  46665. this._recreate(textureSize);
  46666. };
  46667. DynamicTexture.prototype.scaleTo = function (width, height) {
  46668. var textureSize = this.getSize();
  46669. textureSize.width = width;
  46670. textureSize.height = height;
  46671. this._recreate(textureSize);
  46672. };
  46673. DynamicTexture.prototype.getContext = function () {
  46674. return this._context;
  46675. };
  46676. DynamicTexture.prototype.clear = function () {
  46677. var size = this.getSize();
  46678. this._context.fillRect(0, 0, size.width, size.height);
  46679. };
  46680. DynamicTexture.prototype.update = function (invertY) {
  46681. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  46682. };
  46683. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  46684. if (update === void 0) { update = true; }
  46685. var size = this.getSize();
  46686. if (clearColor) {
  46687. this._context.fillStyle = clearColor;
  46688. this._context.fillRect(0, 0, size.width, size.height);
  46689. }
  46690. this._context.font = font;
  46691. if (x === null || x === undefined) {
  46692. var textSize = this._context.measureText(text);
  46693. x = (size.width - textSize.width) / 2;
  46694. }
  46695. if (y === null || y === undefined) {
  46696. var fontSize = parseInt((font.replace(/\D/g, '')));
  46697. ;
  46698. y = (size.height / 2) + (fontSize / 3.65);
  46699. }
  46700. this._context.fillStyle = color;
  46701. this._context.fillText(text, x, y);
  46702. if (update) {
  46703. this.update(invertY);
  46704. }
  46705. };
  46706. DynamicTexture.prototype.clone = function () {
  46707. var textureSize = this.getSize();
  46708. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  46709. // Base texture
  46710. newTexture.hasAlpha = this.hasAlpha;
  46711. newTexture.level = this.level;
  46712. // Dynamic Texture
  46713. newTexture.wrapU = this.wrapU;
  46714. newTexture.wrapV = this.wrapV;
  46715. return newTexture;
  46716. };
  46717. DynamicTexture.prototype._rebuild = function () {
  46718. this.update();
  46719. };
  46720. return DynamicTexture;
  46721. }(BABYLON.Texture));
  46722. BABYLON.DynamicTexture = DynamicTexture;
  46723. })(BABYLON || (BABYLON = {}));
  46724. //# sourceMappingURL=babylon.dynamicTexture.js.map
  46725. var BABYLON;
  46726. (function (BABYLON) {
  46727. var VideoTexture = (function (_super) {
  46728. __extends(VideoTexture, _super);
  46729. /**
  46730. * Creates a video texture.
  46731. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  46732. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  46733. * @param {BABYLON.Scene} scene is obviously the current scene.
  46734. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  46735. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  46736. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  46737. */
  46738. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  46739. if (generateMipMaps === void 0) { generateMipMaps = false; }
  46740. if (invertY === void 0) { invertY = false; }
  46741. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46742. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  46743. _this._autoLaunch = true;
  46744. var urls;
  46745. _this.name = name;
  46746. if (urlsOrVideo instanceof HTMLVideoElement) {
  46747. _this.video = urlsOrVideo;
  46748. }
  46749. else {
  46750. urls = urlsOrVideo;
  46751. _this.video = document.createElement("video");
  46752. _this.video.autoplay = false;
  46753. _this.video.loop = true;
  46754. }
  46755. _this._generateMipMaps = generateMipMaps;
  46756. _this._samplingMode = samplingMode;
  46757. if (!_this.getScene().getEngine().needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  46758. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  46759. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  46760. }
  46761. else {
  46762. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46763. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46764. _this._generateMipMaps = false;
  46765. }
  46766. if (urls) {
  46767. _this.video.addEventListener("canplay", function () {
  46768. _this._createTexture();
  46769. });
  46770. urls.forEach(function (url) {
  46771. var source = document.createElement("source");
  46772. source.src = url;
  46773. _this.video.appendChild(source);
  46774. });
  46775. }
  46776. else {
  46777. _this._createTexture();
  46778. }
  46779. _this._lastUpdate = BABYLON.Tools.Now;
  46780. return _this;
  46781. }
  46782. VideoTexture.prototype.__setTextureReady = function () {
  46783. this._texture.isReady = true;
  46784. };
  46785. VideoTexture.prototype._createTexture = function () {
  46786. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  46787. if (this._autoLaunch) {
  46788. this._autoLaunch = false;
  46789. this.video.play();
  46790. }
  46791. this._setTextureReady = this.__setTextureReady.bind(this);
  46792. this.video.addEventListener("playing", this._setTextureReady);
  46793. };
  46794. VideoTexture.prototype._rebuild = function () {
  46795. this.update();
  46796. };
  46797. VideoTexture.prototype.update = function () {
  46798. var now = BABYLON.Tools.Now;
  46799. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  46800. return false;
  46801. }
  46802. this._lastUpdate = now;
  46803. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  46804. return true;
  46805. };
  46806. VideoTexture.prototype.dispose = function () {
  46807. _super.prototype.dispose.call(this);
  46808. this.video.removeEventListener("playing", this._setTextureReady);
  46809. };
  46810. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  46811. var video = document.createElement("video");
  46812. var constraintsDeviceId;
  46813. if (constraints && constraints.deviceId) {
  46814. constraintsDeviceId = {
  46815. exact: constraints.deviceId
  46816. };
  46817. }
  46818. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  46819. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  46820. if (navigator.getUserMedia) {
  46821. navigator.getUserMedia({
  46822. video: {
  46823. deviceId: constraintsDeviceId,
  46824. width: {
  46825. min: (constraints && constraints.minWidth) || 256,
  46826. max: (constraints && constraints.maxWidth) || 640
  46827. },
  46828. height: {
  46829. min: (constraints && constraints.minHeight) || 256,
  46830. max: (constraints && constraints.maxHeight) || 480
  46831. }
  46832. }
  46833. }, function (stream) {
  46834. if (video.mozSrcObject !== undefined) {
  46835. video.mozSrcObject = stream;
  46836. }
  46837. else {
  46838. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  46839. }
  46840. video.play();
  46841. if (onReady) {
  46842. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  46843. }
  46844. }, function (e) {
  46845. BABYLON.Tools.Error(e.name);
  46846. });
  46847. }
  46848. };
  46849. return VideoTexture;
  46850. }(BABYLON.Texture));
  46851. BABYLON.VideoTexture = VideoTexture;
  46852. })(BABYLON || (BABYLON = {}));
  46853. //# sourceMappingURL=babylon.videoTexture.js.map
  46854. var BABYLON;
  46855. (function (BABYLON) {
  46856. var RawTexture = (function (_super) {
  46857. __extends(RawTexture, _super);
  46858. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  46859. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46860. if (invertY === void 0) { invertY = false; }
  46861. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46862. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  46863. _this.format = format;
  46864. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  46865. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46866. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46867. return _this;
  46868. }
  46869. RawTexture.prototype.update = function (data) {
  46870. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  46871. };
  46872. // Statics
  46873. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46874. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46875. if (invertY === void 0) { invertY = false; }
  46876. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46877. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  46878. };
  46879. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46880. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46881. if (invertY === void 0) { invertY = false; }
  46882. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46883. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  46884. };
  46885. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46886. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46887. if (invertY === void 0) { invertY = false; }
  46888. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46889. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  46890. };
  46891. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46892. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46893. if (invertY === void 0) { invertY = false; }
  46894. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46895. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  46896. };
  46897. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46898. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46899. if (invertY === void 0) { invertY = false; }
  46900. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46901. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  46902. };
  46903. return RawTexture;
  46904. }(BABYLON.Texture));
  46905. BABYLON.RawTexture = RawTexture;
  46906. })(BABYLON || (BABYLON = {}));
  46907. //# sourceMappingURL=babylon.rawTexture.js.map
  46908. var BABYLON;
  46909. (function (BABYLON) {
  46910. var PostProcess = (function () {
  46911. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  46912. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  46913. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  46914. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  46915. if (blockCompilation === void 0) { blockCompilation = false; }
  46916. this.name = name;
  46917. this.width = -1;
  46918. this.height = -1;
  46919. this.autoClear = true;
  46920. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  46921. /*
  46922. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  46923. Can only be used on a single postprocess or on the last one of a chain.
  46924. */
  46925. this.enablePixelPerfectMode = false;
  46926. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  46927. this.alwaysForcePOT = false;
  46928. this.samples = 1;
  46929. this.adaptScaleToCurrentViewport = false;
  46930. this._reusable = false;
  46931. this._textures = new BABYLON.SmartArray(2);
  46932. this._currentRenderTextureInd = 0;
  46933. this._scaleRatio = new BABYLON.Vector2(1, 1);
  46934. this._texelSize = BABYLON.Vector2.Zero();
  46935. // Events
  46936. /**
  46937. * An event triggered when the postprocess is activated.
  46938. * @type {BABYLON.Observable}
  46939. */
  46940. this.onActivateObservable = new BABYLON.Observable();
  46941. /**
  46942. * An event triggered when the postprocess changes its size.
  46943. * @type {BABYLON.Observable}
  46944. */
  46945. this.onSizeChangedObservable = new BABYLON.Observable();
  46946. /**
  46947. * An event triggered when the postprocess applies its effect.
  46948. * @type {BABYLON.Observable}
  46949. */
  46950. this.onApplyObservable = new BABYLON.Observable();
  46951. /**
  46952. * An event triggered before rendering the postprocess
  46953. * @type {BABYLON.Observable}
  46954. */
  46955. this.onBeforeRenderObservable = new BABYLON.Observable();
  46956. /**
  46957. * An event triggered after rendering the postprocess
  46958. * @type {BABYLON.Observable}
  46959. */
  46960. this.onAfterRenderObservable = new BABYLON.Observable();
  46961. if (camera != null) {
  46962. this._camera = camera;
  46963. this._scene = camera.getScene();
  46964. camera.attachPostProcess(this);
  46965. this._engine = this._scene.getEngine();
  46966. this._scene.postProcesses.push(this);
  46967. }
  46968. else {
  46969. this._engine = engine;
  46970. this._engine.postProcesses.push(this);
  46971. }
  46972. this._options = options;
  46973. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  46974. this._reusable = reusable || false;
  46975. this._textureType = textureType;
  46976. this._samplers = samplers || [];
  46977. this._samplers.push("textureSampler");
  46978. this._fragmentUrl = fragmentUrl;
  46979. this._vertexUrl = vertexUrl;
  46980. this._parameters = parameters || [];
  46981. this._parameters.push("scale");
  46982. this._indexParameters = indexParameters;
  46983. if (!blockCompilation) {
  46984. this.updateEffect(defines);
  46985. }
  46986. }
  46987. Object.defineProperty(PostProcess.prototype, "onActivate", {
  46988. set: function (callback) {
  46989. if (this._onActivateObserver) {
  46990. this.onActivateObservable.remove(this._onActivateObserver);
  46991. }
  46992. this._onActivateObserver = this.onActivateObservable.add(callback);
  46993. },
  46994. enumerable: true,
  46995. configurable: true
  46996. });
  46997. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  46998. set: function (callback) {
  46999. if (this._onSizeChangedObserver) {
  47000. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  47001. }
  47002. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  47003. },
  47004. enumerable: true,
  47005. configurable: true
  47006. });
  47007. Object.defineProperty(PostProcess.prototype, "onApply", {
  47008. set: function (callback) {
  47009. if (this._onApplyObserver) {
  47010. this.onApplyObservable.remove(this._onApplyObserver);
  47011. }
  47012. this._onApplyObserver = this.onApplyObservable.add(callback);
  47013. },
  47014. enumerable: true,
  47015. configurable: true
  47016. });
  47017. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  47018. set: function (callback) {
  47019. if (this._onBeforeRenderObserver) {
  47020. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  47021. }
  47022. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  47023. },
  47024. enumerable: true,
  47025. configurable: true
  47026. });
  47027. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  47028. set: function (callback) {
  47029. if (this._onAfterRenderObserver) {
  47030. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  47031. }
  47032. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  47033. },
  47034. enumerable: true,
  47035. configurable: true
  47036. });
  47037. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  47038. get: function () {
  47039. return this._textures.data[this._currentRenderTextureInd];
  47040. },
  47041. set: function (value) {
  47042. this._forcedOutputTexture = value;
  47043. },
  47044. enumerable: true,
  47045. configurable: true
  47046. });
  47047. PostProcess.prototype.getCamera = function () {
  47048. return this._camera;
  47049. };
  47050. Object.defineProperty(PostProcess.prototype, "texelSize", {
  47051. get: function () {
  47052. if (this._shareOutputWithPostProcess) {
  47053. return this._shareOutputWithPostProcess.texelSize;
  47054. }
  47055. if (this._forcedOutputTexture) {
  47056. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  47057. }
  47058. return this._texelSize;
  47059. },
  47060. enumerable: true,
  47061. configurable: true
  47062. });
  47063. PostProcess.prototype.getEngine = function () {
  47064. return this._engine;
  47065. };
  47066. PostProcess.prototype.getEffect = function () {
  47067. return this._effect;
  47068. };
  47069. PostProcess.prototype.shareOutputWith = function (postProcess) {
  47070. this._disposeTextures();
  47071. this._shareOutputWithPostProcess = postProcess;
  47072. return this;
  47073. };
  47074. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  47075. 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);
  47076. };
  47077. PostProcess.prototype.isReusable = function () {
  47078. return this._reusable;
  47079. };
  47080. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  47081. PostProcess.prototype.markTextureDirty = function () {
  47082. this.width = -1;
  47083. };
  47084. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  47085. var _this = this;
  47086. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  47087. camera = camera || this._camera;
  47088. var scene = camera.getScene();
  47089. var engine = scene.getEngine();
  47090. var maxSize = engine.getCaps().maxTextureSize;
  47091. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  47092. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  47093. var desiredWidth = (this._options.width || requiredWidth);
  47094. var desiredHeight = this._options.height || requiredHeight;
  47095. if (this.adaptScaleToCurrentViewport) {
  47096. var currentViewport = engine.currentViewport;
  47097. if (currentViewport) {
  47098. desiredWidth *= currentViewport.width;
  47099. desiredHeight *= currentViewport.height;
  47100. }
  47101. }
  47102. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  47103. if (!this._options.width) {
  47104. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  47105. }
  47106. if (!this._options.height) {
  47107. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  47108. }
  47109. }
  47110. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  47111. if (this._textures.length > 0) {
  47112. for (var i = 0; i < this._textures.length; i++) {
  47113. this._engine._releaseTexture(this._textures.data[i]);
  47114. }
  47115. this._textures.reset();
  47116. }
  47117. this.width = desiredWidth;
  47118. this.height = desiredHeight;
  47119. var textureSize = { width: this.width, height: this.height };
  47120. var textureOptions = {
  47121. generateMipMaps: false,
  47122. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  47123. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  47124. samplingMode: this.renderTargetSamplingMode,
  47125. type: this._textureType
  47126. };
  47127. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  47128. if (this._reusable) {
  47129. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  47130. }
  47131. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  47132. this.onSizeChangedObservable.notifyObservers(this);
  47133. }
  47134. this._textures.forEach(function (texture) {
  47135. if (texture.samples !== _this.samples) {
  47136. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  47137. }
  47138. });
  47139. }
  47140. var target;
  47141. if (this._shareOutputWithPostProcess) {
  47142. target = this._shareOutputWithPostProcess.outputTexture;
  47143. }
  47144. else if (this._forcedOutputTexture) {
  47145. target = this._forcedOutputTexture;
  47146. this.width = this._forcedOutputTexture.width;
  47147. this.height = this._forcedOutputTexture.height;
  47148. }
  47149. else {
  47150. target = this.outputTexture;
  47151. }
  47152. if (this.enablePixelPerfectMode) {
  47153. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  47154. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  47155. }
  47156. else {
  47157. this._scaleRatio.copyFromFloats(1, 1);
  47158. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  47159. }
  47160. this.onActivateObservable.notifyObservers(camera);
  47161. // Clear
  47162. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  47163. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  47164. }
  47165. if (this._reusable) {
  47166. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  47167. }
  47168. };
  47169. Object.defineProperty(PostProcess.prototype, "isSupported", {
  47170. get: function () {
  47171. return this._effect.isSupported;
  47172. },
  47173. enumerable: true,
  47174. configurable: true
  47175. });
  47176. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  47177. get: function () {
  47178. if (this._shareOutputWithPostProcess) {
  47179. return this._shareOutputWithPostProcess.aspectRatio;
  47180. }
  47181. if (this._forcedOutputTexture) {
  47182. var size = this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  47183. }
  47184. return this.width / this.height;
  47185. },
  47186. enumerable: true,
  47187. configurable: true
  47188. });
  47189. PostProcess.prototype.apply = function () {
  47190. // Check
  47191. if (!this._effect || !this._effect.isReady())
  47192. return null;
  47193. // States
  47194. this._engine.enableEffect(this._effect);
  47195. this._engine.setState(false);
  47196. this._engine.setDepthBuffer(false);
  47197. this._engine.setDepthWrite(false);
  47198. // Alpha
  47199. this._engine.setAlphaMode(this.alphaMode);
  47200. if (this.alphaConstants) {
  47201. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  47202. }
  47203. // Texture
  47204. var source;
  47205. if (this._shareOutputWithPostProcess) {
  47206. source = this._shareOutputWithPostProcess.outputTexture;
  47207. }
  47208. else if (this._forcedOutputTexture) {
  47209. source = this._forcedOutputTexture;
  47210. }
  47211. else {
  47212. source = this.outputTexture;
  47213. }
  47214. this._effect._bindTexture("textureSampler", source);
  47215. // Parameters
  47216. this._effect.setVector2("scale", this._scaleRatio);
  47217. this.onApplyObservable.notifyObservers(this._effect);
  47218. return this._effect;
  47219. };
  47220. PostProcess.prototype._disposeTextures = function () {
  47221. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  47222. return;
  47223. }
  47224. if (this._textures.length > 0) {
  47225. for (var i = 0; i < this._textures.length; i++) {
  47226. this._engine._releaseTexture(this._textures.data[i]);
  47227. }
  47228. }
  47229. this._textures.dispose();
  47230. };
  47231. PostProcess.prototype.dispose = function (camera) {
  47232. camera = camera || this._camera;
  47233. this._disposeTextures();
  47234. if (this._scene) {
  47235. var index_1 = this._scene.postProcesses.indexOf(this);
  47236. if (index_1 !== -1) {
  47237. this._scene.postProcesses.splice(index_1, 1);
  47238. }
  47239. }
  47240. else {
  47241. var index_2 = this._engine.postProcesses.indexOf(this);
  47242. if (index_2 !== -1) {
  47243. this._engine.postProcesses.splice(index_2, 1);
  47244. }
  47245. }
  47246. if (!camera) {
  47247. return;
  47248. }
  47249. camera.detachPostProcess(this);
  47250. var index = camera._postProcesses.indexOf(this);
  47251. if (index === 0 && camera._postProcesses.length > 0) {
  47252. this._camera._postProcesses[0].markTextureDirty();
  47253. }
  47254. this.onActivateObservable.clear();
  47255. this.onAfterRenderObservable.clear();
  47256. this.onApplyObservable.clear();
  47257. this.onBeforeRenderObservable.clear();
  47258. this.onSizeChangedObservable.clear();
  47259. };
  47260. return PostProcess;
  47261. }());
  47262. BABYLON.PostProcess = PostProcess;
  47263. })(BABYLON || (BABYLON = {}));
  47264. //# sourceMappingURL=babylon.postProcess.js.map
  47265. var BABYLON;
  47266. (function (BABYLON) {
  47267. var PassPostProcess = (function (_super) {
  47268. __extends(PassPostProcess, _super);
  47269. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  47270. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  47271. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  47272. }
  47273. return PassPostProcess;
  47274. }(BABYLON.PostProcess));
  47275. BABYLON.PassPostProcess = PassPostProcess;
  47276. })(BABYLON || (BABYLON = {}));
  47277. //# sourceMappingURL=babylon.passPostProcess.js.map
  47278. var BABYLON;
  47279. (function (BABYLON) {
  47280. var ShadowGenerator = (function () {
  47281. /**
  47282. * Creates a ShadowGenerator object.
  47283. * A ShadowGenerator is the required tool to use the shadows.
  47284. * Each light casting shadows needs to use its own ShadowGenerator.
  47285. * Required parameters :
  47286. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  47287. * - `light`: the light object generating the shadows.
  47288. * - `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.
  47289. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  47290. */
  47291. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  47292. // Members
  47293. this._bias = 0.00005;
  47294. this._blurBoxOffset = 1;
  47295. this._blurScale = 2;
  47296. this._blurKernel = 1;
  47297. this._useKernelBlur = false;
  47298. this._filter = ShadowGenerator.FILTER_NONE;
  47299. this._darkness = 0;
  47300. this._transparencyShadow = false;
  47301. /**
  47302. * Controls the extent to which the shadows fade out at the edge of the frustum
  47303. * Used only by directionals and spots
  47304. */
  47305. this.frustumEdgeFalloff = 0;
  47306. this.forceBackFacesOnly = false;
  47307. this._lightDirection = BABYLON.Vector3.Zero();
  47308. this._viewMatrix = BABYLON.Matrix.Zero();
  47309. this._projectionMatrix = BABYLON.Matrix.Zero();
  47310. this._transformMatrix = BABYLON.Matrix.Zero();
  47311. this._worldViewProjection = BABYLON.Matrix.Zero();
  47312. this._currentFaceIndex = 0;
  47313. this._currentFaceIndexCache = 0;
  47314. this._isCube = false;
  47315. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  47316. this._mapSize = mapSize;
  47317. this._light = light;
  47318. this._scene = light.getScene();
  47319. light._shadowGenerator = this;
  47320. // Texture type fallback from float to int if not supported.
  47321. var caps = this._scene.getEngine().getCaps();
  47322. if (!useFullFloatFirst) {
  47323. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  47324. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  47325. }
  47326. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  47327. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  47328. }
  47329. else {
  47330. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  47331. }
  47332. }
  47333. else {
  47334. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  47335. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  47336. }
  47337. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  47338. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  47339. }
  47340. else {
  47341. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  47342. }
  47343. }
  47344. this._initializeGenerator();
  47345. }
  47346. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  47347. // Static
  47348. get: function () {
  47349. return ShadowGenerator._FILTER_NONE;
  47350. },
  47351. enumerable: true,
  47352. configurable: true
  47353. });
  47354. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  47355. get: function () {
  47356. return ShadowGenerator._FILTER_POISSONSAMPLING;
  47357. },
  47358. enumerable: true,
  47359. configurable: true
  47360. });
  47361. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  47362. get: function () {
  47363. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  47364. },
  47365. enumerable: true,
  47366. configurable: true
  47367. });
  47368. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  47369. get: function () {
  47370. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  47371. },
  47372. enumerable: true,
  47373. configurable: true
  47374. });
  47375. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  47376. get: function () {
  47377. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  47378. },
  47379. enumerable: true,
  47380. configurable: true
  47381. });
  47382. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  47383. get: function () {
  47384. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  47385. },
  47386. enumerable: true,
  47387. configurable: true
  47388. });
  47389. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  47390. get: function () {
  47391. return this._bias;
  47392. },
  47393. set: function (bias) {
  47394. this._bias = bias;
  47395. },
  47396. enumerable: true,
  47397. configurable: true
  47398. });
  47399. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  47400. get: function () {
  47401. return this._blurBoxOffset;
  47402. },
  47403. set: function (value) {
  47404. if (this._blurBoxOffset === value) {
  47405. return;
  47406. }
  47407. this._blurBoxOffset = value;
  47408. this._disposeBlurPostProcesses();
  47409. },
  47410. enumerable: true,
  47411. configurable: true
  47412. });
  47413. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  47414. get: function () {
  47415. return this._blurScale;
  47416. },
  47417. set: function (value) {
  47418. if (this._blurScale === value) {
  47419. return;
  47420. }
  47421. this._blurScale = value;
  47422. this._disposeBlurPostProcesses();
  47423. },
  47424. enumerable: true,
  47425. configurable: true
  47426. });
  47427. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  47428. get: function () {
  47429. return this._blurKernel;
  47430. },
  47431. set: function (value) {
  47432. if (this._blurKernel === value) {
  47433. return;
  47434. }
  47435. this._blurKernel = value;
  47436. this._disposeBlurPostProcesses();
  47437. },
  47438. enumerable: true,
  47439. configurable: true
  47440. });
  47441. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  47442. get: function () {
  47443. return this._useKernelBlur;
  47444. },
  47445. set: function (value) {
  47446. if (this._useKernelBlur === value) {
  47447. return;
  47448. }
  47449. this._useKernelBlur = value;
  47450. this._disposeBlurPostProcesses();
  47451. },
  47452. enumerable: true,
  47453. configurable: true
  47454. });
  47455. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  47456. get: function () {
  47457. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  47458. },
  47459. set: function (value) {
  47460. this._depthScale = value;
  47461. },
  47462. enumerable: true,
  47463. configurable: true
  47464. });
  47465. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  47466. get: function () {
  47467. return this._filter;
  47468. },
  47469. set: function (value) {
  47470. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  47471. if (this._light.needCube()) {
  47472. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  47473. this.useExponentialShadowMap = true;
  47474. return;
  47475. }
  47476. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  47477. this.useCloseExponentialShadowMap = true;
  47478. return;
  47479. }
  47480. }
  47481. if (this._filter === value) {
  47482. return;
  47483. }
  47484. this._filter = value;
  47485. this._disposeBlurPostProcesses();
  47486. this._applyFilterValues();
  47487. this._light._markMeshesAsLightDirty();
  47488. },
  47489. enumerable: true,
  47490. configurable: true
  47491. });
  47492. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  47493. get: function () {
  47494. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  47495. },
  47496. set: function (value) {
  47497. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  47498. return;
  47499. }
  47500. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  47501. },
  47502. enumerable: true,
  47503. configurable: true
  47504. });
  47505. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  47506. get: function () {
  47507. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  47508. return this.useExponentialShadowMap;
  47509. },
  47510. set: function (value) {
  47511. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  47512. this.useExponentialShadowMap = value;
  47513. },
  47514. enumerable: true,
  47515. configurable: true
  47516. });
  47517. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  47518. get: function () {
  47519. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  47520. return this.useBlurExponentialShadowMap;
  47521. },
  47522. set: function (value) {
  47523. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  47524. this.useBlurExponentialShadowMap = value;
  47525. },
  47526. enumerable: true,
  47527. configurable: true
  47528. });
  47529. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  47530. get: function () {
  47531. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  47532. },
  47533. set: function (value) {
  47534. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  47535. return;
  47536. }
  47537. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  47538. },
  47539. enumerable: true,
  47540. configurable: true
  47541. });
  47542. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  47543. get: function () {
  47544. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  47545. },
  47546. set: function (value) {
  47547. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  47548. return;
  47549. }
  47550. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  47551. },
  47552. enumerable: true,
  47553. configurable: true
  47554. });
  47555. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  47556. get: function () {
  47557. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  47558. },
  47559. set: function (value) {
  47560. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  47561. return;
  47562. }
  47563. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  47564. },
  47565. enumerable: true,
  47566. configurable: true
  47567. });
  47568. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  47569. get: function () {
  47570. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  47571. },
  47572. set: function (value) {
  47573. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  47574. return;
  47575. }
  47576. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  47577. },
  47578. enumerable: true,
  47579. configurable: true
  47580. });
  47581. /**
  47582. * Returns the darkness value (float).
  47583. */
  47584. ShadowGenerator.prototype.getDarkness = function () {
  47585. return this._darkness;
  47586. };
  47587. /**
  47588. * Sets the ShadowGenerator darkness value (float <= 1.0).
  47589. * Returns the ShadowGenerator.
  47590. */
  47591. ShadowGenerator.prototype.setDarkness = function (darkness) {
  47592. if (darkness >= 1.0)
  47593. this._darkness = 1.0;
  47594. else if (darkness <= 0.0)
  47595. this._darkness = 0.0;
  47596. else
  47597. this._darkness = darkness;
  47598. return this;
  47599. };
  47600. /**
  47601. * Sets the ability to have transparent shadow (boolean).
  47602. * Returns the ShadowGenerator.
  47603. */
  47604. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  47605. this._transparencyShadow = hasShadow;
  47606. return this;
  47607. };
  47608. /**
  47609. * Returns a RenderTargetTexture object : the shadow map texture.
  47610. */
  47611. ShadowGenerator.prototype.getShadowMap = function () {
  47612. return this._shadowMap;
  47613. };
  47614. /**
  47615. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  47616. */
  47617. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  47618. if (this._shadowMap2) {
  47619. return this._shadowMap2;
  47620. }
  47621. return this._shadowMap;
  47622. };
  47623. /**
  47624. * Returns the associated light object.
  47625. */
  47626. ShadowGenerator.prototype.getLight = function () {
  47627. return this._light;
  47628. };
  47629. ShadowGenerator.prototype._initializeGenerator = function () {
  47630. this._light._markMeshesAsLightDirty();
  47631. this._initializeShadowMap();
  47632. };
  47633. ShadowGenerator.prototype._initializeShadowMap = function () {
  47634. var _this = this;
  47635. // Render target
  47636. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  47637. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47638. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47639. this._shadowMap.anisotropicFilteringLevel = 1;
  47640. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47641. this._shadowMap.renderParticles = false;
  47642. this._shadowMap.ignoreCameraViewport = true;
  47643. // Record Face Index before render.
  47644. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  47645. _this._currentFaceIndex = faceIndex;
  47646. });
  47647. // Custom render function.
  47648. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  47649. // Blur if required afer render.
  47650. this._shadowMap.onAfterUnbindObservable.add(function () {
  47651. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  47652. return;
  47653. }
  47654. if (!_this._blurPostProcesses) {
  47655. _this._initializeBlurRTTAndPostProcesses();
  47656. }
  47657. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture(), true);
  47658. });
  47659. // Clear according to the chosen filter.
  47660. this._shadowMap.onClearObservable.add(function (engine) {
  47661. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  47662. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  47663. }
  47664. else {
  47665. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  47666. }
  47667. });
  47668. };
  47669. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  47670. var _this = this;
  47671. var engine = this._scene.getEngine();
  47672. var targetSize = this._mapSize / this.blurScale;
  47673. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  47674. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  47675. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47676. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47677. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47678. }
  47679. if (this.useKernelBlur) {
  47680. 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);
  47681. this._kernelBlurXPostprocess.width = targetSize;
  47682. this._kernelBlurXPostprocess.height = targetSize;
  47683. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  47684. effect.setTexture("textureSampler", _this._shadowMap);
  47685. });
  47686. 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);
  47687. this._kernelBlurXPostprocess.autoClear = false;
  47688. this._kernelBlurYPostprocess.autoClear = false;
  47689. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  47690. this._kernelBlurXPostprocess.packedFloat = true;
  47691. this._kernelBlurYPostprocess.packedFloat = true;
  47692. }
  47693. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  47694. }
  47695. else {
  47696. 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);
  47697. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  47698. effect.setFloat2("screenSize", targetSize, targetSize);
  47699. effect.setTexture("textureSampler", _this._shadowMap);
  47700. });
  47701. this._boxBlurPostprocess.autoClear = false;
  47702. this._blurPostProcesses = [this._boxBlurPostprocess];
  47703. }
  47704. };
  47705. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  47706. var index;
  47707. var engine = this._scene.getEngine();
  47708. if (depthOnlySubMeshes.length) {
  47709. engine.setColorWrite(false);
  47710. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  47711. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  47712. }
  47713. engine.setColorWrite(true);
  47714. }
  47715. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47716. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  47717. }
  47718. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47719. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  47720. }
  47721. if (this._transparencyShadow) {
  47722. for (index = 0; index < transparentSubMeshes.length; index++) {
  47723. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  47724. }
  47725. }
  47726. };
  47727. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  47728. var _this = this;
  47729. var mesh = subMesh.getRenderingMesh();
  47730. var scene = this._scene;
  47731. var engine = scene.getEngine();
  47732. // Culling
  47733. engine.setState(subMesh.getMaterial().backFaceCulling);
  47734. // Managing instances
  47735. var batch = mesh._getInstancesRenderList(subMesh._id);
  47736. if (batch.mustReturn) {
  47737. return;
  47738. }
  47739. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  47740. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  47741. engine.enableEffect(this._effect);
  47742. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  47743. var material = subMesh.getMaterial();
  47744. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  47745. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  47746. this._effect.setVector3("lightPosition", this.getLight().position);
  47747. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  47748. // Alpha test
  47749. if (material && material.needAlphaTesting()) {
  47750. var alphaTexture = material.getAlphaTestTexture();
  47751. if (alphaTexture) {
  47752. this._effect.setTexture("diffuseSampler", alphaTexture);
  47753. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  47754. }
  47755. }
  47756. // Bones
  47757. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47758. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47759. }
  47760. if (this.forceBackFacesOnly) {
  47761. engine.setState(true, 0, false, true);
  47762. }
  47763. // Draw
  47764. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  47765. if (this.forceBackFacesOnly) {
  47766. engine.setState(true, 0, false, false);
  47767. }
  47768. }
  47769. else {
  47770. // Need to reset refresh rate of the shadowMap
  47771. this._shadowMap.resetRefreshCounter();
  47772. }
  47773. };
  47774. ShadowGenerator.prototype._applyFilterValues = function () {
  47775. if (this.filter === ShadowGenerator.FILTER_NONE) {
  47776. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  47777. }
  47778. else {
  47779. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47780. }
  47781. };
  47782. /**
  47783. * Force shader compilation including textures ready check
  47784. */
  47785. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  47786. var _this = this;
  47787. var scene = this._scene;
  47788. var engine = scene.getEngine();
  47789. var subMeshes = new Array();
  47790. var currentIndex = 0;
  47791. for (var _i = 0, _a = this.getShadowMap().renderList; _i < _a.length; _i++) {
  47792. var mesh = _a[_i];
  47793. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  47794. }
  47795. var checkReady = function () {
  47796. if (!_this._scene || !_this._scene.getEngine()) {
  47797. return;
  47798. }
  47799. var subMesh = subMeshes[currentIndex];
  47800. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  47801. currentIndex++;
  47802. if (currentIndex >= subMeshes.length) {
  47803. if (onCompiled) {
  47804. onCompiled(_this);
  47805. }
  47806. return;
  47807. }
  47808. }
  47809. setTimeout(checkReady, 16);
  47810. };
  47811. if (subMeshes.length > 0) {
  47812. checkReady();
  47813. }
  47814. };
  47815. /**
  47816. * Boolean : true when the ShadowGenerator is finally computed.
  47817. */
  47818. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  47819. var defines = [];
  47820. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  47821. defines.push("#define FLOAT");
  47822. }
  47823. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  47824. defines.push("#define ESM");
  47825. }
  47826. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47827. var mesh = subMesh.getMesh();
  47828. var material = subMesh.getMaterial();
  47829. // Alpha test
  47830. if (material && material.needAlphaTesting()) {
  47831. var alphaTexture = material.getAlphaTestTexture();
  47832. if (alphaTexture) {
  47833. defines.push("#define ALPHATEST");
  47834. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47835. attribs.push(BABYLON.VertexBuffer.UVKind);
  47836. defines.push("#define UV1");
  47837. }
  47838. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47839. if (alphaTexture.coordinatesIndex === 1) {
  47840. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47841. defines.push("#define UV2");
  47842. }
  47843. }
  47844. }
  47845. }
  47846. // Bones
  47847. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47848. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47849. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47850. if (mesh.numBoneInfluencers > 4) {
  47851. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47852. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47853. }
  47854. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47855. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47856. }
  47857. else {
  47858. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47859. }
  47860. // Instances
  47861. if (useInstances) {
  47862. defines.push("#define INSTANCES");
  47863. attribs.push("world0");
  47864. attribs.push("world1");
  47865. attribs.push("world2");
  47866. attribs.push("world3");
  47867. }
  47868. // Get correct effect
  47869. var join = defines.join("\n");
  47870. if (this._cachedDefines !== join) {
  47871. this._cachedDefines = join;
  47872. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  47873. }
  47874. return this._effect.isReady();
  47875. };
  47876. /**
  47877. * This creates the defines related to the standard BJS materials.
  47878. */
  47879. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  47880. var scene = this._scene;
  47881. var light = this._light;
  47882. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  47883. return;
  47884. }
  47885. defines["SHADOW" + lightIndex] = true;
  47886. if (this.usePoissonSampling) {
  47887. defines["SHADOWPCF" + lightIndex] = true;
  47888. }
  47889. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  47890. defines["SHADOWESM" + lightIndex] = true;
  47891. }
  47892. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  47893. defines["SHADOWCLOSEESM" + lightIndex] = true;
  47894. }
  47895. if (light.needCube()) {
  47896. defines["SHADOWCUBE" + lightIndex] = true;
  47897. }
  47898. };
  47899. /**
  47900. * This binds shadow lights related to the standard BJS materials.
  47901. * It implies the unifroms available on the materials are the standard BJS ones.
  47902. */
  47903. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  47904. var light = this._light;
  47905. var scene = this._scene;
  47906. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  47907. return;
  47908. }
  47909. if (!light.needCube()) {
  47910. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  47911. }
  47912. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  47913. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  47914. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  47915. };
  47916. // Methods
  47917. /**
  47918. * Returns a Matrix object : the updated transformation matrix.
  47919. */
  47920. ShadowGenerator.prototype.getTransformMatrix = function () {
  47921. var scene = this._scene;
  47922. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  47923. return this._transformMatrix;
  47924. }
  47925. this._currentRenderID = scene.getRenderId();
  47926. this._currentFaceIndexCache = this._currentFaceIndex;
  47927. var lightPosition = this._light.position;
  47928. if (this._light.computeTransformedInformation()) {
  47929. lightPosition = this._light.transformedPosition;
  47930. }
  47931. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  47932. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  47933. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  47934. }
  47935. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  47936. this._cachedPosition = lightPosition.clone();
  47937. this._cachedDirection = this._lightDirection.clone();
  47938. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  47939. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  47940. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  47941. }
  47942. return this._transformMatrix;
  47943. };
  47944. ShadowGenerator.prototype.recreateShadowMap = function () {
  47945. // Track render list.
  47946. var renderList = this._shadowMap.renderList;
  47947. // Clean up existing data.
  47948. this._disposeRTTandPostProcesses();
  47949. // Reinitializes.
  47950. this._initializeGenerator();
  47951. // Reaffect the filter to ensure a correct fallback if necessary.
  47952. this.filter = this.filter;
  47953. // Reaffect the filter.
  47954. this._applyFilterValues();
  47955. // Reaffect Render List.
  47956. this._shadowMap.renderList = renderList;
  47957. };
  47958. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  47959. if (this._shadowMap2) {
  47960. this._shadowMap2.dispose();
  47961. this._shadowMap2 = null;
  47962. }
  47963. if (this._downSamplePostprocess) {
  47964. this._downSamplePostprocess.dispose();
  47965. this._downSamplePostprocess = null;
  47966. }
  47967. if (this._boxBlurPostprocess) {
  47968. this._boxBlurPostprocess.dispose();
  47969. this._boxBlurPostprocess = null;
  47970. }
  47971. if (this._kernelBlurXPostprocess) {
  47972. this._kernelBlurXPostprocess.dispose();
  47973. this._kernelBlurXPostprocess = null;
  47974. }
  47975. if (this._kernelBlurYPostprocess) {
  47976. this._kernelBlurYPostprocess.dispose();
  47977. this._kernelBlurYPostprocess = null;
  47978. }
  47979. this._blurPostProcesses = null;
  47980. };
  47981. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  47982. if (this._shadowMap) {
  47983. this._shadowMap.dispose();
  47984. this._shadowMap = null;
  47985. }
  47986. this._disposeBlurPostProcesses();
  47987. };
  47988. /**
  47989. * Disposes the ShadowGenerator.
  47990. * Returns nothing.
  47991. */
  47992. ShadowGenerator.prototype.dispose = function () {
  47993. this._disposeRTTandPostProcesses();
  47994. this._light._shadowGenerator = null;
  47995. this._light._markMeshesAsLightDirty();
  47996. };
  47997. /**
  47998. * Serializes the ShadowGenerator and returns a serializationObject.
  47999. */
  48000. ShadowGenerator.prototype.serialize = function () {
  48001. var serializationObject = {};
  48002. var shadowMap = this.getShadowMap();
  48003. serializationObject.lightId = this._light.id;
  48004. serializationObject.mapSize = shadowMap.getRenderSize();
  48005. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  48006. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  48007. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  48008. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  48009. serializationObject.usePoissonSampling = this.usePoissonSampling;
  48010. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  48011. serializationObject.depthScale = this.depthScale;
  48012. serializationObject.darkness = this.getDarkness();
  48013. serializationObject.blurBoxOffset = this.blurBoxOffset;
  48014. serializationObject.blurKernel = this.blurKernel;
  48015. serializationObject.blurScale = this.blurScale;
  48016. serializationObject.useKernelBlur = this.useKernelBlur;
  48017. serializationObject.transparencyShadow = this._transparencyShadow;
  48018. serializationObject.renderList = [];
  48019. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  48020. var mesh = shadowMap.renderList[meshIndex];
  48021. serializationObject.renderList.push(mesh.id);
  48022. }
  48023. return serializationObject;
  48024. };
  48025. /**
  48026. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  48027. */
  48028. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  48029. //casting to point light, as light is missing the position attr and typescript complains.
  48030. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  48031. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  48032. var shadowMap = shadowGenerator.getShadowMap();
  48033. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  48034. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  48035. meshes.forEach(function (mesh) {
  48036. shadowMap.renderList.push(mesh);
  48037. });
  48038. }
  48039. if (parsedShadowGenerator.usePoissonSampling) {
  48040. shadowGenerator.usePoissonSampling = true;
  48041. }
  48042. else if (parsedShadowGenerator.useExponentialShadowMap) {
  48043. shadowGenerator.useExponentialShadowMap = true;
  48044. }
  48045. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  48046. shadowGenerator.useBlurExponentialShadowMap = true;
  48047. }
  48048. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  48049. shadowGenerator.useCloseExponentialShadowMap = true;
  48050. }
  48051. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  48052. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  48053. }
  48054. else if (parsedShadowGenerator.useVarianceShadowMap) {
  48055. shadowGenerator.useExponentialShadowMap = true;
  48056. }
  48057. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  48058. shadowGenerator.useBlurExponentialShadowMap = true;
  48059. }
  48060. if (parsedShadowGenerator.depthScale) {
  48061. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  48062. }
  48063. if (parsedShadowGenerator.blurScale) {
  48064. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  48065. }
  48066. if (parsedShadowGenerator.blurBoxOffset) {
  48067. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  48068. }
  48069. if (parsedShadowGenerator.useKernelBlur) {
  48070. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  48071. }
  48072. if (parsedShadowGenerator.blurKernel) {
  48073. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  48074. }
  48075. if (parsedShadowGenerator.bias !== undefined) {
  48076. shadowGenerator.bias = parsedShadowGenerator.bias;
  48077. }
  48078. if (parsedShadowGenerator.darkness) {
  48079. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  48080. }
  48081. if (parsedShadowGenerator.transparencyShadow) {
  48082. shadowGenerator.setTransparencyShadow(true);
  48083. }
  48084. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  48085. return shadowGenerator;
  48086. };
  48087. ShadowGenerator._FILTER_NONE = 0;
  48088. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  48089. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  48090. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  48091. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  48092. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  48093. return ShadowGenerator;
  48094. }());
  48095. BABYLON.ShadowGenerator = ShadowGenerator;
  48096. })(BABYLON || (BABYLON = {}));
  48097. //# sourceMappingURL=babylon.shadowGenerator.js.map
  48098. var BABYLON;
  48099. (function (BABYLON) {
  48100. var DefaultLoadingScreen = (function () {
  48101. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  48102. if (_loadingText === void 0) { _loadingText = ""; }
  48103. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  48104. var _this = this;
  48105. this._renderingCanvas = _renderingCanvas;
  48106. this._loadingText = _loadingText;
  48107. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  48108. // Resize
  48109. this._resizeLoadingUI = function () {
  48110. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  48111. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  48112. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  48113. _this._loadingDiv.style.left = canvasRect.left + "px";
  48114. _this._loadingDiv.style.top = canvasRect.top + "px";
  48115. _this._loadingDiv.style.width = canvasRect.width + "px";
  48116. _this._loadingDiv.style.height = canvasRect.height + "px";
  48117. };
  48118. }
  48119. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  48120. if (this._loadingDiv) {
  48121. // Do not add a loading screen if there is already one
  48122. return;
  48123. }
  48124. this._loadingDiv = document.createElement("div");
  48125. this._loadingDiv.id = "babylonjsLoadingDiv";
  48126. this._loadingDiv.style.opacity = "0";
  48127. this._loadingDiv.style.transition = "opacity 1.5s ease";
  48128. // Loading text
  48129. this._loadingTextDiv = document.createElement("div");
  48130. this._loadingTextDiv.style.position = "absolute";
  48131. this._loadingTextDiv.style.left = "0";
  48132. this._loadingTextDiv.style.top = "50%";
  48133. this._loadingTextDiv.style.marginTop = "80px";
  48134. this._loadingTextDiv.style.width = "100%";
  48135. this._loadingTextDiv.style.height = "20px";
  48136. this._loadingTextDiv.style.fontFamily = "Arial";
  48137. this._loadingTextDiv.style.fontSize = "14px";
  48138. this._loadingTextDiv.style.color = "white";
  48139. this._loadingTextDiv.style.textAlign = "center";
  48140. this._loadingTextDiv.innerHTML = "Loading";
  48141. this._loadingDiv.appendChild(this._loadingTextDiv);
  48142. //set the predefined text
  48143. this._loadingTextDiv.innerHTML = this._loadingText;
  48144. // Generating keyframes
  48145. var style = document.createElement('style');
  48146. style.type = 'text/css';
  48147. 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 }";
  48148. style.innerHTML = keyFrames;
  48149. document.getElementsByTagName('head')[0].appendChild(style);
  48150. // Loading img
  48151. var imgBack = new Image();
  48152. 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";
  48153. imgBack.style.position = "absolute";
  48154. imgBack.style.left = "50%";
  48155. imgBack.style.top = "50%";
  48156. imgBack.style.marginLeft = "-60px";
  48157. imgBack.style.marginTop = "-60px";
  48158. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  48159. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  48160. imgBack.style.transformOrigin = "50% 50%";
  48161. imgBack.style.webkitTransformOrigin = "50% 50%";
  48162. this._loadingDiv.appendChild(imgBack);
  48163. this._resizeLoadingUI();
  48164. window.addEventListener("resize", this._resizeLoadingUI);
  48165. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  48166. document.body.appendChild(this._loadingDiv);
  48167. this._loadingDiv.style.opacity = "1";
  48168. };
  48169. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  48170. var _this = this;
  48171. if (!this._loadingDiv) {
  48172. return;
  48173. }
  48174. var onTransitionEnd = function () {
  48175. if (!_this._loadingDiv) {
  48176. return;
  48177. }
  48178. document.body.removeChild(_this._loadingDiv);
  48179. window.removeEventListener("resize", _this._resizeLoadingUI);
  48180. _this._loadingDiv = null;
  48181. };
  48182. this._loadingDiv.style.opacity = "0";
  48183. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  48184. };
  48185. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  48186. set: function (text) {
  48187. this._loadingText = text;
  48188. if (this._loadingTextDiv) {
  48189. this._loadingTextDiv.innerHTML = this._loadingText;
  48190. }
  48191. },
  48192. enumerable: true,
  48193. configurable: true
  48194. });
  48195. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  48196. get: function () {
  48197. return this._loadingDivBackgroundColor;
  48198. },
  48199. set: function (color) {
  48200. this._loadingDivBackgroundColor = color;
  48201. if (!this._loadingDiv) {
  48202. return;
  48203. }
  48204. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  48205. },
  48206. enumerable: true,
  48207. configurable: true
  48208. });
  48209. return DefaultLoadingScreen;
  48210. }());
  48211. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  48212. })(BABYLON || (BABYLON = {}));
  48213. //# sourceMappingURL=babylon.loadingScreen.js.map
  48214. var BABYLON;
  48215. (function (BABYLON) {
  48216. var SceneLoader = (function () {
  48217. function SceneLoader() {
  48218. }
  48219. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  48220. get: function () {
  48221. return 0;
  48222. },
  48223. enumerable: true,
  48224. configurable: true
  48225. });
  48226. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  48227. get: function () {
  48228. return 1;
  48229. },
  48230. enumerable: true,
  48231. configurable: true
  48232. });
  48233. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  48234. get: function () {
  48235. return 2;
  48236. },
  48237. enumerable: true,
  48238. configurable: true
  48239. });
  48240. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  48241. get: function () {
  48242. return 3;
  48243. },
  48244. enumerable: true,
  48245. configurable: true
  48246. });
  48247. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  48248. get: function () {
  48249. return SceneLoader._ForceFullSceneLoadingForIncremental;
  48250. },
  48251. set: function (value) {
  48252. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  48253. },
  48254. enumerable: true,
  48255. configurable: true
  48256. });
  48257. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  48258. get: function () {
  48259. return SceneLoader._ShowLoadingScreen;
  48260. },
  48261. set: function (value) {
  48262. SceneLoader._ShowLoadingScreen = value;
  48263. },
  48264. enumerable: true,
  48265. configurable: true
  48266. });
  48267. Object.defineProperty(SceneLoader, "loggingLevel", {
  48268. get: function () {
  48269. return SceneLoader._loggingLevel;
  48270. },
  48271. set: function (value) {
  48272. SceneLoader._loggingLevel = value;
  48273. },
  48274. enumerable: true,
  48275. configurable: true
  48276. });
  48277. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  48278. get: function () {
  48279. return SceneLoader._CleanBoneMatrixWeights;
  48280. },
  48281. set: function (value) {
  48282. SceneLoader._CleanBoneMatrixWeights = value;
  48283. },
  48284. enumerable: true,
  48285. configurable: true
  48286. });
  48287. SceneLoader._getDefaultPlugin = function () {
  48288. return SceneLoader._registeredPlugins[".babylon"];
  48289. };
  48290. SceneLoader._getPluginForExtension = function (extension) {
  48291. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  48292. if (registeredPlugin) {
  48293. return registeredPlugin;
  48294. }
  48295. return SceneLoader._getDefaultPlugin();
  48296. };
  48297. SceneLoader._getPluginForDirectLoad = function (data) {
  48298. for (var extension in SceneLoader._registeredPlugins) {
  48299. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  48300. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  48301. return SceneLoader._registeredPlugins[extension];
  48302. }
  48303. }
  48304. return SceneLoader._getDefaultPlugin();
  48305. };
  48306. SceneLoader._getPluginForFilename = function (sceneFilename) {
  48307. if (sceneFilename.name) {
  48308. sceneFilename = sceneFilename.name;
  48309. }
  48310. var dotPosition = sceneFilename.lastIndexOf(".");
  48311. var queryStringPosition = sceneFilename.indexOf("?");
  48312. if (queryStringPosition === -1) {
  48313. queryStringPosition = sceneFilename.length;
  48314. }
  48315. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  48316. return SceneLoader._getPluginForExtension(extension);
  48317. };
  48318. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  48319. SceneLoader._getDirectLoad = function (sceneFilename) {
  48320. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  48321. return sceneFilename.substr(5);
  48322. }
  48323. return null;
  48324. };
  48325. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  48326. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  48327. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  48328. var plugin = registeredPlugin.plugin;
  48329. var useArrayBuffer = registeredPlugin.isBinary;
  48330. var database;
  48331. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  48332. var dataCallback = function (data) {
  48333. if (scene.isDisposed) {
  48334. onError("Scene has been disposed");
  48335. return;
  48336. }
  48337. scene.database = database;
  48338. try {
  48339. onSuccess(plugin, data);
  48340. }
  48341. catch (e) {
  48342. onError(null, e);
  48343. }
  48344. };
  48345. var manifestChecked = function (success) {
  48346. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  48347. onError(request.status + " " + request.statusText);
  48348. });
  48349. };
  48350. if (directLoad) {
  48351. dataCallback(directLoad);
  48352. return;
  48353. }
  48354. if (rootUrl.indexOf("file:") === -1) {
  48355. if (scene.getEngine().enableOfflineSupport) {
  48356. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  48357. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  48358. }
  48359. else {
  48360. manifestChecked(true);
  48361. }
  48362. }
  48363. else {
  48364. BABYLON.Tools.ReadFile(sceneFilename, dataCallback, onProgress, useArrayBuffer);
  48365. }
  48366. };
  48367. // Public functions
  48368. SceneLoader.GetPluginForExtension = function (extension) {
  48369. return SceneLoader._getPluginForExtension(extension).plugin;
  48370. };
  48371. SceneLoader.RegisterPlugin = function (plugin) {
  48372. if (typeof plugin.extensions === "string") {
  48373. var extension = plugin.extensions;
  48374. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  48375. plugin: plugin,
  48376. isBinary: false
  48377. };
  48378. }
  48379. else {
  48380. var extensions = plugin.extensions;
  48381. Object.keys(extensions).forEach(function (extension) {
  48382. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  48383. plugin: plugin,
  48384. isBinary: extensions[extension].isBinary
  48385. };
  48386. });
  48387. }
  48388. };
  48389. /**
  48390. * Import meshes into a scene
  48391. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  48392. * @param rootUrl a string that defines the root url for scene and resources
  48393. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  48394. * @param scene the instance of BABYLON.Scene to append to
  48395. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  48396. * @param onProgress a callback with a progress event for each file being loaded
  48397. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  48398. */
  48399. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  48400. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  48401. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  48402. return;
  48403. }
  48404. var loadingToken = {};
  48405. scene._addPendingData(loadingToken);
  48406. var errorHandler = function (message, exception) {
  48407. if (onError) {
  48408. onError(scene, "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  48409. }
  48410. scene._removePendingData(loadingToken);
  48411. };
  48412. var progressHandler = function (event) {
  48413. if (onProgress) {
  48414. onProgress(event);
  48415. }
  48416. };
  48417. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  48418. if (plugin.importMesh) {
  48419. var syncedPlugin = plugin;
  48420. var meshes = [];
  48421. var particleSystems = [];
  48422. var skeletons = [];
  48423. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  48424. return;
  48425. }
  48426. if (onSuccess) {
  48427. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  48428. onSuccess(meshes, particleSystems, skeletons);
  48429. scene._removePendingData(loadingToken);
  48430. }
  48431. }
  48432. else {
  48433. var asyncedPlugin = plugin;
  48434. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  48435. if (onSuccess) {
  48436. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  48437. onSuccess(meshes, particleSystems, skeletons);
  48438. scene._removePendingData(loadingToken);
  48439. }
  48440. }, progressHandler, errorHandler);
  48441. }
  48442. }, progressHandler, errorHandler);
  48443. };
  48444. /**
  48445. * Load a scene
  48446. * @param rootUrl a string that defines the root url for scene and resources
  48447. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  48448. * @param engine is the instance of BABYLON.Engine to use to create the scene
  48449. * @param onSuccess a callback with the scene when import succeeds
  48450. * @param onProgress a callback with a progress event for each file being loaded
  48451. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  48452. */
  48453. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  48454. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  48455. };
  48456. /**
  48457. * Append a scene
  48458. * @param rootUrl a string that defines the root url for scene and resources
  48459. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  48460. * @param scene is the instance of BABYLON.Scene to append to
  48461. * @param onSuccess a callback with the scene when import succeeds
  48462. * @param onProgress a callback with a progress event for each file being loaded
  48463. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  48464. */
  48465. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  48466. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  48467. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  48468. return;
  48469. }
  48470. if (SceneLoader.ShowLoadingScreen) {
  48471. scene.getEngine().displayLoadingUI();
  48472. }
  48473. var loadingToken = {};
  48474. scene._addPendingData(loadingToken);
  48475. var errorHandler = function (message, exception) {
  48476. if (onError) {
  48477. onError(scene, "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  48478. }
  48479. scene._removePendingData(loadingToken);
  48480. scene.getEngine().hideLoadingUI();
  48481. };
  48482. var progressHandler = function (event) {
  48483. if (onProgress) {
  48484. onProgress(event);
  48485. }
  48486. };
  48487. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  48488. if (plugin.load) {
  48489. var syncedPlugin = plugin;
  48490. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  48491. return;
  48492. }
  48493. if (onSuccess) {
  48494. onSuccess(scene);
  48495. }
  48496. scene.loadingPluginName = plugin.name;
  48497. scene._removePendingData(loadingToken);
  48498. }
  48499. else {
  48500. var asyncedPlugin = plugin;
  48501. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  48502. if (onSuccess) {
  48503. onSuccess(scene);
  48504. }
  48505. scene.loadingPluginName = plugin.name;
  48506. scene._removePendingData(loadingToken);
  48507. }, progressHandler, errorHandler);
  48508. }
  48509. if (SceneLoader.ShowLoadingScreen) {
  48510. scene.executeWhenReady(function () {
  48511. scene.getEngine().hideLoadingUI();
  48512. });
  48513. }
  48514. }, progressHandler, errorHandler);
  48515. };
  48516. // Flags
  48517. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  48518. SceneLoader._ShowLoadingScreen = true;
  48519. SceneLoader._CleanBoneMatrixWeights = false;
  48520. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  48521. // Members
  48522. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  48523. SceneLoader._registeredPlugins = {};
  48524. return SceneLoader;
  48525. }());
  48526. BABYLON.SceneLoader = SceneLoader;
  48527. ;
  48528. })(BABYLON || (BABYLON = {}));
  48529. //# sourceMappingURL=babylon.sceneLoader.js.map
  48530. var BABYLON;
  48531. (function (BABYLON) {
  48532. var Internals;
  48533. (function (Internals) {
  48534. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  48535. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  48536. var parsedMaterial = parsedData.materials[index];
  48537. if (parsedMaterial.id === id) {
  48538. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  48539. }
  48540. }
  48541. return null;
  48542. };
  48543. var isDescendantOf = function (mesh, names, hierarchyIds) {
  48544. for (var i in names) {
  48545. if (mesh.name === names[i]) {
  48546. hierarchyIds.push(mesh.id);
  48547. return true;
  48548. }
  48549. }
  48550. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  48551. hierarchyIds.push(mesh.id);
  48552. return true;
  48553. }
  48554. return false;
  48555. };
  48556. var logOperation = function (operation, producer) {
  48557. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  48558. };
  48559. BABYLON.SceneLoader.RegisterPlugin({
  48560. name: "babylon.js",
  48561. extensions: ".babylon",
  48562. canDirectLoad: function (data) {
  48563. if (data.indexOf("babylon") !== -1) {
  48564. return true;
  48565. }
  48566. return false;
  48567. },
  48568. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  48569. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  48570. // when SceneLoader.debugLogging = true (default), or exception encountered.
  48571. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  48572. // and avoid problems with multiple concurrent .babylon loads.
  48573. var log = "importMesh has failed JSON parse";
  48574. try {
  48575. var parsedData = JSON.parse(data);
  48576. log = "";
  48577. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  48578. if (!meshesNames) {
  48579. meshesNames = null;
  48580. }
  48581. else if (!Array.isArray(meshesNames)) {
  48582. meshesNames = [meshesNames];
  48583. }
  48584. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  48585. var loadedSkeletonsIds = [];
  48586. var loadedMaterialsIds = [];
  48587. var hierarchyIds = [];
  48588. var index;
  48589. var cache;
  48590. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  48591. var parsedMesh = parsedData.meshes[index];
  48592. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  48593. if (meshesNames !== null) {
  48594. // Remove found mesh name from list.
  48595. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  48596. }
  48597. //Geometry?
  48598. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  48599. //does the file contain geometries?
  48600. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  48601. //find the correct geometry and add it to the scene
  48602. var found = false;
  48603. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  48604. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  48605. return;
  48606. }
  48607. else {
  48608. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  48609. if (parsedGeometryData.id === parsedMesh.geometryId) {
  48610. switch (geometryType) {
  48611. case "boxes":
  48612. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  48613. break;
  48614. case "spheres":
  48615. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  48616. break;
  48617. case "cylinders":
  48618. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  48619. break;
  48620. case "toruses":
  48621. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  48622. break;
  48623. case "grounds":
  48624. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  48625. break;
  48626. case "planes":
  48627. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  48628. break;
  48629. case "torusKnots":
  48630. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  48631. break;
  48632. case "vertexData":
  48633. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  48634. break;
  48635. }
  48636. found = true;
  48637. }
  48638. });
  48639. }
  48640. });
  48641. if (found === false) {
  48642. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  48643. }
  48644. }
  48645. }
  48646. // Material ?
  48647. if (parsedMesh.materialId) {
  48648. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  48649. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  48650. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  48651. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  48652. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  48653. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  48654. var subMatId = parsedMultiMaterial.materials[matIndex];
  48655. loadedMaterialsIds.push(subMatId);
  48656. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  48657. log += "\n\tMaterial " + mat.toString(fullDetails);
  48658. }
  48659. loadedMaterialsIds.push(parsedMultiMaterial.id);
  48660. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  48661. materialFound = true;
  48662. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  48663. break;
  48664. }
  48665. }
  48666. }
  48667. if (materialFound === false) {
  48668. loadedMaterialsIds.push(parsedMesh.materialId);
  48669. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  48670. if (!mat) {
  48671. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  48672. }
  48673. else {
  48674. log += "\n\tMaterial " + mat.toString(fullDetails);
  48675. }
  48676. }
  48677. }
  48678. // Skeleton ?
  48679. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  48680. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  48681. if (skeletonAlreadyLoaded === false) {
  48682. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  48683. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  48684. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  48685. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  48686. skeletons.push(skeleton);
  48687. loadedSkeletonsIds.push(parsedSkeleton.id);
  48688. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  48689. }
  48690. }
  48691. }
  48692. }
  48693. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  48694. meshes.push(mesh);
  48695. log += "\n\tMesh " + mesh.toString(fullDetails);
  48696. }
  48697. }
  48698. // Connecting parents
  48699. var currentMesh;
  48700. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48701. currentMesh = scene.meshes[index];
  48702. if (currentMesh._waitingParentId) {
  48703. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  48704. currentMesh._waitingParentId = undefined;
  48705. }
  48706. }
  48707. // freeze and compute world matrix application
  48708. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48709. currentMesh = scene.meshes[index];
  48710. if (currentMesh._waitingFreezeWorldMatrix) {
  48711. currentMesh.freezeWorldMatrix();
  48712. currentMesh._waitingFreezeWorldMatrix = undefined;
  48713. }
  48714. else {
  48715. currentMesh.computeWorldMatrix(true);
  48716. }
  48717. }
  48718. }
  48719. // Particles
  48720. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  48721. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  48722. var parsedParticleSystem = parsedData.particleSystems[index];
  48723. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  48724. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  48725. }
  48726. }
  48727. }
  48728. return true;
  48729. }
  48730. catch (err) {
  48731. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  48732. log = null;
  48733. throw err;
  48734. }
  48735. finally {
  48736. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  48737. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  48738. }
  48739. }
  48740. },
  48741. load: function (scene, data, rootUrl) {
  48742. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  48743. // when SceneLoader.debugLogging = true (default), or exception encountered.
  48744. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  48745. // and avoid problems with multiple concurrent .babylon loads.
  48746. var log = "importScene has failed JSON parse";
  48747. try {
  48748. var parsedData = JSON.parse(data);
  48749. log = "";
  48750. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  48751. // Scene
  48752. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  48753. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  48754. }
  48755. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  48756. scene.autoClear = parsedData.autoClear;
  48757. }
  48758. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  48759. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  48760. }
  48761. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  48762. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  48763. }
  48764. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  48765. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  48766. }
  48767. // Fog
  48768. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  48769. scene.fogMode = parsedData.fogMode;
  48770. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  48771. scene.fogStart = parsedData.fogStart;
  48772. scene.fogEnd = parsedData.fogEnd;
  48773. scene.fogDensity = parsedData.fogDensity;
  48774. log += "\tFog mode for scene: ";
  48775. switch (scene.fogMode) {
  48776. // getters not compiling, so using hardcoded
  48777. case 1:
  48778. log += "exp\n";
  48779. break;
  48780. case 2:
  48781. log += "exp2\n";
  48782. break;
  48783. case 3:
  48784. log += "linear\n";
  48785. break;
  48786. }
  48787. }
  48788. //Physics
  48789. if (parsedData.physicsEnabled) {
  48790. var physicsPlugin;
  48791. if (parsedData.physicsEngine === "cannon") {
  48792. physicsPlugin = new BABYLON.CannonJSPlugin();
  48793. }
  48794. else if (parsedData.physicsEngine === "oimo") {
  48795. physicsPlugin = new BABYLON.OimoJSPlugin();
  48796. }
  48797. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  48798. //else - default engine, which is currently oimo
  48799. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  48800. scene.enablePhysics(physicsGravity, physicsPlugin);
  48801. }
  48802. // Metadata
  48803. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  48804. scene.metadata = parsedData.metadata;
  48805. }
  48806. //collisions, if defined. otherwise, default is true
  48807. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  48808. scene.collisionsEnabled = parsedData.collisionsEnabled;
  48809. }
  48810. scene.workerCollisions = !!parsedData.workerCollisions;
  48811. var index;
  48812. var cache;
  48813. // Lights
  48814. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  48815. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  48816. var parsedLight = parsedData.lights[index];
  48817. var light = BABYLON.Light.Parse(parsedLight, scene);
  48818. log += (index === 0 ? "\n\tLights:" : "");
  48819. log += "\n\t\t" + light.toString(fullDetails);
  48820. }
  48821. }
  48822. // Animations
  48823. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  48824. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  48825. var parsedAnimation = parsedData.animations[index];
  48826. var animation = BABYLON.Animation.Parse(parsedAnimation);
  48827. scene.animations.push(animation);
  48828. log += (index === 0 ? "\n\tAnimations:" : "");
  48829. log += "\n\t\t" + animation.toString(fullDetails);
  48830. }
  48831. }
  48832. if (parsedData.autoAnimate) {
  48833. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  48834. }
  48835. // Materials
  48836. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  48837. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  48838. var parsedMaterial = parsedData.materials[index];
  48839. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  48840. log += (index === 0 ? "\n\tMaterials:" : "");
  48841. log += "\n\t\t" + mat.toString(fullDetails);
  48842. }
  48843. }
  48844. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  48845. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  48846. var parsedMultiMaterial = parsedData.multiMaterials[index];
  48847. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  48848. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  48849. log += "\n\t\t" + mmat.toString(fullDetails);
  48850. }
  48851. }
  48852. // Morph targets
  48853. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  48854. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  48855. var managerData = _a[_i];
  48856. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  48857. }
  48858. }
  48859. // Skeletons
  48860. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  48861. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  48862. var parsedSkeleton = parsedData.skeletons[index];
  48863. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  48864. log += (index === 0 ? "\n\tSkeletons:" : "");
  48865. log += "\n\t\t" + skeleton.toString(fullDetails);
  48866. }
  48867. }
  48868. // Geometries
  48869. var geometries = parsedData.geometries;
  48870. if (geometries !== undefined && geometries !== null) {
  48871. // Boxes
  48872. var boxes = geometries.boxes;
  48873. if (boxes !== undefined && boxes !== null) {
  48874. for (index = 0, cache = boxes.length; index < cache; index++) {
  48875. var parsedBox = boxes[index];
  48876. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  48877. }
  48878. }
  48879. // Spheres
  48880. var spheres = geometries.spheres;
  48881. if (spheres !== undefined && spheres !== null) {
  48882. for (index = 0, cache = spheres.length; index < cache; index++) {
  48883. var parsedSphere = spheres[index];
  48884. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  48885. }
  48886. }
  48887. // Cylinders
  48888. var cylinders = geometries.cylinders;
  48889. if (cylinders !== undefined && cylinders !== null) {
  48890. for (index = 0, cache = cylinders.length; index < cache; index++) {
  48891. var parsedCylinder = cylinders[index];
  48892. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  48893. }
  48894. }
  48895. // Toruses
  48896. var toruses = geometries.toruses;
  48897. if (toruses !== undefined && toruses !== null) {
  48898. for (index = 0, cache = toruses.length; index < cache; index++) {
  48899. var parsedTorus = toruses[index];
  48900. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  48901. }
  48902. }
  48903. // Grounds
  48904. var grounds = geometries.grounds;
  48905. if (grounds !== undefined && grounds !== null) {
  48906. for (index = 0, cache = grounds.length; index < cache; index++) {
  48907. var parsedGround = grounds[index];
  48908. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  48909. }
  48910. }
  48911. // Planes
  48912. var planes = geometries.planes;
  48913. if (planes !== undefined && planes !== null) {
  48914. for (index = 0, cache = planes.length; index < cache; index++) {
  48915. var parsedPlane = planes[index];
  48916. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  48917. }
  48918. }
  48919. // TorusKnots
  48920. var torusKnots = geometries.torusKnots;
  48921. if (torusKnots !== undefined && torusKnots !== null) {
  48922. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  48923. var parsedTorusKnot = torusKnots[index];
  48924. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  48925. }
  48926. }
  48927. // VertexData
  48928. var vertexData = geometries.vertexData;
  48929. if (vertexData !== undefined && vertexData !== null) {
  48930. for (index = 0, cache = vertexData.length; index < cache; index++) {
  48931. var parsedVertexData = vertexData[index];
  48932. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  48933. }
  48934. }
  48935. }
  48936. // Meshes
  48937. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  48938. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  48939. var parsedMesh = parsedData.meshes[index];
  48940. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  48941. log += (index === 0 ? "\n\tMeshes:" : "");
  48942. log += "\n\t\t" + mesh.toString(fullDetails);
  48943. }
  48944. }
  48945. // Cameras
  48946. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  48947. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  48948. var parsedCamera = parsedData.cameras[index];
  48949. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  48950. log += (index === 0 ? "\n\tCameras:" : "");
  48951. log += "\n\t\t" + camera.toString(fullDetails);
  48952. }
  48953. }
  48954. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  48955. scene.setActiveCameraByID(parsedData.activeCameraID);
  48956. }
  48957. // Browsing all the graph to connect the dots
  48958. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  48959. var camera = scene.cameras[index];
  48960. if (camera._waitingParentId) {
  48961. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  48962. camera._waitingParentId = undefined;
  48963. }
  48964. }
  48965. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  48966. var light = scene.lights[index];
  48967. if (light._waitingParentId) {
  48968. light.parent = scene.getLastEntryByID(light._waitingParentId);
  48969. light._waitingParentId = undefined;
  48970. }
  48971. }
  48972. // Sounds
  48973. var loadedSounds = [];
  48974. var loadedSound;
  48975. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  48976. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  48977. var parsedSound = parsedData.sounds[index];
  48978. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48979. if (!parsedSound.url)
  48980. parsedSound.url = parsedSound.name;
  48981. if (!loadedSounds[parsedSound.url]) {
  48982. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  48983. loadedSounds[parsedSound.url] = loadedSound;
  48984. }
  48985. else {
  48986. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  48987. }
  48988. }
  48989. else {
  48990. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  48991. }
  48992. }
  48993. }
  48994. loadedSounds = [];
  48995. // Connect parents & children and parse actions
  48996. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48997. var mesh = scene.meshes[index];
  48998. if (mesh._waitingParentId) {
  48999. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  49000. mesh._waitingParentId = undefined;
  49001. }
  49002. if (mesh._waitingActions) {
  49003. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  49004. mesh._waitingActions = undefined;
  49005. }
  49006. }
  49007. // freeze world matrix application
  49008. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  49009. var currentMesh = scene.meshes[index];
  49010. if (currentMesh._waitingFreezeWorldMatrix) {
  49011. currentMesh.freezeWorldMatrix();
  49012. currentMesh._waitingFreezeWorldMatrix = undefined;
  49013. }
  49014. else {
  49015. currentMesh.computeWorldMatrix(true);
  49016. }
  49017. }
  49018. // Particles Systems
  49019. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  49020. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  49021. var parsedParticleSystem = parsedData.particleSystems[index];
  49022. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  49023. }
  49024. }
  49025. // Lens flares
  49026. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  49027. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  49028. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  49029. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  49030. }
  49031. }
  49032. // Shadows
  49033. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  49034. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  49035. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  49036. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  49037. }
  49038. }
  49039. // Lights exclusions / inclusions
  49040. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  49041. var light = scene.lights[index];
  49042. // Excluded check
  49043. if (light._excludedMeshesIds.length > 0) {
  49044. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  49045. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  49046. if (excludedMesh) {
  49047. light.excludedMeshes.push(excludedMesh);
  49048. }
  49049. }
  49050. light._excludedMeshesIds = [];
  49051. }
  49052. // Included check
  49053. if (light._includedOnlyMeshesIds.length > 0) {
  49054. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  49055. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  49056. if (includedOnlyMesh) {
  49057. light.includedOnlyMeshes.push(includedOnlyMesh);
  49058. }
  49059. }
  49060. light._includedOnlyMeshesIds = [];
  49061. }
  49062. }
  49063. // Actions (scene)
  49064. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  49065. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  49066. }
  49067. // Finish
  49068. return true;
  49069. }
  49070. catch (err) {
  49071. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  49072. log = null;
  49073. throw err;
  49074. }
  49075. finally {
  49076. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  49077. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  49078. }
  49079. }
  49080. }
  49081. });
  49082. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49083. })(BABYLON || (BABYLON = {}));
  49084. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  49085. var BABYLON;
  49086. (function (BABYLON) {
  49087. var FilesInput = (function () {
  49088. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback) {
  49089. this._engine = engine;
  49090. this._currentScene = scene;
  49091. this._sceneLoadedCallback = sceneLoadedCallback;
  49092. this._progressCallback = progressCallback;
  49093. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  49094. this._textureLoadingCallback = textureLoadingCallback;
  49095. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  49096. this._onReloadCallback = onReloadCallback;
  49097. }
  49098. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  49099. var _this = this;
  49100. if (elementToMonitor) {
  49101. this._elementToMonitor = elementToMonitor;
  49102. this._dragEnterHandler = function (e) { _this.drag(e); };
  49103. this._dragOverHandler = function (e) { _this.drag(e); };
  49104. this._dropHandler = function (e) { _this.drop(e); };
  49105. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  49106. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  49107. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  49108. }
  49109. };
  49110. FilesInput.prototype.dispose = function () {
  49111. if (!this._elementToMonitor) {
  49112. return;
  49113. }
  49114. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  49115. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  49116. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  49117. };
  49118. FilesInput.prototype.renderFunction = function () {
  49119. if (this._additionalRenderLoopLogicCallback) {
  49120. this._additionalRenderLoopLogicCallback();
  49121. }
  49122. if (this._currentScene) {
  49123. if (this._textureLoadingCallback) {
  49124. var remaining = this._currentScene.getWaitingItemsCount();
  49125. if (remaining > 0) {
  49126. this._textureLoadingCallback(remaining);
  49127. }
  49128. }
  49129. this._currentScene.render();
  49130. }
  49131. };
  49132. FilesInput.prototype.drag = function (e) {
  49133. e.stopPropagation();
  49134. e.preventDefault();
  49135. };
  49136. FilesInput.prototype.drop = function (eventDrop) {
  49137. eventDrop.stopPropagation();
  49138. eventDrop.preventDefault();
  49139. this.loadFiles(eventDrop);
  49140. };
  49141. FilesInput.prototype._handleFolderDrop = function (entry, files, callback) {
  49142. var reader = entry.createReader(), relativePath = entry.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  49143. reader.readEntries(function (fileEntries) {
  49144. var remaining = fileEntries.length;
  49145. for (var _i = 0, fileEntries_1 = fileEntries; _i < fileEntries_1.length; _i++) {
  49146. var fileEntry = fileEntries_1[_i];
  49147. if (fileEntry.isFile) {
  49148. fileEntry.file(function (file) {
  49149. file.correctName = relativePath + file.name;
  49150. files.push(file);
  49151. remaining--;
  49152. if (remaining === 0) {
  49153. callback();
  49154. }
  49155. });
  49156. }
  49157. else {
  49158. remaining--;
  49159. if (remaining === 0) {
  49160. callback();
  49161. }
  49162. }
  49163. }
  49164. });
  49165. };
  49166. FilesInput.prototype._processFiles = function (files) {
  49167. for (var i = 0; i < files.length; i++) {
  49168. var name = files[i].correctName.toLowerCase();
  49169. var extension = name.split('.').pop();
  49170. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  49171. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  49172. this._sceneFileToLoad = files[i];
  49173. }
  49174. else {
  49175. FilesInput.FilesToLoad[name] = files[i];
  49176. }
  49177. }
  49178. if (this._onReloadCallback) {
  49179. this._onReloadCallback(this._sceneFileToLoad);
  49180. }
  49181. else {
  49182. this.reload();
  49183. }
  49184. };
  49185. FilesInput.prototype.loadFiles = function (event) {
  49186. var _this = this;
  49187. if (this._startingProcessingFilesCallback)
  49188. this._startingProcessingFilesCallback();
  49189. // Handling data transfer via drag'n'drop
  49190. if (event && event.dataTransfer && event.dataTransfer.files) {
  49191. this._filesToLoad = event.dataTransfer.files;
  49192. }
  49193. // Handling files from input files
  49194. if (event && event.target && event.target.files) {
  49195. this._filesToLoad = event.target.files;
  49196. }
  49197. if (this._filesToLoad && this._filesToLoad.length > 0) {
  49198. var files_1 = [];
  49199. var folders = [];
  49200. var items = event.dataTransfer ? event.dataTransfer.items : null;
  49201. for (var i = 0; i < this._filesToLoad.length; i++) {
  49202. var fileToLoad = this._filesToLoad[i];
  49203. var name_1 = fileToLoad.name.toLowerCase();
  49204. var type = fileToLoad.type;
  49205. var entry = void 0;
  49206. fileToLoad.correctName = name_1;
  49207. if (items) {
  49208. var item = items[i];
  49209. if (item.getAsEntry) {
  49210. entry = item.getAsEntry();
  49211. }
  49212. else if (item.webkitGetAsEntry) {
  49213. entry = item.webkitGetAsEntry();
  49214. }
  49215. }
  49216. if (!entry) {
  49217. files_1.push(fileToLoad);
  49218. }
  49219. else {
  49220. if (entry.isDirectory) {
  49221. folders.push(entry);
  49222. }
  49223. else {
  49224. files_1.push(fileToLoad);
  49225. }
  49226. }
  49227. }
  49228. if (folders.length === 0) {
  49229. this._processFiles(files_1);
  49230. }
  49231. else {
  49232. var remaining = folders.length;
  49233. // Extract folder content
  49234. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  49235. var folder = folders_1[_i];
  49236. this._handleFolderDrop(folder, files_1, function () {
  49237. remaining--;
  49238. if (remaining === 0) {
  49239. _this._processFiles(files_1);
  49240. }
  49241. });
  49242. }
  49243. }
  49244. }
  49245. };
  49246. FilesInput.prototype.reload = function () {
  49247. var _this = this;
  49248. // If a ".babylon" file has been provided
  49249. if (this._sceneFileToLoad) {
  49250. if (this._currentScene) {
  49251. if (BABYLON.Tools.errorsCount > 0) {
  49252. BABYLON.Tools.ClearLogCache();
  49253. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  49254. }
  49255. this._engine.stopRenderLoop();
  49256. this._currentScene.dispose();
  49257. }
  49258. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  49259. _this._currentScene = newScene;
  49260. if (_this._sceneLoadedCallback) {
  49261. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  49262. }
  49263. // Wait for textures and shaders to be ready
  49264. _this._currentScene.executeWhenReady(function () {
  49265. _this._engine.runRenderLoop(function () {
  49266. _this.renderFunction();
  49267. });
  49268. });
  49269. }, function (progress) {
  49270. if (_this._progressCallback) {
  49271. _this._progressCallback(progress);
  49272. }
  49273. });
  49274. }
  49275. else {
  49276. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  49277. }
  49278. };
  49279. FilesInput.FilesToLoad = new Array();
  49280. return FilesInput;
  49281. }());
  49282. BABYLON.FilesInput = FilesInput;
  49283. })(BABYLON || (BABYLON = {}));
  49284. //# sourceMappingURL=babylon.filesInput.js.map
  49285. var BABYLON;
  49286. (function (BABYLON) {
  49287. /**
  49288. * This class implement a typical dictionary using a string as key and the generic type T as value.
  49289. * The underlying implementation relies on an associative array to ensure the best performances.
  49290. * The value can be anything including 'null' but except 'undefined'
  49291. */
  49292. var StringDictionary = (function () {
  49293. function StringDictionary() {
  49294. this._count = 0;
  49295. this._data = {};
  49296. }
  49297. /**
  49298. * This will clear this dictionary and copy the content from the 'source' one.
  49299. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  49300. * @param source the dictionary to take the content from and copy to this dictionary
  49301. */
  49302. StringDictionary.prototype.copyFrom = function (source) {
  49303. var _this = this;
  49304. this.clear();
  49305. source.forEach(function (t, v) { return _this.add(t, v); });
  49306. };
  49307. /**
  49308. * Get a value based from its key
  49309. * @param key the given key to get the matching value from
  49310. * @return the value if found, otherwise undefined is returned
  49311. */
  49312. StringDictionary.prototype.get = function (key) {
  49313. var val = this._data[key];
  49314. if (val !== undefined) {
  49315. return val;
  49316. }
  49317. return undefined;
  49318. };
  49319. /**
  49320. * Get a value from its key or add it if it doesn't exist.
  49321. * This method will ensure you that a given key/data will be present in the dictionary.
  49322. * @param key the given key to get the matching value from
  49323. * @param factory the factory that will create the value if the key is not present in the dictionary.
  49324. * The factory will only be invoked if there's no data for the given key.
  49325. * @return the value corresponding to the key.
  49326. */
  49327. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  49328. var val = this.get(key);
  49329. if (val !== undefined) {
  49330. return val;
  49331. }
  49332. val = factory(key);
  49333. if (val) {
  49334. this.add(key, val);
  49335. }
  49336. return val;
  49337. };
  49338. /**
  49339. * Get a value from its key if present in the dictionary otherwise add it
  49340. * @param key the key to get the value from
  49341. * @param val if there's no such key/value pair in the dictionary add it with this value
  49342. * @return the value corresponding to the key
  49343. */
  49344. StringDictionary.prototype.getOrAdd = function (key, val) {
  49345. var curVal = this.get(key);
  49346. if (curVal !== undefined) {
  49347. return curVal;
  49348. }
  49349. this.add(key, val);
  49350. return val;
  49351. };
  49352. /**
  49353. * Check if there's a given key in the dictionary
  49354. * @param key the key to check for
  49355. * @return true if the key is present, false otherwise
  49356. */
  49357. StringDictionary.prototype.contains = function (key) {
  49358. return this._data[key] !== undefined;
  49359. };
  49360. /**
  49361. * Add a new key and its corresponding value
  49362. * @param key the key to add
  49363. * @param value the value corresponding to the key
  49364. * @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
  49365. */
  49366. StringDictionary.prototype.add = function (key, value) {
  49367. if (this._data[key] !== undefined) {
  49368. return false;
  49369. }
  49370. this._data[key] = value;
  49371. ++this._count;
  49372. return true;
  49373. };
  49374. StringDictionary.prototype.set = function (key, value) {
  49375. if (this._data[key] === undefined) {
  49376. return false;
  49377. }
  49378. this._data[key] = value;
  49379. return true;
  49380. };
  49381. /**
  49382. * Get the element of the given key and remove it from the dictionary
  49383. * @param key
  49384. */
  49385. StringDictionary.prototype.getAndRemove = function (key) {
  49386. var val = this.get(key);
  49387. if (val !== undefined) {
  49388. delete this._data[key];
  49389. --this._count;
  49390. return val;
  49391. }
  49392. return null;
  49393. };
  49394. /**
  49395. * Remove a key/value from the dictionary.
  49396. * @param key the key to remove
  49397. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  49398. */
  49399. StringDictionary.prototype.remove = function (key) {
  49400. if (this.contains(key)) {
  49401. delete this._data[key];
  49402. --this._count;
  49403. return true;
  49404. }
  49405. return false;
  49406. };
  49407. /**
  49408. * Clear the whole content of the dictionary
  49409. */
  49410. StringDictionary.prototype.clear = function () {
  49411. this._data = {};
  49412. this._count = 0;
  49413. };
  49414. Object.defineProperty(StringDictionary.prototype, "count", {
  49415. get: function () {
  49416. return this._count;
  49417. },
  49418. enumerable: true,
  49419. configurable: true
  49420. });
  49421. /**
  49422. * Execute a callback on each key/val of the dictionary.
  49423. * Note that you can remove any element in this dictionary in the callback implementation
  49424. * @param callback the callback to execute on a given key/value pair
  49425. */
  49426. StringDictionary.prototype.forEach = function (callback) {
  49427. for (var cur in this._data) {
  49428. var val = this._data[cur];
  49429. callback(cur, val);
  49430. }
  49431. };
  49432. /**
  49433. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  49434. * If the callback returns null or undefined the method will iterate to the next key/value pair
  49435. * Note that you can remove any element in this dictionary in the callback implementation
  49436. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  49437. */
  49438. StringDictionary.prototype.first = function (callback) {
  49439. for (var cur in this._data) {
  49440. var val = this._data[cur];
  49441. var res = callback(cur, val);
  49442. if (res) {
  49443. return res;
  49444. }
  49445. }
  49446. return null;
  49447. };
  49448. return StringDictionary;
  49449. }());
  49450. BABYLON.StringDictionary = StringDictionary;
  49451. })(BABYLON || (BABYLON = {}));
  49452. //# sourceMappingURL=babylon.stringDictionary.js.map
  49453. var BABYLON;
  49454. (function (BABYLON) {
  49455. var Tags = (function () {
  49456. function Tags() {
  49457. }
  49458. Tags.EnableFor = function (obj) {
  49459. obj._tags = obj._tags || {};
  49460. obj.hasTags = function () {
  49461. return Tags.HasTags(obj);
  49462. };
  49463. obj.addTags = function (tagsString) {
  49464. return Tags.AddTagsTo(obj, tagsString);
  49465. };
  49466. obj.removeTags = function (tagsString) {
  49467. return Tags.RemoveTagsFrom(obj, tagsString);
  49468. };
  49469. obj.matchesTagsQuery = function (tagsQuery) {
  49470. return Tags.MatchesQuery(obj, tagsQuery);
  49471. };
  49472. };
  49473. Tags.DisableFor = function (obj) {
  49474. delete obj._tags;
  49475. delete obj.hasTags;
  49476. delete obj.addTags;
  49477. delete obj.removeTags;
  49478. delete obj.matchesTagsQuery;
  49479. };
  49480. Tags.HasTags = function (obj) {
  49481. if (!obj._tags) {
  49482. return false;
  49483. }
  49484. return !BABYLON.Tools.IsEmpty(obj._tags);
  49485. };
  49486. Tags.GetTags = function (obj, asString) {
  49487. if (asString === void 0) { asString = true; }
  49488. if (!obj._tags) {
  49489. return null;
  49490. }
  49491. if (asString) {
  49492. var tagsArray = [];
  49493. for (var tag in obj._tags) {
  49494. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  49495. tagsArray.push(tag);
  49496. }
  49497. }
  49498. return tagsArray.join(" ");
  49499. }
  49500. else {
  49501. return obj._tags;
  49502. }
  49503. };
  49504. // the tags 'true' and 'false' are reserved and cannot be used as tags
  49505. // a tag cannot start with '||', '&&', and '!'
  49506. // it cannot contain whitespaces
  49507. Tags.AddTagsTo = function (obj, tagsString) {
  49508. if (!tagsString) {
  49509. return;
  49510. }
  49511. if (typeof tagsString !== "string") {
  49512. return;
  49513. }
  49514. var tags = tagsString.split(" ");
  49515. tags.forEach(function (tag, index, array) {
  49516. Tags._AddTagTo(obj, tag);
  49517. });
  49518. };
  49519. Tags._AddTagTo = function (obj, tag) {
  49520. tag = tag.trim();
  49521. if (tag === "" || tag === "true" || tag === "false") {
  49522. return;
  49523. }
  49524. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  49525. return;
  49526. }
  49527. Tags.EnableFor(obj);
  49528. obj._tags[tag] = true;
  49529. };
  49530. Tags.RemoveTagsFrom = function (obj, tagsString) {
  49531. if (!Tags.HasTags(obj)) {
  49532. return;
  49533. }
  49534. var tags = tagsString.split(" ");
  49535. for (var t in tags) {
  49536. Tags._RemoveTagFrom(obj, tags[t]);
  49537. }
  49538. };
  49539. Tags._RemoveTagFrom = function (obj, tag) {
  49540. delete obj._tags[tag];
  49541. };
  49542. Tags.MatchesQuery = function (obj, tagsQuery) {
  49543. if (tagsQuery === undefined) {
  49544. return true;
  49545. }
  49546. if (tagsQuery === "") {
  49547. return Tags.HasTags(obj);
  49548. }
  49549. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  49550. };
  49551. return Tags;
  49552. }());
  49553. BABYLON.Tags = Tags;
  49554. })(BABYLON || (BABYLON = {}));
  49555. //# sourceMappingURL=babylon.tags.js.map
  49556. var BABYLON;
  49557. (function (BABYLON) {
  49558. var Internals;
  49559. (function (Internals) {
  49560. var AndOrNotEvaluator = (function () {
  49561. function AndOrNotEvaluator() {
  49562. }
  49563. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  49564. if (!query.match(/\([^\(\)]*\)/g)) {
  49565. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  49566. }
  49567. else {
  49568. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  49569. // remove parenthesis
  49570. r = r.slice(1, r.length - 1);
  49571. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  49572. });
  49573. }
  49574. if (query === "true") {
  49575. return true;
  49576. }
  49577. if (query === "false") {
  49578. return false;
  49579. }
  49580. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  49581. };
  49582. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  49583. evaluateCallback = evaluateCallback || (function (r) {
  49584. return r === "true" ? true : false;
  49585. });
  49586. var result;
  49587. var or = parenthesisContent.split("||");
  49588. for (var i in or) {
  49589. if (or.hasOwnProperty(i)) {
  49590. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  49591. var and = ori.split("&&");
  49592. if (and.length > 1) {
  49593. for (var j = 0; j < and.length; ++j) {
  49594. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  49595. if (andj !== "true" && andj !== "false") {
  49596. if (andj[0] === "!") {
  49597. result = !evaluateCallback(andj.substring(1));
  49598. }
  49599. else {
  49600. result = evaluateCallback(andj);
  49601. }
  49602. }
  49603. else {
  49604. result = andj === "true" ? true : false;
  49605. }
  49606. if (!result) {
  49607. ori = "false";
  49608. break;
  49609. }
  49610. }
  49611. }
  49612. if (result || ori === "true") {
  49613. result = true;
  49614. break;
  49615. }
  49616. // result equals false (or undefined)
  49617. if (ori !== "true" && ori !== "false") {
  49618. if (ori[0] === "!") {
  49619. result = !evaluateCallback(ori.substring(1));
  49620. }
  49621. else {
  49622. result = evaluateCallback(ori);
  49623. }
  49624. }
  49625. else {
  49626. result = ori === "true" ? true : false;
  49627. }
  49628. }
  49629. }
  49630. // the whole parenthesis scope is replaced by 'true' or 'false'
  49631. return result ? "true" : "false";
  49632. };
  49633. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  49634. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  49635. // remove whitespaces
  49636. r = r.replace(/[\s]/g, function () { return ""; });
  49637. return r.length % 2 ? "!" : "";
  49638. });
  49639. booleanString = booleanString.trim();
  49640. if (booleanString === "!true") {
  49641. booleanString = "false";
  49642. }
  49643. else if (booleanString === "!false") {
  49644. booleanString = "true";
  49645. }
  49646. return booleanString;
  49647. };
  49648. return AndOrNotEvaluator;
  49649. }());
  49650. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  49651. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49652. })(BABYLON || (BABYLON = {}));
  49653. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  49654. var BABYLON;
  49655. (function (BABYLON) {
  49656. var Database = (function () {
  49657. function Database(urlToScene, callbackManifestChecked) {
  49658. // Handling various flavors of prefixed version of IndexedDB
  49659. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  49660. this.callbackManifestChecked = callbackManifestChecked;
  49661. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  49662. this.db = null;
  49663. this.enableSceneOffline = false;
  49664. this.enableTexturesOffline = false;
  49665. this.manifestVersionFound = 0;
  49666. this.mustUpdateRessources = false;
  49667. this.hasReachedQuota = false;
  49668. if (!Database.IDBStorageEnabled) {
  49669. this.callbackManifestChecked(true);
  49670. }
  49671. else {
  49672. this.checkManifestFile();
  49673. }
  49674. }
  49675. Database.prototype.checkManifestFile = function () {
  49676. var _this = this;
  49677. function noManifestFile() {
  49678. that.enableSceneOffline = false;
  49679. that.enableTexturesOffline = false;
  49680. that.callbackManifestChecked(false);
  49681. }
  49682. var that = this;
  49683. var timeStampUsed = false;
  49684. var manifestURL = this.currentSceneUrl + ".manifest";
  49685. var xhr = new XMLHttpRequest();
  49686. if (navigator.onLine) {
  49687. // Adding a timestamp to by-pass browsers' cache
  49688. timeStampUsed = true;
  49689. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  49690. }
  49691. xhr.open("GET", manifestURL, true);
  49692. xhr.addEventListener("load", function () {
  49693. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  49694. try {
  49695. var manifestFile = JSON.parse(xhr.response);
  49696. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  49697. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  49698. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  49699. _this.manifestVersionFound = manifestFile.version;
  49700. }
  49701. if (_this.callbackManifestChecked) {
  49702. _this.callbackManifestChecked(true);
  49703. }
  49704. }
  49705. catch (ex) {
  49706. noManifestFile();
  49707. }
  49708. }
  49709. else {
  49710. noManifestFile();
  49711. }
  49712. }, false);
  49713. xhr.addEventListener("error", function (event) {
  49714. if (timeStampUsed) {
  49715. timeStampUsed = false;
  49716. // Let's retry without the timeStamp
  49717. // It could fail when coupled with HTML5 Offline API
  49718. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  49719. xhr.open("GET", retryManifestURL, true);
  49720. xhr.send();
  49721. }
  49722. else {
  49723. noManifestFile();
  49724. }
  49725. }, false);
  49726. try {
  49727. xhr.send();
  49728. }
  49729. catch (ex) {
  49730. BABYLON.Tools.Error("Error on XHR send request.");
  49731. that.callbackManifestChecked(false);
  49732. }
  49733. };
  49734. Database.prototype.openAsync = function (successCallback, errorCallback) {
  49735. var _this = this;
  49736. function handleError() {
  49737. that.isSupported = false;
  49738. if (errorCallback)
  49739. errorCallback();
  49740. }
  49741. var that = this;
  49742. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  49743. // Your browser doesn't support IndexedDB
  49744. this.isSupported = false;
  49745. if (errorCallback)
  49746. errorCallback();
  49747. }
  49748. else {
  49749. // If the DB hasn't been opened or created yet
  49750. if (!this.db) {
  49751. this.hasReachedQuota = false;
  49752. this.isSupported = true;
  49753. var request = this.idbFactory.open("babylonjs", 1);
  49754. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  49755. request.onerror = function (event) {
  49756. handleError();
  49757. };
  49758. // executes when a version change transaction cannot complete due to other active transactions
  49759. request.onblocked = function (event) {
  49760. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  49761. handleError();
  49762. };
  49763. // DB has been opened successfully
  49764. request.onsuccess = function (event) {
  49765. _this.db = request.result;
  49766. successCallback();
  49767. };
  49768. // Initialization of the DB. Creating Scenes & Textures stores
  49769. request.onupgradeneeded = function (event) {
  49770. _this.db = (event.target).result;
  49771. try {
  49772. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  49773. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  49774. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  49775. }
  49776. catch (ex) {
  49777. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  49778. handleError();
  49779. }
  49780. };
  49781. }
  49782. else {
  49783. if (successCallback)
  49784. successCallback();
  49785. }
  49786. }
  49787. };
  49788. Database.prototype.loadImageFromDB = function (url, image) {
  49789. var _this = this;
  49790. var completeURL = Database.ReturnFullUrlLocation(url);
  49791. var saveAndLoadImage = function () {
  49792. if (!_this.hasReachedQuota && _this.db !== null) {
  49793. // the texture is not yet in the DB, let's try to save it
  49794. _this._saveImageIntoDBAsync(completeURL, image);
  49795. }
  49796. else {
  49797. image.src = url;
  49798. }
  49799. };
  49800. if (!this.mustUpdateRessources) {
  49801. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  49802. }
  49803. else {
  49804. saveAndLoadImage();
  49805. }
  49806. };
  49807. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  49808. if (this.isSupported && this.db !== null) {
  49809. var texture;
  49810. var transaction = this.db.transaction(["textures"]);
  49811. transaction.onabort = function (event) {
  49812. image.src = url;
  49813. };
  49814. transaction.oncomplete = function (event) {
  49815. var blobTextureURL;
  49816. if (texture) {
  49817. var URL = window.URL || window.webkitURL;
  49818. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  49819. image.onerror = function () {
  49820. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  49821. image.src = url;
  49822. };
  49823. image.src = blobTextureURL;
  49824. }
  49825. else {
  49826. notInDBCallback();
  49827. }
  49828. };
  49829. var getRequest = transaction.objectStore("textures").get(url);
  49830. getRequest.onsuccess = function (event) {
  49831. texture = (event.target).result;
  49832. };
  49833. getRequest.onerror = function (event) {
  49834. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  49835. image.src = url;
  49836. };
  49837. }
  49838. else {
  49839. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  49840. image.src = url;
  49841. }
  49842. };
  49843. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  49844. var _this = this;
  49845. if (this.isSupported) {
  49846. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  49847. var generateBlobUrl = function () {
  49848. var blobTextureURL;
  49849. if (blob) {
  49850. var URL = window.URL || window.webkitURL;
  49851. try {
  49852. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  49853. }
  49854. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  49855. catch (ex) {
  49856. blobTextureURL = URL.createObjectURL(blob);
  49857. }
  49858. }
  49859. image.src = blobTextureURL;
  49860. };
  49861. if (Database.IsUASupportingBlobStorage) {
  49862. var xhr = new XMLHttpRequest(), blob;
  49863. xhr.open("GET", url, true);
  49864. xhr.responseType = "blob";
  49865. xhr.addEventListener("load", function () {
  49866. if (xhr.status === 200) {
  49867. // Blob as response (XHR2)
  49868. blob = xhr.response;
  49869. var transaction = _this.db.transaction(["textures"], "readwrite");
  49870. // the transaction could abort because of a QuotaExceededError error
  49871. transaction.onabort = function (event) {
  49872. try {
  49873. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  49874. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  49875. _this.hasReachedQuota = true;
  49876. }
  49877. }
  49878. catch (ex) { }
  49879. generateBlobUrl();
  49880. };
  49881. transaction.oncomplete = function (event) {
  49882. generateBlobUrl();
  49883. };
  49884. var newTexture = { textureUrl: url, data: blob };
  49885. try {
  49886. // Put the blob into the dabase
  49887. var addRequest = transaction.objectStore("textures").put(newTexture);
  49888. addRequest.onsuccess = function (event) {
  49889. };
  49890. addRequest.onerror = function (event) {
  49891. generateBlobUrl();
  49892. };
  49893. }
  49894. catch (ex) {
  49895. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  49896. if (ex.code === 25) {
  49897. Database.IsUASupportingBlobStorage = false;
  49898. }
  49899. image.src = url;
  49900. }
  49901. }
  49902. else {
  49903. image.src = url;
  49904. }
  49905. }, false);
  49906. xhr.addEventListener("error", function (event) {
  49907. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  49908. image.src = url;
  49909. }, false);
  49910. xhr.send();
  49911. }
  49912. else {
  49913. image.src = url;
  49914. }
  49915. }
  49916. else {
  49917. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  49918. image.src = url;
  49919. }
  49920. };
  49921. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  49922. var _this = this;
  49923. var updateVersion = function (event) {
  49924. // the version is not yet in the DB or we need to update it
  49925. _this._saveVersionIntoDBAsync(url, versionLoaded);
  49926. };
  49927. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  49928. };
  49929. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  49930. var _this = this;
  49931. if (this.isSupported) {
  49932. var version;
  49933. try {
  49934. var transaction = this.db.transaction(["versions"]);
  49935. transaction.oncomplete = function (event) {
  49936. if (version) {
  49937. // If the version in the JSON file is > than the version in DB
  49938. if (_this.manifestVersionFound > version.data) {
  49939. _this.mustUpdateRessources = true;
  49940. updateInDBCallback();
  49941. }
  49942. else {
  49943. callback(version.data);
  49944. }
  49945. }
  49946. else {
  49947. _this.mustUpdateRessources = true;
  49948. updateInDBCallback();
  49949. }
  49950. };
  49951. transaction.onabort = function (event) {
  49952. callback(-1);
  49953. };
  49954. var getRequest = transaction.objectStore("versions").get(url);
  49955. getRequest.onsuccess = function (event) {
  49956. version = (event.target).result;
  49957. };
  49958. getRequest.onerror = function (event) {
  49959. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  49960. callback(-1);
  49961. };
  49962. }
  49963. catch (ex) {
  49964. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  49965. callback(-1);
  49966. }
  49967. }
  49968. else {
  49969. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  49970. callback(-1);
  49971. }
  49972. };
  49973. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  49974. var _this = this;
  49975. if (this.isSupported && !this.hasReachedQuota) {
  49976. try {
  49977. // Open a transaction to the database
  49978. var transaction = this.db.transaction(["versions"], "readwrite");
  49979. // the transaction could abort because of a QuotaExceededError error
  49980. transaction.onabort = function (event) {
  49981. try {
  49982. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  49983. _this.hasReachedQuota = true;
  49984. }
  49985. }
  49986. catch (ex) { }
  49987. callback(-1);
  49988. };
  49989. transaction.oncomplete = function (event) {
  49990. callback(_this.manifestVersionFound);
  49991. };
  49992. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  49993. // Put the scene into the database
  49994. var addRequest = transaction.objectStore("versions").put(newVersion);
  49995. addRequest.onsuccess = function (event) {
  49996. };
  49997. addRequest.onerror = function (event) {
  49998. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  49999. };
  50000. }
  50001. catch (ex) {
  50002. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  50003. callback(-1);
  50004. }
  50005. }
  50006. else {
  50007. callback(-1);
  50008. }
  50009. };
  50010. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  50011. var _this = this;
  50012. var completeUrl = Database.ReturnFullUrlLocation(url);
  50013. var saveAndLoadFile = function (event) {
  50014. // the scene is not yet in the DB, let's try to save it
  50015. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  50016. };
  50017. this._checkVersionFromDB(completeUrl, function (version) {
  50018. if (version !== -1) {
  50019. if (!_this.mustUpdateRessources) {
  50020. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  50021. }
  50022. else {
  50023. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  50024. }
  50025. }
  50026. else {
  50027. errorCallback();
  50028. }
  50029. });
  50030. };
  50031. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  50032. if (this.isSupported) {
  50033. var targetStore;
  50034. if (url.indexOf(".babylon") !== -1) {
  50035. targetStore = "scenes";
  50036. }
  50037. else {
  50038. targetStore = "textures";
  50039. }
  50040. var file;
  50041. var transaction = this.db.transaction([targetStore]);
  50042. transaction.oncomplete = function (event) {
  50043. if (file) {
  50044. callback(file.data);
  50045. }
  50046. else {
  50047. notInDBCallback();
  50048. }
  50049. };
  50050. transaction.onabort = function (event) {
  50051. notInDBCallback();
  50052. };
  50053. var getRequest = transaction.objectStore(targetStore).get(url);
  50054. getRequest.onsuccess = function (event) {
  50055. file = (event.target).result;
  50056. };
  50057. getRequest.onerror = function (event) {
  50058. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  50059. notInDBCallback();
  50060. };
  50061. }
  50062. else {
  50063. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  50064. callback();
  50065. }
  50066. };
  50067. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  50068. var _this = this;
  50069. if (this.isSupported) {
  50070. var targetStore;
  50071. if (url.indexOf(".babylon") !== -1) {
  50072. targetStore = "scenes";
  50073. }
  50074. else {
  50075. targetStore = "textures";
  50076. }
  50077. // Create XHR
  50078. var xhr = new XMLHttpRequest(), fileData;
  50079. xhr.open("GET", url, true);
  50080. if (useArrayBuffer) {
  50081. xhr.responseType = "arraybuffer";
  50082. }
  50083. xhr.onprogress = progressCallback;
  50084. xhr.addEventListener("load", function () {
  50085. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  50086. // Blob as response (XHR2)
  50087. //fileData = xhr.responseText;
  50088. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  50089. if (!_this.hasReachedQuota) {
  50090. // Open a transaction to the database
  50091. var transaction = _this.db.transaction([targetStore], "readwrite");
  50092. // the transaction could abort because of a QuotaExceededError error
  50093. transaction.onabort = function (event) {
  50094. try {
  50095. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  50096. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  50097. _this.hasReachedQuota = true;
  50098. }
  50099. }
  50100. catch (ex) { }
  50101. callback(fileData);
  50102. };
  50103. transaction.oncomplete = function (event) {
  50104. callback(fileData);
  50105. };
  50106. var newFile;
  50107. if (targetStore === "scenes") {
  50108. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  50109. }
  50110. else {
  50111. newFile = { textureUrl: url, data: fileData };
  50112. }
  50113. try {
  50114. // Put the scene into the database
  50115. var addRequest = transaction.objectStore(targetStore).put(newFile);
  50116. addRequest.onsuccess = function (event) {
  50117. };
  50118. addRequest.onerror = function (event) {
  50119. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  50120. };
  50121. }
  50122. catch (ex) {
  50123. callback(fileData);
  50124. }
  50125. }
  50126. else {
  50127. callback(fileData);
  50128. }
  50129. }
  50130. else {
  50131. callback();
  50132. }
  50133. }, false);
  50134. xhr.addEventListener("error", function (event) {
  50135. BABYLON.Tools.Error("error on XHR request.");
  50136. callback();
  50137. }, false);
  50138. xhr.send();
  50139. }
  50140. else {
  50141. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  50142. callback();
  50143. }
  50144. };
  50145. Database.IsUASupportingBlobStorage = true;
  50146. Database.IDBStorageEnabled = true;
  50147. Database.parseURL = function (url) {
  50148. var a = document.createElement('a');
  50149. a.href = url;
  50150. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  50151. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  50152. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  50153. return absLocation;
  50154. };
  50155. Database.ReturnFullUrlLocation = function (url) {
  50156. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  50157. return (Database.parseURL(window.location.href) + url);
  50158. }
  50159. else {
  50160. return url;
  50161. }
  50162. };
  50163. return Database;
  50164. }());
  50165. BABYLON.Database = Database;
  50166. })(BABYLON || (BABYLON = {}));
  50167. //# sourceMappingURL=babylon.database.js.map
  50168. var BABYLON;
  50169. (function (BABYLON) {
  50170. var FresnelParameters = (function () {
  50171. function FresnelParameters() {
  50172. this._isEnabled = true;
  50173. this.leftColor = BABYLON.Color3.White();
  50174. this.rightColor = BABYLON.Color3.Black();
  50175. this.bias = 0;
  50176. this.power = 1;
  50177. }
  50178. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  50179. get: function () {
  50180. return this._isEnabled;
  50181. },
  50182. set: function (value) {
  50183. if (this._isEnabled === value) {
  50184. return;
  50185. }
  50186. this._isEnabled = value;
  50187. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  50188. },
  50189. enumerable: true,
  50190. configurable: true
  50191. });
  50192. FresnelParameters.prototype.clone = function () {
  50193. var newFresnelParameters = new FresnelParameters();
  50194. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  50195. return newFresnelParameters;
  50196. };
  50197. FresnelParameters.prototype.serialize = function () {
  50198. var serializationObject = {};
  50199. serializationObject.isEnabled = this.isEnabled;
  50200. serializationObject.leftColor = this.leftColor;
  50201. serializationObject.rightColor = this.rightColor;
  50202. serializationObject.bias = this.bias;
  50203. serializationObject.power = this.power;
  50204. return serializationObject;
  50205. };
  50206. FresnelParameters.Parse = function (parsedFresnelParameters) {
  50207. var fresnelParameters = new FresnelParameters();
  50208. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  50209. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  50210. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  50211. fresnelParameters.bias = parsedFresnelParameters.bias;
  50212. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  50213. return fresnelParameters;
  50214. };
  50215. return FresnelParameters;
  50216. }());
  50217. BABYLON.FresnelParameters = FresnelParameters;
  50218. })(BABYLON || (BABYLON = {}));
  50219. //# sourceMappingURL=babylon.fresnelParameters.js.map
  50220. var BABYLON;
  50221. (function (BABYLON) {
  50222. var MultiMaterial = (function (_super) {
  50223. __extends(MultiMaterial, _super);
  50224. function MultiMaterial(name, scene) {
  50225. var _this = _super.call(this, name, scene, true) || this;
  50226. scene.multiMaterials.push(_this);
  50227. _this.subMaterials = new Array();
  50228. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  50229. return _this;
  50230. }
  50231. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  50232. get: function () {
  50233. return this._subMaterials;
  50234. },
  50235. set: function (value) {
  50236. this._subMaterials = value;
  50237. this._hookArray(value);
  50238. },
  50239. enumerable: true,
  50240. configurable: true
  50241. });
  50242. MultiMaterial.prototype._hookArray = function (array) {
  50243. var _this = this;
  50244. var oldPush = array.push;
  50245. array.push = function () {
  50246. var items = [];
  50247. for (var _i = 0; _i < arguments.length; _i++) {
  50248. items[_i] = arguments[_i];
  50249. }
  50250. var result = oldPush.apply(array, items);
  50251. _this._markAllSubMeshesAsTexturesDirty();
  50252. return result;
  50253. };
  50254. var oldSplice = array.splice;
  50255. array.splice = function (index, deleteCount) {
  50256. var deleted = oldSplice.apply(array, [index, deleteCount]);
  50257. _this._markAllSubMeshesAsTexturesDirty();
  50258. return deleted;
  50259. };
  50260. };
  50261. // Properties
  50262. MultiMaterial.prototype.getSubMaterial = function (index) {
  50263. if (index < 0 || index >= this.subMaterials.length) {
  50264. return this.getScene().defaultMaterial;
  50265. }
  50266. return this.subMaterials[index];
  50267. };
  50268. MultiMaterial.prototype.getActiveTextures = function () {
  50269. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  50270. var _a;
  50271. };
  50272. // Methods
  50273. MultiMaterial.prototype.getClassName = function () {
  50274. return "MultiMaterial";
  50275. };
  50276. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  50277. for (var index = 0; index < this.subMaterials.length; index++) {
  50278. var subMaterial = this.subMaterials[index];
  50279. if (subMaterial) {
  50280. if (this.subMaterials[index].storeEffectOnSubMeshes) {
  50281. if (!this.subMaterials[index].isReadyForSubMesh(mesh, subMesh, useInstances)) {
  50282. return false;
  50283. }
  50284. continue;
  50285. }
  50286. if (!this.subMaterials[index].isReady(mesh)) {
  50287. return false;
  50288. }
  50289. }
  50290. }
  50291. return true;
  50292. };
  50293. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  50294. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  50295. for (var index = 0; index < this.subMaterials.length; index++) {
  50296. var subMaterial = null;
  50297. if (cloneChildren) {
  50298. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  50299. }
  50300. else {
  50301. subMaterial = this.subMaterials[index];
  50302. }
  50303. newMultiMaterial.subMaterials.push(subMaterial);
  50304. }
  50305. return newMultiMaterial;
  50306. };
  50307. MultiMaterial.prototype.serialize = function () {
  50308. var serializationObject = {};
  50309. serializationObject.name = this.name;
  50310. serializationObject.id = this.id;
  50311. serializationObject.tags = BABYLON.Tags.GetTags(this);
  50312. serializationObject.materials = [];
  50313. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  50314. var subMat = this.subMaterials[matIndex];
  50315. if (subMat) {
  50316. serializationObject.materials.push(subMat.id);
  50317. }
  50318. else {
  50319. serializationObject.materials.push(null);
  50320. }
  50321. }
  50322. return serializationObject;
  50323. };
  50324. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  50325. var scene = this.getScene();
  50326. if (!scene) {
  50327. return;
  50328. }
  50329. var index = scene.multiMaterials.indexOf(this);
  50330. if (index >= 0) {
  50331. scene.multiMaterials.splice(index, 1);
  50332. }
  50333. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  50334. };
  50335. return MultiMaterial;
  50336. }(BABYLON.Material));
  50337. BABYLON.MultiMaterial = MultiMaterial;
  50338. })(BABYLON || (BABYLON = {}));
  50339. //# sourceMappingURL=babylon.multiMaterial.js.map
  50340. var BABYLON;
  50341. (function (BABYLON) {
  50342. var FreeCameraTouchInput = (function () {
  50343. function FreeCameraTouchInput() {
  50344. this._offsetX = null;
  50345. this._offsetY = null;
  50346. this._pointerCount = 0;
  50347. this._pointerPressed = [];
  50348. this.touchAngularSensibility = 200000.0;
  50349. this.touchMoveSensibility = 250.0;
  50350. }
  50351. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  50352. var _this = this;
  50353. var previousPosition;
  50354. if (this._pointerInput === undefined) {
  50355. this._onLostFocus = function (evt) {
  50356. _this._offsetX = null;
  50357. _this._offsetY = null;
  50358. };
  50359. this._pointerInput = function (p, s) {
  50360. var evt = p.event;
  50361. if (evt.pointerType === "mouse") {
  50362. return;
  50363. }
  50364. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  50365. if (!noPreventDefault) {
  50366. evt.preventDefault();
  50367. }
  50368. _this._pointerPressed.push(evt.pointerId);
  50369. if (_this._pointerPressed.length !== 1) {
  50370. return;
  50371. }
  50372. previousPosition = {
  50373. x: evt.clientX,
  50374. y: evt.clientY
  50375. };
  50376. }
  50377. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  50378. if (!noPreventDefault) {
  50379. evt.preventDefault();
  50380. }
  50381. var index = _this._pointerPressed.indexOf(evt.pointerId);
  50382. if (index === -1) {
  50383. return;
  50384. }
  50385. _this._pointerPressed.splice(index, 1);
  50386. if (index != 0) {
  50387. return;
  50388. }
  50389. previousPosition = null;
  50390. _this._offsetX = null;
  50391. _this._offsetY = null;
  50392. }
  50393. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  50394. if (!noPreventDefault) {
  50395. evt.preventDefault();
  50396. }
  50397. if (!previousPosition) {
  50398. return;
  50399. }
  50400. var index = _this._pointerPressed.indexOf(evt.pointerId);
  50401. if (index != 0) {
  50402. return;
  50403. }
  50404. _this._offsetX = evt.clientX - previousPosition.x;
  50405. _this._offsetY = -(evt.clientY - previousPosition.y);
  50406. }
  50407. };
  50408. }
  50409. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  50410. element.addEventListener("blur", this._onLostFocus);
  50411. };
  50412. FreeCameraTouchInput.prototype.detachControl = function (element) {
  50413. if (this._pointerInput && element) {
  50414. this.camera.getScene().onPointerObservable.remove(this._observer);
  50415. this._observer = null;
  50416. element.removeEventListener("blur", this._onLostFocus);
  50417. this._onLostFocus = null;
  50418. this._pointerPressed = [];
  50419. this._offsetX = null;
  50420. this._offsetY = null;
  50421. this._pointerCount = 0;
  50422. }
  50423. };
  50424. FreeCameraTouchInput.prototype.checkInputs = function () {
  50425. if (this._offsetX) {
  50426. var camera = this.camera;
  50427. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  50428. if (this._pointerPressed.length > 1) {
  50429. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  50430. }
  50431. else {
  50432. var speed = camera._computeLocalCameraSpeed();
  50433. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  50434. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  50435. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  50436. }
  50437. }
  50438. };
  50439. FreeCameraTouchInput.prototype.getClassName = function () {
  50440. return "FreeCameraTouchInput";
  50441. };
  50442. FreeCameraTouchInput.prototype.getSimpleName = function () {
  50443. return "touch";
  50444. };
  50445. __decorate([
  50446. BABYLON.serialize()
  50447. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  50448. __decorate([
  50449. BABYLON.serialize()
  50450. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  50451. return FreeCameraTouchInput;
  50452. }());
  50453. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  50454. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  50455. })(BABYLON || (BABYLON = {}));
  50456. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  50457. /// <reference path="babylon.freeCamera.ts" />
  50458. var BABYLON;
  50459. (function (BABYLON) {
  50460. // We're mainly based on the logic defined into the FreeCamera code
  50461. var TouchCamera = (function (_super) {
  50462. __extends(TouchCamera, _super);
  50463. //-- end properties for backward compatibility for inputs
  50464. function TouchCamera(name, position, scene) {
  50465. var _this = _super.call(this, name, position, scene) || this;
  50466. _this.inputs.addTouch();
  50467. _this._setupInputs();
  50468. return _this;
  50469. }
  50470. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  50471. //-- Begin properties for backward compatibility for inputs
  50472. get: function () {
  50473. var touch = this.inputs.attached["touch"];
  50474. if (touch)
  50475. return touch.touchAngularSensibility;
  50476. },
  50477. set: function (value) {
  50478. var touch = this.inputs.attached["touch"];
  50479. if (touch)
  50480. touch.touchAngularSensibility = value;
  50481. },
  50482. enumerable: true,
  50483. configurable: true
  50484. });
  50485. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  50486. get: function () {
  50487. var touch = this.inputs.attached["touch"];
  50488. if (touch)
  50489. return touch.touchMoveSensibility;
  50490. },
  50491. set: function (value) {
  50492. var touch = this.inputs.attached["touch"];
  50493. if (touch)
  50494. touch.touchMoveSensibility = value;
  50495. },
  50496. enumerable: true,
  50497. configurable: true
  50498. });
  50499. TouchCamera.prototype.getClassName = function () {
  50500. return "TouchCamera";
  50501. };
  50502. TouchCamera.prototype._setupInputs = function () {
  50503. var mouse = this.inputs.attached["mouse"];
  50504. if (mouse) {
  50505. mouse.touchEnabled = false;
  50506. }
  50507. };
  50508. return TouchCamera;
  50509. }(BABYLON.FreeCamera));
  50510. BABYLON.TouchCamera = TouchCamera;
  50511. })(BABYLON || (BABYLON = {}));
  50512. //# sourceMappingURL=babylon.touchCamera.js.map
  50513. var BABYLON;
  50514. (function (BABYLON) {
  50515. var ProceduralTexture = (function (_super) {
  50516. __extends(ProceduralTexture, _super);
  50517. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  50518. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50519. if (isCube === void 0) { isCube = false; }
  50520. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  50521. _this.isCube = isCube;
  50522. _this.isEnabled = true;
  50523. _this._currentRefreshId = -1;
  50524. _this._refreshRate = 1;
  50525. _this._vertexBuffers = {};
  50526. _this._uniforms = new Array();
  50527. _this._samplers = new Array();
  50528. _this._textures = new Array();
  50529. _this._floats = new Array();
  50530. _this._floatsArrays = {};
  50531. _this._colors3 = new Array();
  50532. _this._colors4 = new Array();
  50533. _this._vectors2 = new Array();
  50534. _this._vectors3 = new Array();
  50535. _this._matrices = new Array();
  50536. _this._fallbackTextureUsed = false;
  50537. scene._proceduralTextures.push(_this);
  50538. _this.name = name;
  50539. _this.isRenderTarget = true;
  50540. _this._size = size;
  50541. _this._generateMipMaps = generateMipMaps;
  50542. _this.setFragment(fragment);
  50543. _this._fallbackTexture = fallbackTexture;
  50544. var engine = scene.getEngine();
  50545. if (isCube) {
  50546. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  50547. _this.setFloat("face", 0);
  50548. }
  50549. else {
  50550. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  50551. }
  50552. // VBO
  50553. var vertices = [];
  50554. vertices.push(1, 1);
  50555. vertices.push(-1, 1);
  50556. vertices.push(-1, -1);
  50557. vertices.push(1, -1);
  50558. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  50559. _this._createIndexBuffer();
  50560. return _this;
  50561. }
  50562. ProceduralTexture.prototype._createIndexBuffer = function () {
  50563. var engine = this.getScene().getEngine();
  50564. // Indices
  50565. var indices = [];
  50566. indices.push(0);
  50567. indices.push(1);
  50568. indices.push(2);
  50569. indices.push(0);
  50570. indices.push(2);
  50571. indices.push(3);
  50572. this._indexBuffer = engine.createIndexBuffer(indices);
  50573. };
  50574. ProceduralTexture.prototype._rebuild = function () {
  50575. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  50576. this._createIndexBuffer();
  50577. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  50578. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  50579. }
  50580. };
  50581. ProceduralTexture.prototype.reset = function () {
  50582. if (this._effect === undefined) {
  50583. return;
  50584. }
  50585. var engine = this.getScene().getEngine();
  50586. engine._releaseEffect(this._effect);
  50587. };
  50588. ProceduralTexture.prototype.isReady = function () {
  50589. var _this = this;
  50590. var engine = this.getScene().getEngine();
  50591. var shaders;
  50592. if (!this._fragment) {
  50593. return false;
  50594. }
  50595. if (this._fallbackTextureUsed) {
  50596. return true;
  50597. }
  50598. if (this._fragment.fragmentElement !== undefined) {
  50599. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  50600. }
  50601. else {
  50602. shaders = { vertex: "procedural", fragment: this._fragment };
  50603. }
  50604. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  50605. _this.releaseInternalTexture();
  50606. if (_this._fallbackTexture) {
  50607. _this._texture = _this._fallbackTexture._texture;
  50608. _this._texture.incrementReferences();
  50609. }
  50610. _this._fallbackTextureUsed = true;
  50611. });
  50612. return this._effect.isReady();
  50613. };
  50614. ProceduralTexture.prototype.resetRefreshCounter = function () {
  50615. this._currentRefreshId = -1;
  50616. };
  50617. ProceduralTexture.prototype.setFragment = function (fragment) {
  50618. this._fragment = fragment;
  50619. };
  50620. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  50621. get: function () {
  50622. return this._refreshRate;
  50623. },
  50624. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  50625. set: function (value) {
  50626. this._refreshRate = value;
  50627. this.resetRefreshCounter();
  50628. },
  50629. enumerable: true,
  50630. configurable: true
  50631. });
  50632. ProceduralTexture.prototype._shouldRender = function () {
  50633. if (!this.isEnabled || !this.isReady() || !this._texture) {
  50634. return false;
  50635. }
  50636. if (this._fallbackTextureUsed) {
  50637. return false;
  50638. }
  50639. if (this._currentRefreshId === -1) {
  50640. this._currentRefreshId = 1;
  50641. return true;
  50642. }
  50643. if (this.refreshRate === this._currentRefreshId) {
  50644. this._currentRefreshId = 1;
  50645. return true;
  50646. }
  50647. this._currentRefreshId++;
  50648. return false;
  50649. };
  50650. ProceduralTexture.prototype.getRenderSize = function () {
  50651. return this._size;
  50652. };
  50653. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  50654. if (this._fallbackTextureUsed) {
  50655. return;
  50656. }
  50657. this.releaseInternalTexture();
  50658. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  50659. };
  50660. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  50661. if (this._uniforms.indexOf(uniformName) === -1) {
  50662. this._uniforms.push(uniformName);
  50663. }
  50664. };
  50665. ProceduralTexture.prototype.setTexture = function (name, texture) {
  50666. if (this._samplers.indexOf(name) === -1) {
  50667. this._samplers.push(name);
  50668. }
  50669. this._textures[name] = texture;
  50670. return this;
  50671. };
  50672. ProceduralTexture.prototype.setFloat = function (name, value) {
  50673. this._checkUniform(name);
  50674. this._floats[name] = value;
  50675. return this;
  50676. };
  50677. ProceduralTexture.prototype.setFloats = function (name, value) {
  50678. this._checkUniform(name);
  50679. this._floatsArrays[name] = value;
  50680. return this;
  50681. };
  50682. ProceduralTexture.prototype.setColor3 = function (name, value) {
  50683. this._checkUniform(name);
  50684. this._colors3[name] = value;
  50685. return this;
  50686. };
  50687. ProceduralTexture.prototype.setColor4 = function (name, value) {
  50688. this._checkUniform(name);
  50689. this._colors4[name] = value;
  50690. return this;
  50691. };
  50692. ProceduralTexture.prototype.setVector2 = function (name, value) {
  50693. this._checkUniform(name);
  50694. this._vectors2[name] = value;
  50695. return this;
  50696. };
  50697. ProceduralTexture.prototype.setVector3 = function (name, value) {
  50698. this._checkUniform(name);
  50699. this._vectors3[name] = value;
  50700. return this;
  50701. };
  50702. ProceduralTexture.prototype.setMatrix = function (name, value) {
  50703. this._checkUniform(name);
  50704. this._matrices[name] = value;
  50705. return this;
  50706. };
  50707. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  50708. var scene = this.getScene();
  50709. var engine = scene.getEngine();
  50710. // Render
  50711. engine.enableEffect(this._effect);
  50712. engine.setState(false);
  50713. // Texture
  50714. for (var name in this._textures) {
  50715. this._effect.setTexture(name, this._textures[name]);
  50716. }
  50717. // Float
  50718. for (name in this._floats) {
  50719. this._effect.setFloat(name, this._floats[name]);
  50720. }
  50721. // Floats
  50722. for (name in this._floatsArrays) {
  50723. this._effect.setArray(name, this._floatsArrays[name]);
  50724. }
  50725. // Color3
  50726. for (name in this._colors3) {
  50727. this._effect.setColor3(name, this._colors3[name]);
  50728. }
  50729. // Color4
  50730. for (name in this._colors4) {
  50731. var color = this._colors4[name];
  50732. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  50733. }
  50734. // Vector2
  50735. for (name in this._vectors2) {
  50736. this._effect.setVector2(name, this._vectors2[name]);
  50737. }
  50738. // Vector3
  50739. for (name in this._vectors3) {
  50740. this._effect.setVector3(name, this._vectors3[name]);
  50741. }
  50742. // Matrix
  50743. for (name in this._matrices) {
  50744. this._effect.setMatrix(name, this._matrices[name]);
  50745. }
  50746. if (this.isCube) {
  50747. for (var face = 0; face < 6; face++) {
  50748. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  50749. // VBOs
  50750. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  50751. this._effect.setFloat("face", face);
  50752. // Clear
  50753. engine.clear(scene.clearColor, true, true, true);
  50754. // Draw order
  50755. engine.draw(true, 0, 6);
  50756. // Mipmaps
  50757. if (face === 5) {
  50758. engine.generateMipMapsForCubemap(this._texture);
  50759. }
  50760. }
  50761. }
  50762. else {
  50763. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  50764. // VBOs
  50765. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  50766. // Clear
  50767. engine.clear(scene.clearColor, true, true, true);
  50768. // Draw order
  50769. engine.draw(true, 0, 6);
  50770. }
  50771. // Unbind
  50772. engine.unBindFramebuffer(this._texture, this.isCube);
  50773. if (this.onGenerated) {
  50774. this.onGenerated();
  50775. }
  50776. };
  50777. ProceduralTexture.prototype.clone = function () {
  50778. var textureSize = this.getSize();
  50779. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  50780. // Base texture
  50781. newTexture.hasAlpha = this.hasAlpha;
  50782. newTexture.level = this.level;
  50783. // RenderTarget Texture
  50784. newTexture.coordinatesMode = this.coordinatesMode;
  50785. return newTexture;
  50786. };
  50787. ProceduralTexture.prototype.dispose = function () {
  50788. var index = this.getScene()._proceduralTextures.indexOf(this);
  50789. if (index >= 0) {
  50790. this.getScene()._proceduralTextures.splice(index, 1);
  50791. }
  50792. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  50793. if (vertexBuffer) {
  50794. vertexBuffer.dispose();
  50795. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  50796. }
  50797. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  50798. this._indexBuffer = null;
  50799. }
  50800. _super.prototype.dispose.call(this);
  50801. };
  50802. return ProceduralTexture;
  50803. }(BABYLON.Texture));
  50804. BABYLON.ProceduralTexture = ProceduralTexture;
  50805. })(BABYLON || (BABYLON = {}));
  50806. //# sourceMappingURL=babylon.proceduralTexture.js.map
  50807. /// <reference path="babylon.proceduralTexture.ts" />
  50808. var BABYLON;
  50809. (function (BABYLON) {
  50810. var CustomProceduralTexture = (function (_super) {
  50811. __extends(CustomProceduralTexture, _super);
  50812. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  50813. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  50814. _this._animate = true;
  50815. _this._time = 0;
  50816. _this._texturePath = texturePath;
  50817. //Try to load json
  50818. _this.loadJson(texturePath);
  50819. _this.refreshRate = 1;
  50820. return _this;
  50821. }
  50822. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  50823. var _this = this;
  50824. var that = this;
  50825. function noConfigFile() {
  50826. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  50827. try {
  50828. that.setFragment(that._texturePath);
  50829. }
  50830. catch (ex) {
  50831. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  50832. }
  50833. }
  50834. var configFileUrl = jsonUrl + "/config.json";
  50835. var xhr = new XMLHttpRequest();
  50836. xhr.open("GET", configFileUrl, true);
  50837. xhr.addEventListener("load", function () {
  50838. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  50839. try {
  50840. _this._config = JSON.parse(xhr.response);
  50841. _this.updateShaderUniforms();
  50842. _this.updateTextures();
  50843. _this.setFragment(_this._texturePath + "/custom");
  50844. _this._animate = _this._config.animate;
  50845. _this.refreshRate = _this._config.refreshrate;
  50846. }
  50847. catch (ex) {
  50848. noConfigFile();
  50849. }
  50850. }
  50851. else {
  50852. noConfigFile();
  50853. }
  50854. }, false);
  50855. xhr.addEventListener("error", function () {
  50856. noConfigFile();
  50857. }, false);
  50858. try {
  50859. xhr.send();
  50860. }
  50861. catch (ex) {
  50862. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  50863. }
  50864. };
  50865. CustomProceduralTexture.prototype.isReady = function () {
  50866. if (!_super.prototype.isReady.call(this)) {
  50867. return false;
  50868. }
  50869. for (var name in this._textures) {
  50870. var texture = this._textures[name];
  50871. if (!texture.isReady()) {
  50872. return false;
  50873. }
  50874. }
  50875. return true;
  50876. };
  50877. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  50878. if (this._animate) {
  50879. this._time += this.getScene().getAnimationRatio() * 0.03;
  50880. this.updateShaderUniforms();
  50881. }
  50882. _super.prototype.render.call(this, useCameraPostProcess);
  50883. };
  50884. CustomProceduralTexture.prototype.updateTextures = function () {
  50885. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  50886. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  50887. }
  50888. };
  50889. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  50890. if (this._config) {
  50891. for (var j = 0; j < this._config.uniforms.length; j++) {
  50892. var uniform = this._config.uniforms[j];
  50893. switch (uniform.type) {
  50894. case "float":
  50895. this.setFloat(uniform.name, uniform.value);
  50896. break;
  50897. case "color3":
  50898. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  50899. break;
  50900. case "color4":
  50901. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  50902. break;
  50903. case "vector2":
  50904. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  50905. break;
  50906. case "vector3":
  50907. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  50908. break;
  50909. }
  50910. }
  50911. }
  50912. this.setFloat("time", this._time);
  50913. };
  50914. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  50915. get: function () {
  50916. return this._animate;
  50917. },
  50918. set: function (value) {
  50919. this._animate = value;
  50920. },
  50921. enumerable: true,
  50922. configurable: true
  50923. });
  50924. return CustomProceduralTexture;
  50925. }(BABYLON.ProceduralTexture));
  50926. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  50927. })(BABYLON || (BABYLON = {}));
  50928. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  50929. var BABYLON;
  50930. (function (BABYLON) {
  50931. var FreeCameraGamepadInput = (function () {
  50932. function FreeCameraGamepadInput() {
  50933. this.gamepadAngularSensibility = 200;
  50934. this.gamepadMoveSensibility = 40;
  50935. // private members
  50936. this._cameraTransform = BABYLON.Matrix.Identity();
  50937. this._deltaTransform = BABYLON.Vector3.Zero();
  50938. this._vector3 = BABYLON.Vector3.Zero();
  50939. this._vector2 = BABYLON.Vector2.Zero();
  50940. }
  50941. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  50942. var _this = this;
  50943. var manager = this.camera.getScene().gamepadManager;
  50944. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  50945. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  50946. // prioritize XBOX gamepads.
  50947. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  50948. _this.gamepad = gamepad;
  50949. }
  50950. }
  50951. });
  50952. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  50953. if (_this.gamepad === gamepad) {
  50954. _this.gamepad = null;
  50955. }
  50956. });
  50957. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  50958. };
  50959. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  50960. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  50961. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  50962. this.gamepad = null;
  50963. };
  50964. FreeCameraGamepadInput.prototype.checkInputs = function () {
  50965. if (this.gamepad && this.gamepad.leftStick) {
  50966. var camera = this.camera;
  50967. var LSValues = this.gamepad.leftStick;
  50968. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  50969. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  50970. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  50971. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  50972. var RSValues = this.gamepad.rightStick;
  50973. if (RSValues) {
  50974. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  50975. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  50976. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  50977. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  50978. }
  50979. else {
  50980. RSValues = { x: 0, y: 0 };
  50981. }
  50982. if (!camera.rotationQuaternion) {
  50983. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  50984. }
  50985. else {
  50986. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  50987. }
  50988. var speed = camera._computeLocalCameraSpeed() * 50.0;
  50989. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  50990. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  50991. camera.cameraDirection.addInPlace(this._deltaTransform);
  50992. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  50993. camera.cameraRotation.addInPlace(this._vector2);
  50994. }
  50995. };
  50996. FreeCameraGamepadInput.prototype.getClassName = function () {
  50997. return "FreeCameraGamepadInput";
  50998. };
  50999. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  51000. return "gamepad";
  51001. };
  51002. __decorate([
  51003. BABYLON.serialize()
  51004. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  51005. __decorate([
  51006. BABYLON.serialize()
  51007. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  51008. return FreeCameraGamepadInput;
  51009. }());
  51010. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  51011. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  51012. })(BABYLON || (BABYLON = {}));
  51013. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  51014. var BABYLON;
  51015. (function (BABYLON) {
  51016. var ArcRotateCameraGamepadInput = (function () {
  51017. function ArcRotateCameraGamepadInput() {
  51018. this.gamepadRotationSensibility = 80;
  51019. this.gamepadMoveSensibility = 40;
  51020. }
  51021. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  51022. var _this = this;
  51023. var manager = this.camera.getScene().gamepadManager;
  51024. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  51025. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  51026. // prioritize XBOX gamepads.
  51027. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  51028. _this.gamepad = gamepad;
  51029. }
  51030. }
  51031. });
  51032. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  51033. if (_this.gamepad === gamepad) {
  51034. _this.gamepad = null;
  51035. }
  51036. });
  51037. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  51038. };
  51039. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  51040. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  51041. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  51042. this.gamepad = null;
  51043. };
  51044. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  51045. if (this.gamepad) {
  51046. var camera = this.camera;
  51047. var RSValues = this.gamepad.rightStick;
  51048. if (RSValues) {
  51049. if (RSValues.x != 0) {
  51050. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  51051. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  51052. camera.inertialAlphaOffset += normalizedRX;
  51053. }
  51054. }
  51055. if (RSValues.y != 0) {
  51056. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  51057. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  51058. camera.inertialBetaOffset += normalizedRY;
  51059. }
  51060. }
  51061. }
  51062. var LSValues = this.gamepad.leftStick;
  51063. if (LSValues && LSValues.y != 0) {
  51064. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  51065. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  51066. this.camera.inertialRadiusOffset -= normalizedLY;
  51067. }
  51068. }
  51069. }
  51070. };
  51071. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  51072. return "ArcRotateCameraGamepadInput";
  51073. };
  51074. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  51075. return "gamepad";
  51076. };
  51077. __decorate([
  51078. BABYLON.serialize()
  51079. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  51080. __decorate([
  51081. BABYLON.serialize()
  51082. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  51083. return ArcRotateCameraGamepadInput;
  51084. }());
  51085. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  51086. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  51087. })(BABYLON || (BABYLON = {}));
  51088. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  51089. var BABYLON;
  51090. (function (BABYLON) {
  51091. var GamepadManager = (function () {
  51092. function GamepadManager() {
  51093. var _this = this;
  51094. this._babylonGamepads = [];
  51095. this._oneGamepadConnected = false;
  51096. this._isMonitoring = false;
  51097. this._gamepadEventSupported = 'GamepadEvent' in window;
  51098. this._gamepadSupport = (navigator.getGamepads ||
  51099. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  51100. this.onGamepadConnectedObservable = new BABYLON.Observable();
  51101. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  51102. this._onGamepadConnectedEvent = function (evt) {
  51103. var gamepad = evt.gamepad;
  51104. // Protection code for Chrome which has a very buggy gamepad implementation...
  51105. // And raises a connected event on disconnection for instance
  51106. if (gamepad.index in _this._babylonGamepads) {
  51107. return;
  51108. }
  51109. var newGamepad = _this._addNewGamepad(gamepad);
  51110. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  51111. _this._startMonitoringGamepads();
  51112. };
  51113. this._onGamepadDisconnectedEvent = function (evt) {
  51114. var gamepad = evt.gamepad;
  51115. // Remove the gamepad from the list of gamepads to monitor.
  51116. for (var i in _this._babylonGamepads) {
  51117. if (_this._babylonGamepads[i].index === gamepad.index) {
  51118. var gamepadToRemove = _this._babylonGamepads[i];
  51119. _this._babylonGamepads[i] = null;
  51120. _this.onGamepadDisconnectedObservable.notifyObservers(gamepadToRemove);
  51121. gamepadToRemove.dispose();
  51122. break;
  51123. }
  51124. }
  51125. };
  51126. if (this._gamepadSupport) {
  51127. //first add already-connected gamepads
  51128. this._updateGamepadObjects();
  51129. if (this._babylonGamepads.length) {
  51130. this._startMonitoringGamepads();
  51131. }
  51132. // Checking if the gamepad connected event is supported (like in Firefox)
  51133. if (this._gamepadEventSupported) {
  51134. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  51135. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  51136. }
  51137. else {
  51138. this._startMonitoringGamepads();
  51139. }
  51140. }
  51141. }
  51142. GamepadManager.prototype.getGamepadByType = function (type) {
  51143. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  51144. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  51145. var gamepad = _a[_i];
  51146. if (gamepad && gamepad.type === type) {
  51147. return gamepad;
  51148. }
  51149. }
  51150. return null;
  51151. };
  51152. GamepadManager.prototype.dispose = function () {
  51153. if (this._gamepadEventSupported) {
  51154. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  51155. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  51156. this._onGamepadConnectedEvent = null;
  51157. this._onGamepadDisconnectedEvent = null;
  51158. }
  51159. this._oneGamepadConnected = false;
  51160. this._stopMonitoringGamepads();
  51161. this._babylonGamepads = [];
  51162. };
  51163. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  51164. if (!this._oneGamepadConnected) {
  51165. this._oneGamepadConnected = true;
  51166. }
  51167. var newGamepad;
  51168. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  51169. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  51170. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  51171. }
  51172. else if (gamepad.pose) {
  51173. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  51174. }
  51175. else {
  51176. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  51177. }
  51178. this._babylonGamepads[newGamepad.index] = newGamepad;
  51179. return newGamepad;
  51180. };
  51181. GamepadManager.prototype._startMonitoringGamepads = function () {
  51182. if (!this._isMonitoring) {
  51183. this._isMonitoring = true;
  51184. this._checkGamepadsStatus();
  51185. }
  51186. };
  51187. GamepadManager.prototype._stopMonitoringGamepads = function () {
  51188. this._isMonitoring = false;
  51189. };
  51190. GamepadManager.prototype._checkGamepadsStatus = function () {
  51191. var _this = this;
  51192. // Hack to be compatible Chrome
  51193. this._updateGamepadObjects();
  51194. for (var i in this._babylonGamepads) {
  51195. var gamepad = this._babylonGamepads[i];
  51196. if (!gamepad) {
  51197. continue;
  51198. }
  51199. gamepad.update();
  51200. }
  51201. if (this._isMonitoring) {
  51202. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  51203. }
  51204. };
  51205. // This function is called only on Chrome, which does not properly support
  51206. // connection/disconnection events and forces you to recopy again the gamepad object
  51207. GamepadManager.prototype._updateGamepadObjects = function () {
  51208. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  51209. for (var i = 0; i < gamepads.length; i++) {
  51210. if (gamepads[i]) {
  51211. if (!this._babylonGamepads[gamepads[i].index]) {
  51212. var newGamepad = this._addNewGamepad(gamepads[i]);
  51213. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  51214. }
  51215. else {
  51216. // Forced to copy again this object for Chrome for unknown reason
  51217. this._babylonGamepads[i].browserGamepad = gamepads[i];
  51218. }
  51219. }
  51220. }
  51221. };
  51222. return GamepadManager;
  51223. }());
  51224. BABYLON.GamepadManager = GamepadManager;
  51225. })(BABYLON || (BABYLON = {}));
  51226. //# sourceMappingURL=babylon.gamepadManager.js.map
  51227. var BABYLON;
  51228. (function (BABYLON) {
  51229. var StickValues = (function () {
  51230. function StickValues(x, y) {
  51231. this.x = x;
  51232. this.y = y;
  51233. }
  51234. return StickValues;
  51235. }());
  51236. BABYLON.StickValues = StickValues;
  51237. var Gamepad = (function () {
  51238. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  51239. if (leftStickX === void 0) { leftStickX = 0; }
  51240. if (leftStickY === void 0) { leftStickY = 1; }
  51241. if (rightStickX === void 0) { rightStickX = 2; }
  51242. if (rightStickY === void 0) { rightStickY = 3; }
  51243. this.id = id;
  51244. this.index = index;
  51245. this.browserGamepad = browserGamepad;
  51246. this.type = Gamepad.GAMEPAD;
  51247. this._leftStickAxisX = leftStickX;
  51248. this._leftStickAxisY = leftStickY;
  51249. this._rightStickAxisX = rightStickX;
  51250. this._rightStickAxisY = rightStickY;
  51251. if (this.browserGamepad.axes.length >= 2) {
  51252. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  51253. }
  51254. if (this.browserGamepad.axes.length >= 4) {
  51255. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  51256. }
  51257. }
  51258. Gamepad.prototype.onleftstickchanged = function (callback) {
  51259. this._onleftstickchanged = callback;
  51260. };
  51261. Gamepad.prototype.onrightstickchanged = function (callback) {
  51262. this._onrightstickchanged = callback;
  51263. };
  51264. Object.defineProperty(Gamepad.prototype, "leftStick", {
  51265. get: function () {
  51266. return this._leftStick;
  51267. },
  51268. set: function (newValues) {
  51269. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  51270. this._onleftstickchanged(newValues);
  51271. }
  51272. this._leftStick = newValues;
  51273. },
  51274. enumerable: true,
  51275. configurable: true
  51276. });
  51277. Object.defineProperty(Gamepad.prototype, "rightStick", {
  51278. get: function () {
  51279. return this._rightStick;
  51280. },
  51281. set: function (newValues) {
  51282. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  51283. this._onrightstickchanged(newValues);
  51284. }
  51285. this._rightStick = newValues;
  51286. },
  51287. enumerable: true,
  51288. configurable: true
  51289. });
  51290. Gamepad.prototype.update = function () {
  51291. if (this._leftStick) {
  51292. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  51293. }
  51294. if (this._rightStick) {
  51295. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  51296. }
  51297. };
  51298. Gamepad.prototype.dispose = function () {
  51299. };
  51300. Gamepad.GAMEPAD = 0;
  51301. Gamepad.GENERIC = 1;
  51302. Gamepad.XBOX = 2;
  51303. Gamepad.POSE_ENABLED = 3;
  51304. return Gamepad;
  51305. }());
  51306. BABYLON.Gamepad = Gamepad;
  51307. var GenericPad = (function (_super) {
  51308. __extends(GenericPad, _super);
  51309. function GenericPad(id, index, browserGamepad) {
  51310. var _this = _super.call(this, id, index, browserGamepad) || this;
  51311. _this.type = Gamepad.GENERIC;
  51312. _this._buttons = new Array(browserGamepad.buttons.length);
  51313. return _this;
  51314. }
  51315. GenericPad.prototype.onbuttondown = function (callback) {
  51316. this._onbuttondown = callback;
  51317. };
  51318. GenericPad.prototype.onbuttonup = function (callback) {
  51319. this._onbuttonup = callback;
  51320. };
  51321. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  51322. if (newValue !== currentValue) {
  51323. if (this._onbuttondown && newValue === 1) {
  51324. this._onbuttondown(buttonIndex);
  51325. }
  51326. if (this._onbuttonup && newValue === 0) {
  51327. this._onbuttonup(buttonIndex);
  51328. }
  51329. }
  51330. return newValue;
  51331. };
  51332. GenericPad.prototype.update = function () {
  51333. _super.prototype.update.call(this);
  51334. for (var index = 0; index < this._buttons.length; index++) {
  51335. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  51336. }
  51337. };
  51338. return GenericPad;
  51339. }(Gamepad));
  51340. BABYLON.GenericPad = GenericPad;
  51341. })(BABYLON || (BABYLON = {}));
  51342. //# sourceMappingURL=babylon.gamepad.js.map
  51343. var BABYLON;
  51344. (function (BABYLON) {
  51345. var Xbox360Button;
  51346. (function (Xbox360Button) {
  51347. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  51348. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  51349. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  51350. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  51351. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  51352. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  51353. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  51354. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  51355. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  51356. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  51357. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  51358. var Xbox360Dpad;
  51359. (function (Xbox360Dpad) {
  51360. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  51361. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  51362. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  51363. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  51364. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  51365. var Xbox360Pad = (function (_super) {
  51366. __extends(Xbox360Pad, _super);
  51367. function Xbox360Pad(id, index, gamepad, xboxOne) {
  51368. if (xboxOne === void 0) { xboxOne = false; }
  51369. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  51370. _this._leftTrigger = 0;
  51371. _this._rightTrigger = 0;
  51372. _this._buttonA = 0;
  51373. _this._buttonB = 0;
  51374. _this._buttonX = 0;
  51375. _this._buttonY = 0;
  51376. _this._buttonBack = 0;
  51377. _this._buttonStart = 0;
  51378. _this._buttonLB = 0;
  51379. _this._buttonRB = 0;
  51380. _this._buttonLeftStick = 0;
  51381. _this._buttonRightStick = 0;
  51382. _this._dPadUp = 0;
  51383. _this._dPadDown = 0;
  51384. _this._dPadLeft = 0;
  51385. _this._dPadRight = 0;
  51386. _this._isXboxOnePad = false;
  51387. _this.type = BABYLON.Gamepad.XBOX;
  51388. _this._isXboxOnePad = xboxOne;
  51389. return _this;
  51390. }
  51391. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  51392. this._onlefttriggerchanged = callback;
  51393. };
  51394. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  51395. this._onrighttriggerchanged = callback;
  51396. };
  51397. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  51398. get: function () {
  51399. return this._leftTrigger;
  51400. },
  51401. set: function (newValue) {
  51402. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  51403. this._onlefttriggerchanged(newValue);
  51404. }
  51405. this._leftTrigger = newValue;
  51406. },
  51407. enumerable: true,
  51408. configurable: true
  51409. });
  51410. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  51411. get: function () {
  51412. return this._rightTrigger;
  51413. },
  51414. set: function (newValue) {
  51415. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  51416. this._onrighttriggerchanged(newValue);
  51417. }
  51418. this._rightTrigger = newValue;
  51419. },
  51420. enumerable: true,
  51421. configurable: true
  51422. });
  51423. Xbox360Pad.prototype.onbuttondown = function (callback) {
  51424. this._onbuttondown = callback;
  51425. };
  51426. Xbox360Pad.prototype.onbuttonup = function (callback) {
  51427. this._onbuttonup = callback;
  51428. };
  51429. Xbox360Pad.prototype.ondpaddown = function (callback) {
  51430. this._ondpaddown = callback;
  51431. };
  51432. Xbox360Pad.prototype.ondpadup = function (callback) {
  51433. this._ondpadup = callback;
  51434. };
  51435. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  51436. if (newValue !== currentValue) {
  51437. if (this._onbuttondown && newValue === 1) {
  51438. this._onbuttondown(buttonType);
  51439. }
  51440. if (this._onbuttonup && newValue === 0) {
  51441. this._onbuttonup(buttonType);
  51442. }
  51443. }
  51444. return newValue;
  51445. };
  51446. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  51447. if (newValue !== currentValue) {
  51448. if (this._ondpaddown && newValue === 1) {
  51449. this._ondpaddown(buttonType);
  51450. }
  51451. if (this._ondpadup && newValue === 0) {
  51452. this._ondpadup(buttonType);
  51453. }
  51454. }
  51455. return newValue;
  51456. };
  51457. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  51458. get: function () {
  51459. return this._buttonA;
  51460. },
  51461. set: function (value) {
  51462. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  51463. },
  51464. enumerable: true,
  51465. configurable: true
  51466. });
  51467. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  51468. get: function () {
  51469. return this._buttonB;
  51470. },
  51471. set: function (value) {
  51472. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  51473. },
  51474. enumerable: true,
  51475. configurable: true
  51476. });
  51477. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  51478. get: function () {
  51479. return this._buttonX;
  51480. },
  51481. set: function (value) {
  51482. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  51483. },
  51484. enumerable: true,
  51485. configurable: true
  51486. });
  51487. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  51488. get: function () {
  51489. return this._buttonY;
  51490. },
  51491. set: function (value) {
  51492. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  51493. },
  51494. enumerable: true,
  51495. configurable: true
  51496. });
  51497. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  51498. get: function () {
  51499. return this._buttonStart;
  51500. },
  51501. set: function (value) {
  51502. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  51503. },
  51504. enumerable: true,
  51505. configurable: true
  51506. });
  51507. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  51508. get: function () {
  51509. return this._buttonBack;
  51510. },
  51511. set: function (value) {
  51512. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  51513. },
  51514. enumerable: true,
  51515. configurable: true
  51516. });
  51517. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  51518. get: function () {
  51519. return this._buttonLB;
  51520. },
  51521. set: function (value) {
  51522. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  51523. },
  51524. enumerable: true,
  51525. configurable: true
  51526. });
  51527. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  51528. get: function () {
  51529. return this._buttonRB;
  51530. },
  51531. set: function (value) {
  51532. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  51533. },
  51534. enumerable: true,
  51535. configurable: true
  51536. });
  51537. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  51538. get: function () {
  51539. return this._buttonLeftStick;
  51540. },
  51541. set: function (value) {
  51542. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  51543. },
  51544. enumerable: true,
  51545. configurable: true
  51546. });
  51547. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  51548. get: function () {
  51549. return this._buttonRightStick;
  51550. },
  51551. set: function (value) {
  51552. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  51553. },
  51554. enumerable: true,
  51555. configurable: true
  51556. });
  51557. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  51558. get: function () {
  51559. return this._dPadUp;
  51560. },
  51561. set: function (value) {
  51562. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  51563. },
  51564. enumerable: true,
  51565. configurable: true
  51566. });
  51567. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  51568. get: function () {
  51569. return this._dPadDown;
  51570. },
  51571. set: function (value) {
  51572. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  51573. },
  51574. enumerable: true,
  51575. configurable: true
  51576. });
  51577. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  51578. get: function () {
  51579. return this._dPadLeft;
  51580. },
  51581. set: function (value) {
  51582. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  51583. },
  51584. enumerable: true,
  51585. configurable: true
  51586. });
  51587. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  51588. get: function () {
  51589. return this._dPadRight;
  51590. },
  51591. set: function (value) {
  51592. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  51593. },
  51594. enumerable: true,
  51595. configurable: true
  51596. });
  51597. Xbox360Pad.prototype.update = function () {
  51598. _super.prototype.update.call(this);
  51599. if (this._isXboxOnePad) {
  51600. this.buttonA = this.browserGamepad.buttons[0].value;
  51601. this.buttonB = this.browserGamepad.buttons[1].value;
  51602. this.buttonX = this.browserGamepad.buttons[2].value;
  51603. this.buttonY = this.browserGamepad.buttons[3].value;
  51604. this.buttonLB = this.browserGamepad.buttons[4].value;
  51605. this.buttonRB = this.browserGamepad.buttons[5].value;
  51606. this.leftTrigger = this.browserGamepad.axes[2];
  51607. this.rightTrigger = this.browserGamepad.axes[5];
  51608. this.buttonBack = this.browserGamepad.buttons[9].value;
  51609. this.buttonStart = this.browserGamepad.buttons[8].value;
  51610. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  51611. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  51612. this.dPadUp = this.browserGamepad.buttons[11].value;
  51613. this.dPadDown = this.browserGamepad.buttons[12].value;
  51614. this.dPadLeft = this.browserGamepad.buttons[13].value;
  51615. this.dPadRight = this.browserGamepad.buttons[14].value;
  51616. }
  51617. else {
  51618. this.buttonA = this.browserGamepad.buttons[0].value;
  51619. this.buttonB = this.browserGamepad.buttons[1].value;
  51620. this.buttonX = this.browserGamepad.buttons[2].value;
  51621. this.buttonY = this.browserGamepad.buttons[3].value;
  51622. this.buttonLB = this.browserGamepad.buttons[4].value;
  51623. this.buttonRB = this.browserGamepad.buttons[5].value;
  51624. this.leftTrigger = this.browserGamepad.buttons[6].value;
  51625. this.rightTrigger = this.browserGamepad.buttons[7].value;
  51626. this.buttonBack = this.browserGamepad.buttons[8].value;
  51627. this.buttonStart = this.browserGamepad.buttons[9].value;
  51628. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  51629. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  51630. this.dPadUp = this.browserGamepad.buttons[12].value;
  51631. this.dPadDown = this.browserGamepad.buttons[13].value;
  51632. this.dPadLeft = this.browserGamepad.buttons[14].value;
  51633. this.dPadRight = this.browserGamepad.buttons[15].value;
  51634. }
  51635. };
  51636. return Xbox360Pad;
  51637. }(BABYLON.Gamepad));
  51638. BABYLON.Xbox360Pad = Xbox360Pad;
  51639. })(BABYLON || (BABYLON = {}));
  51640. //# sourceMappingURL=babylon.xboxGamepad.js.map
  51641. var BABYLON;
  51642. (function (BABYLON) {
  51643. var PoseEnabledControllerType;
  51644. (function (PoseEnabledControllerType) {
  51645. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  51646. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  51647. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  51648. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  51649. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  51650. var PoseEnabledControllerHelper = (function () {
  51651. function PoseEnabledControllerHelper() {
  51652. }
  51653. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  51654. // Oculus Touch
  51655. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  51656. return new BABYLON.OculusTouchController(vrGamepad);
  51657. }
  51658. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  51659. return new BABYLON.ViveController(vrGamepad);
  51660. }
  51661. else {
  51662. return new BABYLON.GenericController(vrGamepad);
  51663. }
  51664. };
  51665. return PoseEnabledControllerHelper;
  51666. }());
  51667. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  51668. var PoseEnabledController = (function (_super) {
  51669. __extends(PoseEnabledController, _super);
  51670. function PoseEnabledController(vrGamepad) {
  51671. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  51672. _this.vrGamepad = vrGamepad;
  51673. _this.deviceScaleFactor = 1;
  51674. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  51675. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  51676. _this.controllerType = PoseEnabledControllerType.GENERIC;
  51677. _this.position = BABYLON.Vector3.Zero();
  51678. _this.rotationQuaternion = new BABYLON.Quaternion();
  51679. _this.devicePosition = BABYLON.Vector3.Zero();
  51680. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  51681. _this._calculatedPosition = BABYLON.Vector3.Zero();
  51682. _this._calculatedRotation = new BABYLON.Quaternion();
  51683. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  51684. return _this;
  51685. }
  51686. PoseEnabledController.prototype.update = function () {
  51687. _super.prototype.update.call(this);
  51688. var pose = this.vrGamepad.pose;
  51689. this.updateFromDevice(pose);
  51690. if (this._mesh) {
  51691. this._mesh.position.copyFrom(this._calculatedPosition);
  51692. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  51693. }
  51694. };
  51695. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  51696. if (poseData) {
  51697. this.rawPose = poseData;
  51698. if (poseData.position) {
  51699. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  51700. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  51701. this.devicePosition.z *= -1;
  51702. }
  51703. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  51704. this._calculatedPosition.addInPlace(this.position);
  51705. }
  51706. if (poseData.orientation) {
  51707. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  51708. if (this._mesh) {
  51709. if (this._mesh.getScene().useRightHandedSystem) {
  51710. this.deviceRotationQuaternion.z *= -1;
  51711. this.deviceRotationQuaternion.w *= -1;
  51712. }
  51713. else {
  51714. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  51715. }
  51716. }
  51717. // if the camera is set, rotate to the camera's rotation
  51718. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  51719. }
  51720. }
  51721. };
  51722. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  51723. if (this._mesh) {
  51724. this._mesh.parent = undefined;
  51725. }
  51726. this._mesh = mesh;
  51727. if (this._poseControlledCamera) {
  51728. this._mesh.parent = this._poseControlledCamera;
  51729. }
  51730. if (!this._mesh.rotationQuaternion) {
  51731. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  51732. }
  51733. };
  51734. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  51735. this._poseControlledCamera = camera;
  51736. if (this._mesh) {
  51737. this._mesh.parent = this._poseControlledCamera;
  51738. }
  51739. };
  51740. PoseEnabledController.prototype.dispose = function () {
  51741. if (this._mesh) {
  51742. this._mesh.dispose();
  51743. }
  51744. this._mesh = undefined;
  51745. _super.prototype.dispose.call(this);
  51746. };
  51747. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  51748. get: function () {
  51749. return this._mesh;
  51750. },
  51751. enumerable: true,
  51752. configurable: true
  51753. });
  51754. PoseEnabledController.prototype.getForwardRay = function (length) {
  51755. if (length === void 0) { length = 100; }
  51756. if (!this.mesh) {
  51757. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  51758. }
  51759. var m = this.mesh.getWorldMatrix();
  51760. var origin = m.getTranslation();
  51761. var forward = new BABYLON.Vector3(0, 0, -1);
  51762. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  51763. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  51764. return new BABYLON.Ray(origin, direction, length);
  51765. };
  51766. return PoseEnabledController;
  51767. }(BABYLON.Gamepad));
  51768. BABYLON.PoseEnabledController = PoseEnabledController;
  51769. })(BABYLON || (BABYLON = {}));
  51770. //# sourceMappingURL=babylon.poseEnabledController.js.map
  51771. var BABYLON;
  51772. (function (BABYLON) {
  51773. var WebVRController = (function (_super) {
  51774. __extends(WebVRController, _super);
  51775. function WebVRController(vrGamepad) {
  51776. var _this = _super.call(this, vrGamepad) || this;
  51777. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  51778. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  51779. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  51780. _this.onPadStateChangedObservable = new BABYLON.Observable();
  51781. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  51782. _this.pad = { x: 0, y: 0 };
  51783. // avoid GC, store state in a tmp object
  51784. _this._changes = {
  51785. pressChanged: false,
  51786. touchChanged: false,
  51787. valueChanged: false,
  51788. changed: false
  51789. };
  51790. _this._buttons = new Array(vrGamepad.buttons.length);
  51791. _this.hand = vrGamepad.hand;
  51792. return _this;
  51793. }
  51794. WebVRController.prototype.onButtonStateChange = function (callback) {
  51795. this._onButtonStateChange = callback;
  51796. };
  51797. WebVRController.prototype.update = function () {
  51798. _super.prototype.update.call(this);
  51799. for (var index = 0; index < this._buttons.length; index++) {
  51800. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  51801. }
  51802. ;
  51803. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  51804. this.pad.x = this.leftStick.x;
  51805. this.pad.y = this.leftStick.y;
  51806. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  51807. }
  51808. };
  51809. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  51810. if (!newState) {
  51811. newState = {
  51812. pressed: false,
  51813. touched: false,
  51814. value: 0
  51815. };
  51816. }
  51817. if (!currentState) {
  51818. this._buttons[buttonIndex] = {
  51819. pressed: newState.pressed,
  51820. touched: newState.touched,
  51821. value: newState.value
  51822. };
  51823. return;
  51824. }
  51825. this._checkChanges(newState, currentState);
  51826. if (this._changes.changed) {
  51827. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  51828. this.handleButtonChange(buttonIndex, newState, this._changes);
  51829. }
  51830. this._buttons[buttonIndex].pressed = newState.pressed;
  51831. this._buttons[buttonIndex].touched = newState.touched;
  51832. // oculus triggers are never 0, thou not touched.
  51833. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  51834. };
  51835. WebVRController.prototype._checkChanges = function (newState, currentState) {
  51836. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  51837. this._changes.touchChanged = newState.touched !== currentState.touched;
  51838. this._changes.valueChanged = newState.value !== currentState.value;
  51839. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  51840. return this._changes;
  51841. };
  51842. return WebVRController;
  51843. }(BABYLON.PoseEnabledController));
  51844. BABYLON.WebVRController = WebVRController;
  51845. })(BABYLON || (BABYLON = {}));
  51846. //# sourceMappingURL=babylon.webVRController.js.map
  51847. var BABYLON;
  51848. (function (BABYLON) {
  51849. var OculusTouchController = (function (_super) {
  51850. __extends(OculusTouchController, _super);
  51851. function OculusTouchController(vrGamepad) {
  51852. var _this = _super.call(this, vrGamepad) || this;
  51853. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  51854. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  51855. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  51856. return _this;
  51857. }
  51858. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  51859. var _this = this;
  51860. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  51861. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  51862. /*
  51863. Parent Mesh name: oculus_touch_left
  51864. - body
  51865. - trigger
  51866. - thumbstick
  51867. - grip
  51868. - button_y
  51869. - button_x
  51870. - button_enter
  51871. */
  51872. _this._defaultModel = newMeshes[1];
  51873. if (meshLoaded) {
  51874. meshLoaded(_this._defaultModel);
  51875. }
  51876. _this.attachToMesh(_this._defaultModel);
  51877. });
  51878. };
  51879. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  51880. // helper getters for left and right hand.
  51881. get: function () {
  51882. if (this.hand === 'right') {
  51883. return this.onMainButtonStateChangedObservable;
  51884. }
  51885. else {
  51886. throw new Error('No A button on left hand');
  51887. }
  51888. },
  51889. enumerable: true,
  51890. configurable: true
  51891. });
  51892. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  51893. get: function () {
  51894. if (this.hand === 'right') {
  51895. return this.onSecondaryButtonStateChangedObservable;
  51896. }
  51897. else {
  51898. throw new Error('No B button on left hand');
  51899. }
  51900. },
  51901. enumerable: true,
  51902. configurable: true
  51903. });
  51904. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  51905. get: function () {
  51906. if (this.hand === 'left') {
  51907. return this.onMainButtonStateChangedObservable;
  51908. }
  51909. else {
  51910. throw new Error('No X button on right hand');
  51911. }
  51912. },
  51913. enumerable: true,
  51914. configurable: true
  51915. });
  51916. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  51917. get: function () {
  51918. if (this.hand === 'left') {
  51919. return this.onSecondaryButtonStateChangedObservable;
  51920. }
  51921. else {
  51922. throw new Error('No Y button on right hand');
  51923. }
  51924. },
  51925. enumerable: true,
  51926. configurable: true
  51927. });
  51928. /*
  51929. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  51930. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  51931. 2) secondary trigger (same)
  51932. 3) A (right) X (left), touch, pressed = value
  51933. 4) B / Y
  51934. 5) thumb rest
  51935. */
  51936. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  51937. var notifyObject = state; //{ state: state, changes: changes };
  51938. var triggerDirection = this.hand === 'right' ? -1 : 1;
  51939. switch (buttonIdx) {
  51940. case 0:
  51941. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  51942. return;
  51943. case 1:// index trigger
  51944. if (this._defaultModel) {
  51945. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  51946. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  51947. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  51948. }
  51949. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  51950. return;
  51951. case 2:// secondary trigger
  51952. if (this._defaultModel) {
  51953. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  51954. }
  51955. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  51956. return;
  51957. case 3:
  51958. if (this._defaultModel) {
  51959. if (notifyObject.pressed) {
  51960. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  51961. }
  51962. else {
  51963. (this._defaultModel.getChildren()[1]).position.y = 0;
  51964. }
  51965. }
  51966. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  51967. return;
  51968. case 4:
  51969. if (this._defaultModel) {
  51970. if (notifyObject.pressed) {
  51971. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  51972. }
  51973. else {
  51974. (this._defaultModel.getChildren()[2]).position.y = 0;
  51975. }
  51976. }
  51977. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  51978. return;
  51979. case 5:
  51980. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  51981. return;
  51982. }
  51983. };
  51984. return OculusTouchController;
  51985. }(BABYLON.WebVRController));
  51986. BABYLON.OculusTouchController = OculusTouchController;
  51987. })(BABYLON || (BABYLON = {}));
  51988. //# sourceMappingURL=babylon.oculusTouchController.js.map
  51989. var BABYLON;
  51990. (function (BABYLON) {
  51991. var ViveController = (function (_super) {
  51992. __extends(ViveController, _super);
  51993. function ViveController(vrGamepad) {
  51994. var _this = _super.call(this, vrGamepad) || this;
  51995. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  51996. return _this;
  51997. }
  51998. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  51999. var _this = this;
  52000. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  52001. /*
  52002. Parent Mesh name: ViveWand
  52003. - body
  52004. - r_gripper
  52005. - l_gripper
  52006. - menu_button
  52007. - system_button
  52008. - trackpad
  52009. - trigger
  52010. - LED
  52011. */
  52012. _this._defaultModel = newMeshes[1];
  52013. if (meshLoaded) {
  52014. meshLoaded(_this._defaultModel);
  52015. }
  52016. _this.attachToMesh(_this._defaultModel);
  52017. });
  52018. };
  52019. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  52020. get: function () {
  52021. return this.onMainButtonStateChangedObservable;
  52022. },
  52023. enumerable: true,
  52024. configurable: true
  52025. });
  52026. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  52027. get: function () {
  52028. return this.onMainButtonStateChangedObservable;
  52029. },
  52030. enumerable: true,
  52031. configurable: true
  52032. });
  52033. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  52034. get: function () {
  52035. return this.onSecondaryButtonStateChangedObservable;
  52036. },
  52037. enumerable: true,
  52038. configurable: true
  52039. });
  52040. /**
  52041. * Vive mapping:
  52042. * 0: touchpad
  52043. * 1: trigger
  52044. * 2: left AND right buttons
  52045. * 3: menu button
  52046. */
  52047. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  52048. var notifyObject = state; //{ state: state, changes: changes };
  52049. switch (buttonIdx) {
  52050. case 0:
  52051. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  52052. return;
  52053. case 1:// index trigger
  52054. if (this._defaultModel) {
  52055. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  52056. }
  52057. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  52058. return;
  52059. case 2:// left AND right button
  52060. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  52061. return;
  52062. case 3:
  52063. if (this._defaultModel) {
  52064. if (notifyObject.pressed) {
  52065. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  52066. }
  52067. else {
  52068. (this._defaultModel.getChildren()[2]).position.y = 0;
  52069. }
  52070. }
  52071. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  52072. return;
  52073. }
  52074. };
  52075. return ViveController;
  52076. }(BABYLON.WebVRController));
  52077. BABYLON.ViveController = ViveController;
  52078. })(BABYLON || (BABYLON = {}));
  52079. //# sourceMappingURL=babylon.viveController.js.map
  52080. var BABYLON;
  52081. (function (BABYLON) {
  52082. var GenericController = (function (_super) {
  52083. __extends(GenericController, _super);
  52084. function GenericController(vrGamepad) {
  52085. return _super.call(this, vrGamepad) || this;
  52086. }
  52087. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  52088. var _this = this;
  52089. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "genericvrcontroller.babylon", scene, function (newMeshes) {
  52090. _this._defaultModel = newMeshes[1];
  52091. if (meshLoaded) {
  52092. meshLoaded(_this._defaultModel);
  52093. }
  52094. _this.attachToMesh(_this._defaultModel);
  52095. });
  52096. };
  52097. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  52098. console.log("Button id: " + buttonIdx + "state: ");
  52099. console.dir(state);
  52100. };
  52101. return GenericController;
  52102. }(BABYLON.WebVRController));
  52103. BABYLON.GenericController = GenericController;
  52104. })(BABYLON || (BABYLON = {}));
  52105. //# sourceMappingURL=babylon.genericController.js.map
  52106. /// <reference path="babylon.targetCamera.ts" />
  52107. var BABYLON;
  52108. (function (BABYLON) {
  52109. var FollowCamera = (function (_super) {
  52110. __extends(FollowCamera, _super);
  52111. function FollowCamera(name, position, scene, lockedTarget) {
  52112. var _this = _super.call(this, name, position, scene) || this;
  52113. _this.radius = 12;
  52114. _this.rotationOffset = 0;
  52115. _this.heightOffset = 4;
  52116. _this.cameraAcceleration = 0.05;
  52117. _this.maxCameraSpeed = 20;
  52118. _this.lockedTarget = lockedTarget;
  52119. return _this;
  52120. }
  52121. FollowCamera.prototype.getRadians = function (degrees) {
  52122. return degrees * Math.PI / 180;
  52123. };
  52124. FollowCamera.prototype.follow = function (cameraTarget) {
  52125. if (!cameraTarget)
  52126. return;
  52127. var yRotation;
  52128. if (cameraTarget.rotationQuaternion) {
  52129. var rotMatrix = new BABYLON.Matrix();
  52130. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  52131. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  52132. }
  52133. else {
  52134. yRotation = cameraTarget.rotation.y;
  52135. }
  52136. var radians = this.getRadians(this.rotationOffset) + yRotation;
  52137. var targetPosition = cameraTarget.getAbsolutePosition();
  52138. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  52139. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  52140. var dx = targetX - this.position.x;
  52141. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  52142. var dz = (targetZ) - this.position.z;
  52143. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  52144. var vy = dy * this.cameraAcceleration;
  52145. var vz = dz * this.cameraAcceleration * 2;
  52146. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  52147. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  52148. }
  52149. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  52150. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  52151. }
  52152. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  52153. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  52154. }
  52155. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  52156. this.setTarget(targetPosition);
  52157. };
  52158. FollowCamera.prototype._checkInputs = function () {
  52159. _super.prototype._checkInputs.call(this);
  52160. this.follow(this.lockedTarget);
  52161. };
  52162. FollowCamera.prototype.getClassName = function () {
  52163. return "FollowCamera";
  52164. };
  52165. __decorate([
  52166. BABYLON.serialize()
  52167. ], FollowCamera.prototype, "radius", void 0);
  52168. __decorate([
  52169. BABYLON.serialize()
  52170. ], FollowCamera.prototype, "rotationOffset", void 0);
  52171. __decorate([
  52172. BABYLON.serialize()
  52173. ], FollowCamera.prototype, "heightOffset", void 0);
  52174. __decorate([
  52175. BABYLON.serialize()
  52176. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  52177. __decorate([
  52178. BABYLON.serialize()
  52179. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  52180. __decorate([
  52181. BABYLON.serializeAsMeshReference("lockedTargetId")
  52182. ], FollowCamera.prototype, "lockedTarget", void 0);
  52183. return FollowCamera;
  52184. }(BABYLON.TargetCamera));
  52185. BABYLON.FollowCamera = FollowCamera;
  52186. var ArcFollowCamera = (function (_super) {
  52187. __extends(ArcFollowCamera, _super);
  52188. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  52189. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  52190. _this.alpha = alpha;
  52191. _this.beta = beta;
  52192. _this.radius = radius;
  52193. _this.target = target;
  52194. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  52195. _this.follow();
  52196. return _this;
  52197. }
  52198. ArcFollowCamera.prototype.follow = function () {
  52199. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  52200. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  52201. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  52202. var targetPosition = this.target.getAbsolutePosition();
  52203. this.position = targetPosition.add(this._cartesianCoordinates);
  52204. this.setTarget(targetPosition);
  52205. };
  52206. ArcFollowCamera.prototype._checkInputs = function () {
  52207. _super.prototype._checkInputs.call(this);
  52208. this.follow();
  52209. };
  52210. ArcFollowCamera.prototype.getClassName = function () {
  52211. return "ArcFollowCamera";
  52212. };
  52213. return ArcFollowCamera;
  52214. }(BABYLON.TargetCamera));
  52215. BABYLON.ArcFollowCamera = ArcFollowCamera;
  52216. })(BABYLON || (BABYLON = {}));
  52217. //# sourceMappingURL=babylon.followCamera.js.map
  52218. /// <reference path="babylon.touchCamera.ts" />
  52219. var BABYLON;
  52220. (function (BABYLON) {
  52221. // We're mainly based on the logic defined into the FreeCamera code
  52222. var UniversalCamera = (function (_super) {
  52223. __extends(UniversalCamera, _super);
  52224. //-- end properties for backward compatibility for inputs
  52225. function UniversalCamera(name, position, scene) {
  52226. var _this = _super.call(this, name, position, scene) || this;
  52227. _this.inputs.addGamepad();
  52228. return _this;
  52229. }
  52230. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  52231. //-- Begin properties for backward compatibility for inputs
  52232. get: function () {
  52233. var gamepad = this.inputs.attached["gamepad"];
  52234. if (gamepad)
  52235. return gamepad.gamepadAngularSensibility;
  52236. },
  52237. set: function (value) {
  52238. var gamepad = this.inputs.attached["gamepad"];
  52239. if (gamepad)
  52240. gamepad.gamepadAngularSensibility = value;
  52241. },
  52242. enumerable: true,
  52243. configurable: true
  52244. });
  52245. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  52246. get: function () {
  52247. var gamepad = this.inputs.attached["gamepad"];
  52248. if (gamepad)
  52249. return gamepad.gamepadMoveSensibility;
  52250. },
  52251. set: function (value) {
  52252. var gamepad = this.inputs.attached["gamepad"];
  52253. if (gamepad)
  52254. gamepad.gamepadMoveSensibility = value;
  52255. },
  52256. enumerable: true,
  52257. configurable: true
  52258. });
  52259. UniversalCamera.prototype.getClassName = function () {
  52260. return "UniversalCamera";
  52261. };
  52262. return UniversalCamera;
  52263. }(BABYLON.TouchCamera));
  52264. BABYLON.UniversalCamera = UniversalCamera;
  52265. })(BABYLON || (BABYLON = {}));
  52266. //# sourceMappingURL=babylon.universalCamera.js.map
  52267. /// <reference path="babylon.universalCamera.ts" />
  52268. var BABYLON;
  52269. (function (BABYLON) {
  52270. // We're mainly based on the logic defined into the FreeCamera code
  52271. var GamepadCamera = (function (_super) {
  52272. __extends(GamepadCamera, _super);
  52273. //-- end properties for backward compatibility for inputs
  52274. function GamepadCamera(name, position, scene) {
  52275. return _super.call(this, name, position, scene) || this;
  52276. }
  52277. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  52278. //-- Begin properties for backward compatibility for inputs
  52279. get: function () {
  52280. var gamepad = this.inputs.attached["gamepad"];
  52281. if (gamepad)
  52282. return gamepad.gamepadAngularSensibility;
  52283. },
  52284. set: function (value) {
  52285. var gamepad = this.inputs.attached["gamepad"];
  52286. if (gamepad)
  52287. gamepad.gamepadAngularSensibility = value;
  52288. },
  52289. enumerable: true,
  52290. configurable: true
  52291. });
  52292. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  52293. get: function () {
  52294. var gamepad = this.inputs.attached["gamepad"];
  52295. if (gamepad)
  52296. return gamepad.gamepadMoveSensibility;
  52297. },
  52298. set: function (value) {
  52299. var gamepad = this.inputs.attached["gamepad"];
  52300. if (gamepad)
  52301. gamepad.gamepadMoveSensibility = value;
  52302. },
  52303. enumerable: true,
  52304. configurable: true
  52305. });
  52306. GamepadCamera.prototype.getClassName = function () {
  52307. return "GamepadCamera";
  52308. };
  52309. return GamepadCamera;
  52310. }(BABYLON.UniversalCamera));
  52311. BABYLON.GamepadCamera = GamepadCamera;
  52312. })(BABYLON || (BABYLON = {}));
  52313. //# sourceMappingURL=babylon.gamepadCamera.js.map
  52314. var BABYLON;
  52315. (function (BABYLON) {
  52316. var PostProcessRenderPipelineManager = (function () {
  52317. function PostProcessRenderPipelineManager() {
  52318. this._renderPipelines = {};
  52319. }
  52320. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  52321. this._renderPipelines[renderPipeline._name] = renderPipeline;
  52322. };
  52323. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  52324. var renderPipeline = this._renderPipelines[renderPipelineName];
  52325. if (!renderPipeline) {
  52326. return;
  52327. }
  52328. renderPipeline._attachCameras(cameras, unique);
  52329. };
  52330. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  52331. var renderPipeline = this._renderPipelines[renderPipelineName];
  52332. if (!renderPipeline) {
  52333. return;
  52334. }
  52335. renderPipeline._detachCameras(cameras);
  52336. };
  52337. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  52338. var renderPipeline = this._renderPipelines[renderPipelineName];
  52339. if (!renderPipeline) {
  52340. return;
  52341. }
  52342. renderPipeline._enableEffect(renderEffectName, cameras);
  52343. };
  52344. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  52345. var renderPipeline = this._renderPipelines[renderPipelineName];
  52346. if (!renderPipeline) {
  52347. return;
  52348. }
  52349. renderPipeline._disableEffect(renderEffectName, cameras);
  52350. };
  52351. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  52352. var renderPipeline = this._renderPipelines[renderPipelineName];
  52353. if (!renderPipeline) {
  52354. return;
  52355. }
  52356. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  52357. };
  52358. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  52359. var renderPipeline = this._renderPipelines[renderPipelineName];
  52360. if (!renderPipeline) {
  52361. return;
  52362. }
  52363. renderPipeline._disableDisplayOnlyPass(cameras);
  52364. };
  52365. PostProcessRenderPipelineManager.prototype.update = function () {
  52366. for (var renderPipelineName in this._renderPipelines) {
  52367. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  52368. var pipeline = this._renderPipelines[renderPipelineName];
  52369. if (!pipeline.isSupported) {
  52370. pipeline.dispose();
  52371. delete this._renderPipelines[renderPipelineName];
  52372. }
  52373. else {
  52374. pipeline._update();
  52375. }
  52376. }
  52377. }
  52378. };
  52379. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  52380. for (var renderPipelineName in this._renderPipelines) {
  52381. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  52382. var pipeline = this._renderPipelines[renderPipelineName];
  52383. pipeline._rebuild();
  52384. }
  52385. }
  52386. };
  52387. PostProcessRenderPipelineManager.prototype.dispose = function () {
  52388. for (var renderPipelineName in this._renderPipelines) {
  52389. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  52390. var pipeline = this._renderPipelines[renderPipelineName];
  52391. pipeline.dispose();
  52392. }
  52393. }
  52394. };
  52395. return PostProcessRenderPipelineManager;
  52396. }());
  52397. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  52398. })(BABYLON || (BABYLON = {}));
  52399. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  52400. var BABYLON;
  52401. (function (BABYLON) {
  52402. var PostProcessRenderPass = (function () {
  52403. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  52404. this._enabled = true;
  52405. this._refCount = 0;
  52406. this._name = name;
  52407. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  52408. this.setRenderList(renderList);
  52409. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  52410. this._renderTexture.onAfterRenderObservable.add(afterRender);
  52411. this._scene = scene;
  52412. this._renderList = renderList;
  52413. }
  52414. // private
  52415. PostProcessRenderPass.prototype._incRefCount = function () {
  52416. if (this._refCount === 0) {
  52417. this._scene.customRenderTargets.push(this._renderTexture);
  52418. }
  52419. return ++this._refCount;
  52420. };
  52421. PostProcessRenderPass.prototype._decRefCount = function () {
  52422. this._refCount--;
  52423. if (this._refCount <= 0) {
  52424. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  52425. }
  52426. return this._refCount;
  52427. };
  52428. PostProcessRenderPass.prototype._update = function () {
  52429. this.setRenderList(this._renderList);
  52430. };
  52431. // public
  52432. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  52433. this._renderTexture.renderList = renderList;
  52434. };
  52435. PostProcessRenderPass.prototype.getRenderTexture = function () {
  52436. return this._renderTexture;
  52437. };
  52438. return PostProcessRenderPass;
  52439. }());
  52440. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  52441. })(BABYLON || (BABYLON = {}));
  52442. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  52443. var BABYLON;
  52444. (function (BABYLON) {
  52445. var PostProcessRenderEffect = (function () {
  52446. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  52447. this._engine = engine;
  52448. this._name = name;
  52449. this._singleInstance = singleInstance || true;
  52450. this._getPostProcess = getPostProcess;
  52451. this._cameras = [];
  52452. this._indicesForCamera = [];
  52453. this._postProcesses = {};
  52454. this._renderPasses = {};
  52455. this._renderEffectAsPasses = {};
  52456. }
  52457. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  52458. get: function () {
  52459. for (var index in this._postProcesses) {
  52460. if (!this._postProcesses[index].isSupported) {
  52461. return false;
  52462. }
  52463. }
  52464. return true;
  52465. },
  52466. enumerable: true,
  52467. configurable: true
  52468. });
  52469. PostProcessRenderEffect.prototype._update = function () {
  52470. for (var renderPassName in this._renderPasses) {
  52471. this._renderPasses[renderPassName]._update();
  52472. }
  52473. };
  52474. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  52475. this._renderPasses[renderPass._name] = renderPass;
  52476. this._linkParameters();
  52477. };
  52478. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  52479. delete this._renderPasses[renderPass._name];
  52480. this._linkParameters();
  52481. };
  52482. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  52483. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  52484. this._linkParameters();
  52485. };
  52486. PostProcessRenderEffect.prototype.getPass = function (passName) {
  52487. for (var renderPassName in this._renderPasses) {
  52488. if (renderPassName === passName) {
  52489. return this._renderPasses[passName];
  52490. }
  52491. }
  52492. };
  52493. PostProcessRenderEffect.prototype.emptyPasses = function () {
  52494. this._renderPasses = {};
  52495. this._linkParameters();
  52496. };
  52497. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  52498. var cameraKey;
  52499. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  52500. for (var i = 0; i < _cam.length; i++) {
  52501. var camera = _cam[i];
  52502. var cameraName = camera.name;
  52503. if (this._singleInstance) {
  52504. cameraKey = 0;
  52505. }
  52506. else {
  52507. cameraKey = cameraName;
  52508. }
  52509. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  52510. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  52511. if (!this._indicesForCamera[cameraName]) {
  52512. this._indicesForCamera[cameraName] = [];
  52513. }
  52514. this._indicesForCamera[cameraName].push(index);
  52515. if (this._cameras.indexOf(camera) === -1) {
  52516. this._cameras[cameraName] = camera;
  52517. }
  52518. for (var passName in this._renderPasses) {
  52519. this._renderPasses[passName]._incRefCount();
  52520. }
  52521. }
  52522. this._linkParameters();
  52523. };
  52524. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  52525. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  52526. for (var i = 0; i < _cam.length; i++) {
  52527. var camera = _cam[i];
  52528. var cameraName = camera.name;
  52529. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  52530. var index = this._cameras.indexOf(cameraName);
  52531. this._indicesForCamera.splice(index, 1);
  52532. this._cameras.splice(index, 1);
  52533. for (var passName in this._renderPasses) {
  52534. this._renderPasses[passName]._decRefCount();
  52535. }
  52536. }
  52537. };
  52538. PostProcessRenderEffect.prototype._enable = function (cameras) {
  52539. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  52540. for (var i = 0; i < _cam.length; i++) {
  52541. var camera = _cam[i];
  52542. var cameraName = camera.name;
  52543. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  52544. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  52545. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  52546. }
  52547. }
  52548. for (var passName in this._renderPasses) {
  52549. this._renderPasses[passName]._incRefCount();
  52550. }
  52551. }
  52552. };
  52553. PostProcessRenderEffect.prototype._disable = function (cameras) {
  52554. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  52555. for (var i = 0; i < _cam.length; i++) {
  52556. var camera = _cam[i];
  52557. var cameraName = camera.Name;
  52558. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  52559. for (var passName in this._renderPasses) {
  52560. this._renderPasses[passName]._decRefCount();
  52561. }
  52562. }
  52563. };
  52564. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  52565. if (this._singleInstance) {
  52566. return this._postProcesses[0];
  52567. }
  52568. else {
  52569. return this._postProcesses[camera.name];
  52570. }
  52571. };
  52572. PostProcessRenderEffect.prototype._linkParameters = function () {
  52573. var _this = this;
  52574. for (var index in this._postProcesses) {
  52575. if (this.applyParameters) {
  52576. this.applyParameters(this._postProcesses[index]);
  52577. }
  52578. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  52579. _this._linkTextures(effect);
  52580. });
  52581. }
  52582. };
  52583. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  52584. for (var renderPassName in this._renderPasses) {
  52585. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  52586. }
  52587. for (var renderEffectName in this._renderEffectAsPasses) {
  52588. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  52589. }
  52590. };
  52591. return PostProcessRenderEffect;
  52592. }());
  52593. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  52594. })(BABYLON || (BABYLON = {}));
  52595. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  52596. var BABYLON;
  52597. (function (BABYLON) {
  52598. var PostProcessRenderPipeline = (function () {
  52599. function PostProcessRenderPipeline(engine, name) {
  52600. this._engine = engine;
  52601. this._name = name;
  52602. this._renderEffects = new Array();
  52603. this._renderEffectsForIsolatedPass = new Array();
  52604. this._cameras = [];
  52605. }
  52606. PostProcessRenderPipeline.prototype.getClassName = function () {
  52607. return "PostProcessRenderPipeline";
  52608. };
  52609. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  52610. get: function () {
  52611. for (var renderEffectName in this._renderEffects) {
  52612. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  52613. if (!this._renderEffects[renderEffectName].isSupported) {
  52614. return false;
  52615. }
  52616. }
  52617. }
  52618. return true;
  52619. },
  52620. enumerable: true,
  52621. configurable: true
  52622. });
  52623. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  52624. this._renderEffects[renderEffect._name] = renderEffect;
  52625. };
  52626. // private
  52627. PostProcessRenderPipeline.prototype._rebuild = function () {
  52628. };
  52629. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  52630. var renderEffects = this._renderEffects[renderEffectName];
  52631. if (!renderEffects) {
  52632. return;
  52633. }
  52634. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  52635. };
  52636. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  52637. var renderEffects = this._renderEffects[renderEffectName];
  52638. if (!renderEffects) {
  52639. return;
  52640. }
  52641. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  52642. };
  52643. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  52644. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  52645. var indicesToDelete = [];
  52646. var i;
  52647. for (i = 0; i < _cam.length; i++) {
  52648. var camera = _cam[i];
  52649. var cameraName = camera.name;
  52650. if (this._cameras.indexOf(camera) === -1) {
  52651. this._cameras[cameraName] = camera;
  52652. }
  52653. else if (unique) {
  52654. indicesToDelete.push(i);
  52655. }
  52656. }
  52657. for (i = 0; i < indicesToDelete.length; i++) {
  52658. cameras.splice(indicesToDelete[i], 1);
  52659. }
  52660. for (var renderEffectName in this._renderEffects) {
  52661. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  52662. this._renderEffects[renderEffectName]._attachCameras(_cam);
  52663. }
  52664. }
  52665. };
  52666. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  52667. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  52668. for (var renderEffectName in this._renderEffects) {
  52669. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  52670. this._renderEffects[renderEffectName]._detachCameras(_cam);
  52671. }
  52672. }
  52673. for (var i = 0; i < _cam.length; i++) {
  52674. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  52675. }
  52676. };
  52677. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  52678. var _this = this;
  52679. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  52680. var pass = null;
  52681. var renderEffectName;
  52682. for (renderEffectName in this._renderEffects) {
  52683. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  52684. pass = this._renderEffects[renderEffectName].getPass(passName);
  52685. if (pass != null) {
  52686. break;
  52687. }
  52688. }
  52689. }
  52690. if (pass === null) {
  52691. return;
  52692. }
  52693. for (renderEffectName in this._renderEffects) {
  52694. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  52695. this._renderEffects[renderEffectName]._disable(_cam);
  52696. }
  52697. }
  52698. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  52699. for (var i = 0; i < _cam.length; i++) {
  52700. var camera = _cam[i];
  52701. var cameraName = camera.name;
  52702. 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); });
  52703. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  52704. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  52705. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  52706. }
  52707. };
  52708. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  52709. var _this = this;
  52710. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  52711. for (var i = 0; i < _cam.length; i++) {
  52712. var camera = _cam[i];
  52713. var cameraName = camera.name;
  52714. 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); });
  52715. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  52716. }
  52717. for (var renderEffectName in this._renderEffects) {
  52718. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  52719. this._renderEffects[renderEffectName]._enable(_cam);
  52720. }
  52721. }
  52722. };
  52723. PostProcessRenderPipeline.prototype._update = function () {
  52724. for (var renderEffectName in this._renderEffects) {
  52725. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  52726. this._renderEffects[renderEffectName]._update();
  52727. }
  52728. }
  52729. for (var i = 0; i < this._cameras.length; i++) {
  52730. var cameraName = this._cameras[i].name;
  52731. if (this._renderEffectsForIsolatedPass[cameraName]) {
  52732. this._renderEffectsForIsolatedPass[cameraName]._update();
  52733. }
  52734. }
  52735. };
  52736. PostProcessRenderPipeline.prototype._reset = function () {
  52737. this._renderEffects = new Array();
  52738. this._renderEffectsForIsolatedPass = new Array();
  52739. };
  52740. PostProcessRenderPipeline.prototype.dispose = function () {
  52741. // Must be implemented by children
  52742. };
  52743. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  52744. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  52745. __decorate([
  52746. BABYLON.serialize()
  52747. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  52748. return PostProcessRenderPipeline;
  52749. }());
  52750. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  52751. })(BABYLON || (BABYLON = {}));
  52752. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  52753. var BABYLON;
  52754. (function (BABYLON) {
  52755. var DepthRenderer = (function () {
  52756. function DepthRenderer(scene, type) {
  52757. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  52758. var _this = this;
  52759. this._viewMatrix = BABYLON.Matrix.Zero();
  52760. this._projectionMatrix = BABYLON.Matrix.Zero();
  52761. this._transformMatrix = BABYLON.Matrix.Zero();
  52762. this._worldViewProjection = BABYLON.Matrix.Zero();
  52763. this._scene = scene;
  52764. var engine = scene.getEngine();
  52765. // Render target
  52766. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  52767. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52768. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52769. this._depthMap.refreshRate = 1;
  52770. this._depthMap.renderParticles = false;
  52771. this._depthMap.renderList = null;
  52772. // set default depth value to 1.0 (far away)
  52773. this._depthMap.onClearObservable.add(function (engine) {
  52774. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  52775. });
  52776. // Custom render function
  52777. var renderSubMesh = function (subMesh) {
  52778. var mesh = subMesh.getRenderingMesh();
  52779. var scene = _this._scene;
  52780. var engine = scene.getEngine();
  52781. // Culling
  52782. engine.setState(subMesh.getMaterial().backFaceCulling);
  52783. // Managing instances
  52784. var batch = mesh._getInstancesRenderList(subMesh._id);
  52785. if (batch.mustReturn) {
  52786. return;
  52787. }
  52788. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  52789. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  52790. engine.enableEffect(_this._effect);
  52791. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  52792. var material = subMesh.getMaterial();
  52793. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  52794. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  52795. // Alpha test
  52796. if (material && material.needAlphaTesting()) {
  52797. var alphaTexture = material.getAlphaTestTexture();
  52798. _this._effect.setTexture("diffuseSampler", alphaTexture);
  52799. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  52800. }
  52801. // Bones
  52802. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52803. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  52804. }
  52805. // Draw
  52806. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  52807. }
  52808. };
  52809. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  52810. var index;
  52811. if (depthOnlySubMeshes.length) {
  52812. engine.setColorWrite(false);
  52813. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  52814. renderSubMesh(depthOnlySubMeshes.data[index]);
  52815. }
  52816. engine.setColorWrite(true);
  52817. }
  52818. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52819. renderSubMesh(opaqueSubMeshes.data[index]);
  52820. }
  52821. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52822. renderSubMesh(alphaTestSubMeshes.data[index]);
  52823. }
  52824. };
  52825. }
  52826. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  52827. var material = subMesh.getMaterial();
  52828. if (material.disableDepthWrite) {
  52829. return false;
  52830. }
  52831. var defines = [];
  52832. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52833. var mesh = subMesh.getMesh();
  52834. var scene = mesh.getScene();
  52835. // Alpha test
  52836. if (material && material.needAlphaTesting()) {
  52837. defines.push("#define ALPHATEST");
  52838. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52839. attribs.push(BABYLON.VertexBuffer.UVKind);
  52840. defines.push("#define UV1");
  52841. }
  52842. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52843. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52844. defines.push("#define UV2");
  52845. }
  52846. }
  52847. // Bones
  52848. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52849. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52850. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52851. if (mesh.numBoneInfluencers > 4) {
  52852. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52853. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52854. }
  52855. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52856. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52857. }
  52858. else {
  52859. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52860. }
  52861. // Instances
  52862. if (useInstances) {
  52863. defines.push("#define INSTANCES");
  52864. attribs.push("world0");
  52865. attribs.push("world1");
  52866. attribs.push("world2");
  52867. attribs.push("world3");
  52868. }
  52869. // Get correct effect
  52870. var join = defines.join("\n");
  52871. if (this._cachedDefines !== join) {
  52872. this._cachedDefines = join;
  52873. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  52874. }
  52875. return this._effect.isReady();
  52876. };
  52877. DepthRenderer.prototype.getDepthMap = function () {
  52878. return this._depthMap;
  52879. };
  52880. // Methods
  52881. DepthRenderer.prototype.dispose = function () {
  52882. this._depthMap.dispose();
  52883. };
  52884. return DepthRenderer;
  52885. }());
  52886. BABYLON.DepthRenderer = DepthRenderer;
  52887. })(BABYLON || (BABYLON = {}));
  52888. //# sourceMappingURL=babylon.depthRenderer.js.map
  52889. var BABYLON;
  52890. (function (BABYLON) {
  52891. var SSAORenderingPipeline = (function (_super) {
  52892. __extends(SSAORenderingPipeline, _super);
  52893. /**
  52894. * @constructor
  52895. * @param {string} name - The rendering pipeline name
  52896. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52897. * @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 }
  52898. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52899. */
  52900. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  52901. var _this = _super.call(this, scene.getEngine(), name) || this;
  52902. // Members
  52903. /**
  52904. * The PassPostProcess id in the pipeline that contains the original scene color
  52905. * @type {string}
  52906. */
  52907. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  52908. /**
  52909. * The SSAO PostProcess id in the pipeline
  52910. * @type {string}
  52911. */
  52912. _this.SSAORenderEffect = "SSAORenderEffect";
  52913. /**
  52914. * The horizontal blur PostProcess id in the pipeline
  52915. * @type {string}
  52916. */
  52917. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  52918. /**
  52919. * The vertical blur PostProcess id in the pipeline
  52920. * @type {string}
  52921. */
  52922. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  52923. /**
  52924. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  52925. * @type {string}
  52926. */
  52927. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  52928. /**
  52929. * The output strength of the SSAO post-process. Default value is 1.0.
  52930. * @type {number}
  52931. */
  52932. _this.totalStrength = 1.0;
  52933. /**
  52934. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  52935. * @type {number}
  52936. */
  52937. _this.radius = 0.0001;
  52938. /**
  52939. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  52940. * Must not be equal to fallOff and superior to fallOff.
  52941. * Default value is 0.975
  52942. * @type {number}
  52943. */
  52944. _this.area = 0.0075;
  52945. /**
  52946. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  52947. * Must not be equal to area and inferior to area.
  52948. * Default value is 0.0
  52949. * @type {number}
  52950. */
  52951. _this.fallOff = 0.000001;
  52952. /**
  52953. * The base color of the SSAO post-process
  52954. * The final result is "base + ssao" between [0, 1]
  52955. * @type {number}
  52956. */
  52957. _this.base = 0.5;
  52958. _this._firstUpdate = true;
  52959. _this._scene = scene;
  52960. // Set up assets
  52961. _this._createRandomTexture();
  52962. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  52963. var ssaoRatio = ratio.ssaoRatio || ratio;
  52964. var combineRatio = ratio.combineRatio || ratio;
  52965. _this._ratio = {
  52966. ssaoRatio: ssaoRatio,
  52967. combineRatio: combineRatio
  52968. };
  52969. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  52970. _this._createSSAOPostProcess(ssaoRatio);
  52971. _this._createBlurPostProcess(ssaoRatio);
  52972. _this._createSSAOCombinePostProcess(combineRatio);
  52973. // Set up pipeline
  52974. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  52975. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  52976. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  52977. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  52978. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  52979. // Finish
  52980. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52981. if (cameras)
  52982. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52983. return _this;
  52984. }
  52985. // Public Methods
  52986. /**
  52987. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  52988. */
  52989. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  52990. if (disableDepthRender === void 0) { disableDepthRender = false; }
  52991. for (var i = 0; i < this._scene.cameras.length; i++) {
  52992. var camera = this._scene.cameras[i];
  52993. this._originalColorPostProcess.dispose(camera);
  52994. this._ssaoPostProcess.dispose(camera);
  52995. this._blurHPostProcess.dispose(camera);
  52996. this._blurVPostProcess.dispose(camera);
  52997. this._ssaoCombinePostProcess.dispose(camera);
  52998. }
  52999. this._randomTexture.dispose();
  53000. if (disableDepthRender)
  53001. this._scene.disableDepthRenderer();
  53002. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53003. _super.prototype.dispose.call(this);
  53004. };
  53005. // Private Methods
  53006. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  53007. var _this = this;
  53008. /*
  53009. var samplerOffsets = [
  53010. -8.0, -6.0, -4.0, -2.0,
  53011. 0.0,
  53012. 2.0, 4.0, 6.0, 8.0
  53013. ];
  53014. */
  53015. var samples = 16;
  53016. var samplerOffsets = [];
  53017. for (var i = -8; i < 8; i++) {
  53018. samplerOffsets.push(i * 2);
  53019. }
  53020. 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");
  53021. this._blurHPostProcess.onApply = function (effect) {
  53022. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  53023. effect.setTexture("depthSampler", _this._depthTexture);
  53024. if (_this._firstUpdate) {
  53025. effect.setArray("samplerOffsets", samplerOffsets);
  53026. }
  53027. };
  53028. 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");
  53029. this._blurVPostProcess.onApply = function (effect) {
  53030. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  53031. effect.setTexture("depthSampler", _this._depthTexture);
  53032. if (_this._firstUpdate) {
  53033. effect.setArray("samplerOffsets", samplerOffsets);
  53034. _this._firstUpdate = false;
  53035. }
  53036. };
  53037. };
  53038. SSAORenderingPipeline.prototype._rebuild = function () {
  53039. this._firstUpdate = true;
  53040. _super.prototype._rebuild.call(this);
  53041. };
  53042. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  53043. var _this = this;
  53044. var numSamples = 16;
  53045. var sampleSphere = [
  53046. 0.5381, 0.1856, -0.4319,
  53047. 0.1379, 0.2486, 0.4430,
  53048. 0.3371, 0.5679, -0.0057,
  53049. -0.6999, -0.0451, -0.0019,
  53050. 0.0689, -0.1598, -0.8547,
  53051. 0.0560, 0.0069, -0.1843,
  53052. -0.0146, 0.1402, 0.0762,
  53053. 0.0100, -0.1924, -0.0344,
  53054. -0.3577, -0.5301, -0.4358,
  53055. -0.3169, 0.1063, 0.0158,
  53056. 0.0103, -0.5869, 0.0046,
  53057. -0.0897, -0.4940, 0.3287,
  53058. 0.7119, -0.0154, -0.0918,
  53059. -0.0533, 0.0596, -0.5411,
  53060. 0.0352, -0.0631, 0.5460,
  53061. -0.4776, 0.2847, -0.0271
  53062. ];
  53063. var samplesFactor = 1.0 / numSamples;
  53064. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  53065. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  53066. "area", "fallOff", "base", "range", "viewport"
  53067. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  53068. var viewport = new BABYLON.Vector2(0, 0);
  53069. this._ssaoPostProcess.onApply = function (effect) {
  53070. if (_this._firstUpdate) {
  53071. effect.setArray3("sampleSphere", sampleSphere);
  53072. effect.setFloat("samplesFactor", samplesFactor);
  53073. effect.setFloat("randTextureTiles", 4.0);
  53074. }
  53075. effect.setFloat("totalStrength", _this.totalStrength);
  53076. effect.setFloat("radius", _this.radius);
  53077. effect.setFloat("area", _this.area);
  53078. effect.setFloat("fallOff", _this.fallOff);
  53079. effect.setFloat("base", _this.base);
  53080. effect.setTexture("textureSampler", _this._depthTexture);
  53081. effect.setTexture("randomSampler", _this._randomTexture);
  53082. };
  53083. };
  53084. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  53085. var _this = this;
  53086. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53087. this._ssaoCombinePostProcess.onApply = function (effect) {
  53088. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  53089. };
  53090. };
  53091. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  53092. var size = 512;
  53093. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  53094. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53095. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53096. var context = this._randomTexture.getContext();
  53097. var rand = function (min, max) {
  53098. return Math.random() * (max - min) + min;
  53099. };
  53100. var randVector = BABYLON.Vector3.Zero();
  53101. for (var x = 0; x < size; x++) {
  53102. for (var y = 0; y < size; y++) {
  53103. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  53104. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  53105. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  53106. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  53107. context.fillRect(x, y, 1, 1);
  53108. }
  53109. }
  53110. this._randomTexture.update(false);
  53111. };
  53112. __decorate([
  53113. BABYLON.serialize()
  53114. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  53115. __decorate([
  53116. BABYLON.serialize()
  53117. ], SSAORenderingPipeline.prototype, "radius", void 0);
  53118. __decorate([
  53119. BABYLON.serialize()
  53120. ], SSAORenderingPipeline.prototype, "area", void 0);
  53121. __decorate([
  53122. BABYLON.serialize()
  53123. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  53124. __decorate([
  53125. BABYLON.serialize()
  53126. ], SSAORenderingPipeline.prototype, "base", void 0);
  53127. __decorate([
  53128. BABYLON.serialize()
  53129. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  53130. return SSAORenderingPipeline;
  53131. }(BABYLON.PostProcessRenderPipeline));
  53132. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  53133. })(BABYLON || (BABYLON = {}));
  53134. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  53135. var BABYLON;
  53136. (function (BABYLON) {
  53137. var SSAO2RenderingPipeline = (function (_super) {
  53138. __extends(SSAO2RenderingPipeline, _super);
  53139. /**
  53140. * @constructor
  53141. * @param {string} name - The rendering pipeline name
  53142. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53143. * @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 }
  53144. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53145. */
  53146. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  53147. var _this = _super.call(this, scene.getEngine(), name) || this;
  53148. // Members
  53149. /**
  53150. * The PassPostProcess id in the pipeline that contains the original scene color
  53151. * @type {string}
  53152. */
  53153. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  53154. /**
  53155. * The SSAO PostProcess id in the pipeline
  53156. * @type {string}
  53157. */
  53158. _this.SSAORenderEffect = "SSAORenderEffect";
  53159. /**
  53160. * The horizontal blur PostProcess id in the pipeline
  53161. * @type {string}
  53162. */
  53163. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  53164. /**
  53165. * The vertical blur PostProcess id in the pipeline
  53166. * @type {string}
  53167. */
  53168. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  53169. /**
  53170. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  53171. * @type {string}
  53172. */
  53173. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  53174. /**
  53175. * The output strength of the SSAO post-process. Default value is 1.0.
  53176. * @type {number}
  53177. */
  53178. _this.totalStrength = 1.0;
  53179. /**
  53180. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  53181. * @type {number}
  53182. */
  53183. _this.maxZ = 100.0;
  53184. /**
  53185. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  53186. * @type {number}
  53187. */
  53188. _this.minZAspect = 0.2;
  53189. /**
  53190. * Number of samples used for the SSAO calculations. Default value is 8
  53191. * @type {number}
  53192. */
  53193. _this._samples = 8;
  53194. /**
  53195. * Are we using bilateral blur ?
  53196. * @type {boolean}
  53197. */
  53198. _this._expensiveBlur = true;
  53199. /**
  53200. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  53201. * @type {number}
  53202. */
  53203. _this.radius = 2.0;
  53204. /**
  53205. * The base color of the SSAO post-process
  53206. * The final result is "base + ssao" between [0, 1]
  53207. * @type {number}
  53208. */
  53209. _this.base = 0.1;
  53210. _this._firstUpdate = true;
  53211. _this._scene = scene;
  53212. if (!_this.isSupported) {
  53213. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  53214. return _this;
  53215. }
  53216. var ssaoRatio = ratio.ssaoRatio || ratio;
  53217. var blurRatio = ratio.blurRatio || ratio;
  53218. _this._ratio = {
  53219. ssaoRatio: ssaoRatio,
  53220. blurRatio: blurRatio
  53221. };
  53222. // Set up assets
  53223. _this._createRandomTexture();
  53224. _this._depthTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  53225. _this._normalTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[1];
  53226. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  53227. _this._createSSAOPostProcess(1.0);
  53228. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  53229. _this._createSSAOCombinePostProcess(blurRatio);
  53230. // Set up pipeline
  53231. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  53232. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  53233. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  53234. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  53235. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  53236. // Finish
  53237. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53238. if (cameras)
  53239. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53240. return _this;
  53241. }
  53242. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  53243. get: function () {
  53244. return this._samples;
  53245. },
  53246. set: function (n) {
  53247. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  53248. this._samples = n;
  53249. this._sampleSphere = this._generateHemisphere();
  53250. this._firstUpdate = true;
  53251. },
  53252. enumerable: true,
  53253. configurable: true
  53254. });
  53255. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  53256. get: function () {
  53257. return this._expensiveBlur;
  53258. },
  53259. set: function (b) {
  53260. 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"]);
  53261. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  53262. this._expensiveBlur = b;
  53263. this._firstUpdate = true;
  53264. },
  53265. enumerable: true,
  53266. configurable: true
  53267. });
  53268. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  53269. /**
  53270. * Support test.
  53271. * @type {boolean}
  53272. */
  53273. get: function () {
  53274. var engine = BABYLON.Engine.LastCreatedEngine;
  53275. return engine.getCaps().drawBuffersExtension;
  53276. },
  53277. enumerable: true,
  53278. configurable: true
  53279. });
  53280. // Public Methods
  53281. /**
  53282. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  53283. */
  53284. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  53285. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  53286. for (var i = 0; i < this._scene.cameras.length; i++) {
  53287. var camera = this._scene.cameras[i];
  53288. this._originalColorPostProcess.dispose(camera);
  53289. this._ssaoPostProcess.dispose(camera);
  53290. this._blurHPostProcess.dispose(camera);
  53291. this._blurVPostProcess.dispose(camera);
  53292. this._ssaoCombinePostProcess.dispose(camera);
  53293. }
  53294. this._randomTexture.dispose();
  53295. if (disableGeometryBufferRenderer)
  53296. this._scene.disableGeometryBufferRenderer();
  53297. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53298. _super.prototype.dispose.call(this);
  53299. };
  53300. // Private Methods
  53301. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  53302. var _this = this;
  53303. var samples = 16;
  53304. this._samplerOffsets = [];
  53305. var expensive = this.expensiveBlur;
  53306. for (var i = -8; i < 8; i++) {
  53307. this._samplerOffsets.push(i * 2 + 0.5);
  53308. }
  53309. 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");
  53310. this._blurHPostProcess.onApply = function (effect) {
  53311. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  53312. effect.setFloat("near", _this._scene.activeCamera.minZ);
  53313. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  53314. effect.setFloat("radius", _this.radius);
  53315. effect.setTexture("depthSampler", _this._depthTexture);
  53316. if (_this._firstUpdate) {
  53317. effect.setArray("samplerOffsets", _this._samplerOffsets);
  53318. }
  53319. };
  53320. 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");
  53321. this._blurVPostProcess.onApply = function (effect) {
  53322. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  53323. effect.setFloat("near", _this._scene.activeCamera.minZ);
  53324. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  53325. effect.setFloat("radius", _this.radius);
  53326. effect.setTexture("depthSampler", _this._depthTexture);
  53327. if (_this._firstUpdate) {
  53328. effect.setArray("samplerOffsets", _this._samplerOffsets);
  53329. _this._firstUpdate = false;
  53330. }
  53331. };
  53332. };
  53333. SSAO2RenderingPipeline.prototype._rebuild = function () {
  53334. this._firstUpdate = true;
  53335. _super.prototype._rebuild.call(this);
  53336. };
  53337. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  53338. var numSamples = this.samples;
  53339. var result = [];
  53340. var vector, scale;
  53341. var rand = function (min, max) {
  53342. return Math.random() * (max - min) + min;
  53343. };
  53344. var lerp = function (start, end, percent) {
  53345. return (start + percent * (end - start));
  53346. };
  53347. var i = 0;
  53348. var normal = new BABYLON.Vector3(0, 0, 1);
  53349. while (i < numSamples) {
  53350. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  53351. vector.normalize();
  53352. scale = i / numSamples;
  53353. scale = lerp(0.1, 1.0, scale * scale);
  53354. vector.scaleInPlace(scale);
  53355. result.push(vector.x, vector.y, vector.z);
  53356. i++;
  53357. }
  53358. return result;
  53359. };
  53360. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  53361. var _this = this;
  53362. var numSamples = this.samples;
  53363. this._sampleSphere = this._generateHemisphere();
  53364. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  53365. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  53366. "base", "range", "projection", "near", "far", "texelSize",
  53367. "xViewport", "yViewport", "maxZ", "minZAspect"
  53368. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  53369. this._ssaoPostProcess.onApply = function (effect) {
  53370. if (_this._firstUpdate) {
  53371. effect.setArray3("sampleSphere", _this._sampleSphere);
  53372. effect.setFloat("randTextureTiles", 4.0);
  53373. }
  53374. effect.setFloat("samplesFactor", 1 / _this.samples);
  53375. effect.setFloat("totalStrength", _this.totalStrength);
  53376. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  53377. effect.setFloat("radius", _this.radius);
  53378. effect.setFloat("maxZ", _this.maxZ);
  53379. effect.setFloat("minZAspect", _this.minZAspect);
  53380. effect.setFloat("base", _this.base);
  53381. effect.setFloat("near", _this._scene.activeCamera.minZ);
  53382. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  53383. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  53384. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  53385. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  53386. effect.setTexture("textureSampler", _this._depthTexture);
  53387. effect.setTexture("normalSampler", _this._normalTexture);
  53388. effect.setTexture("randomSampler", _this._randomTexture);
  53389. };
  53390. };
  53391. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  53392. var _this = this;
  53393. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53394. this._ssaoCombinePostProcess.onApply = function (effect) {
  53395. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  53396. };
  53397. };
  53398. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  53399. var size = 512;
  53400. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  53401. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53402. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53403. var context = this._randomTexture.getContext();
  53404. var rand = function (min, max) {
  53405. return Math.random() * (max - min) + min;
  53406. };
  53407. var randVector = BABYLON.Vector3.Zero();
  53408. for (var x = 0; x < size; x++) {
  53409. for (var y = 0; y < size; y++) {
  53410. randVector.x = rand(0.0, 1.0);
  53411. randVector.y = rand(0.0, 1.0);
  53412. randVector.z = 0.0;
  53413. randVector.normalize();
  53414. randVector.scaleInPlace(255);
  53415. randVector.x = Math.floor(randVector.x);
  53416. randVector.y = Math.floor(randVector.y);
  53417. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  53418. context.fillRect(x, y, 1, 1);
  53419. }
  53420. }
  53421. this._randomTexture.update(false);
  53422. };
  53423. __decorate([
  53424. BABYLON.serialize()
  53425. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  53426. __decorate([
  53427. BABYLON.serialize()
  53428. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  53429. __decorate([
  53430. BABYLON.serialize()
  53431. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  53432. __decorate([
  53433. BABYLON.serialize("samples")
  53434. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  53435. __decorate([
  53436. BABYLON.serialize("expensiveBlur")
  53437. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  53438. __decorate([
  53439. BABYLON.serialize()
  53440. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  53441. __decorate([
  53442. BABYLON.serialize()
  53443. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  53444. __decorate([
  53445. BABYLON.serialize()
  53446. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  53447. return SSAO2RenderingPipeline;
  53448. }(BABYLON.PostProcessRenderPipeline));
  53449. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  53450. })(BABYLON || (BABYLON = {}));
  53451. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  53452. // BABYLON.JS Chromatic Aberration GLSL Shader
  53453. // Author: Olivier Guyot
  53454. // Separates very slightly R, G and B colors on the edges of the screen
  53455. // Inspired by Francois Tarlier & Martins Upitis
  53456. var BABYLON;
  53457. (function (BABYLON) {
  53458. var LensRenderingPipeline = (function (_super) {
  53459. __extends(LensRenderingPipeline, _super);
  53460. /**
  53461. * @constructor
  53462. *
  53463. * Effect parameters are as follow:
  53464. * {
  53465. * chromatic_aberration: number; // from 0 to x (1 for realism)
  53466. * edge_blur: number; // from 0 to x (1 for realism)
  53467. * distortion: number; // from 0 to x (1 for realism)
  53468. * grain_amount: number; // from 0 to 1
  53469. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  53470. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  53471. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  53472. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  53473. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  53474. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  53475. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  53476. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  53477. * }
  53478. * Note: if an effect parameter is unset, effect is disabled
  53479. *
  53480. * @param {string} name - The rendering pipeline name
  53481. * @param {object} parameters - An object containing all parameters (see above)
  53482. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53483. * @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)
  53484. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53485. */
  53486. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  53487. if (ratio === void 0) { ratio = 1.0; }
  53488. var _this = _super.call(this, scene.getEngine(), name) || this;
  53489. // Lens effects can be of the following:
  53490. // - chromatic aberration (slight shift of RGB colors)
  53491. // - blur on the edge of the lens
  53492. // - lens distortion
  53493. // - depth-of-field blur & highlights enhancing
  53494. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  53495. // - grain effect (noise or custom texture)
  53496. // Two additional texture samplers are needed:
  53497. // - depth map (for depth-of-field)
  53498. // - grain texture
  53499. /**
  53500. * The chromatic aberration PostProcess id in the pipeline
  53501. * @type {string}
  53502. */
  53503. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  53504. /**
  53505. * The highlights enhancing PostProcess id in the pipeline
  53506. * @type {string}
  53507. */
  53508. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  53509. /**
  53510. * The depth-of-field PostProcess id in the pipeline
  53511. * @type {string}
  53512. */
  53513. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  53514. _this._scene = scene;
  53515. // Fetch texture samplers
  53516. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  53517. if (parameters.grain_texture) {
  53518. _this._grainTexture = parameters.grain_texture;
  53519. }
  53520. else {
  53521. _this._createGrainTexture();
  53522. }
  53523. // save parameters
  53524. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  53525. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  53526. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  53527. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  53528. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  53529. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  53530. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  53531. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  53532. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  53533. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  53534. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  53535. // Create effects
  53536. _this._createChromaticAberrationPostProcess(ratio);
  53537. _this._createHighlightsPostProcess(ratio);
  53538. _this._createDepthOfFieldPostProcess(ratio / 4);
  53539. // Set up pipeline
  53540. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  53541. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  53542. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  53543. if (_this._highlightsGain === -1) {
  53544. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  53545. }
  53546. // Finish
  53547. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53548. if (cameras) {
  53549. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53550. }
  53551. return _this;
  53552. }
  53553. // public methods (self explanatory)
  53554. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  53555. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  53556. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  53557. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  53558. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  53559. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  53560. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  53561. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  53562. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  53563. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  53564. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  53565. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  53566. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  53567. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  53568. };
  53569. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  53570. this._highlightsPostProcess.updateEffect();
  53571. };
  53572. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  53573. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  53574. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  53575. this._highlightsGain = amount;
  53576. };
  53577. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  53578. if (this._highlightsGain === -1) {
  53579. this._highlightsGain = 1.0;
  53580. }
  53581. this._highlightsThreshold = amount;
  53582. };
  53583. LensRenderingPipeline.prototype.disableHighlights = function () {
  53584. this._highlightsGain = -1;
  53585. };
  53586. /**
  53587. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  53588. */
  53589. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  53590. if (disableDepthRender === void 0) { disableDepthRender = false; }
  53591. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53592. this._chromaticAberrationPostProcess = undefined;
  53593. this._highlightsPostProcess = undefined;
  53594. this._depthOfFieldPostProcess = undefined;
  53595. this._grainTexture.dispose();
  53596. if (disableDepthRender)
  53597. this._scene.disableDepthRenderer();
  53598. };
  53599. // colors shifting and distortion
  53600. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  53601. var _this = this;
  53602. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  53603. [], // samplers
  53604. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53605. this._chromaticAberrationPostProcess.onApply = function (effect) {
  53606. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  53607. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  53608. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  53609. };
  53610. };
  53611. // highlights enhancing
  53612. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  53613. var _this = this;
  53614. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  53615. [], // samplers
  53616. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  53617. this._highlightsPostProcess.onApply = function (effect) {
  53618. effect.setFloat('gain', _this._highlightsGain);
  53619. effect.setFloat('threshold', _this._highlightsThreshold);
  53620. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  53621. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  53622. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  53623. };
  53624. };
  53625. // colors shifting and distortion
  53626. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  53627. var _this = this;
  53628. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  53629. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  53630. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  53631. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  53632. this._depthOfFieldPostProcess.onApply = function (effect) {
  53633. effect.setTexture("depthSampler", _this._depthTexture);
  53634. effect.setTexture("grainSampler", _this._grainTexture);
  53635. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  53636. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  53637. effect.setFloat('grain_amount', _this._grainAmount);
  53638. effect.setBool('blur_noise', _this._blurNoise);
  53639. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  53640. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  53641. effect.setFloat('distortion', _this._distortion);
  53642. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  53643. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  53644. effect.setFloat('aperture', _this._dofAperture);
  53645. effect.setFloat('darken', _this._dofDarken);
  53646. effect.setFloat('edge_blur', _this._edgeBlur);
  53647. effect.setBool('highlights', (_this._highlightsGain !== -1));
  53648. effect.setFloat('near', _this._scene.activeCamera.minZ);
  53649. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  53650. };
  53651. };
  53652. // creates a black and white random noise texture, 512x512
  53653. LensRenderingPipeline.prototype._createGrainTexture = function () {
  53654. var size = 512;
  53655. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53656. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53657. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53658. var context = this._grainTexture.getContext();
  53659. var rand = function (min, max) {
  53660. return Math.random() * (max - min) + min;
  53661. };
  53662. var value;
  53663. for (var x = 0; x < size; x++) {
  53664. for (var y = 0; y < size; y++) {
  53665. value = Math.floor(rand(0.42, 0.58) * 255);
  53666. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  53667. context.fillRect(x, y, 1, 1);
  53668. }
  53669. }
  53670. this._grainTexture.update(false);
  53671. };
  53672. return LensRenderingPipeline;
  53673. }(BABYLON.PostProcessRenderPipeline));
  53674. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  53675. })(BABYLON || (BABYLON = {}));
  53676. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  53677. var BABYLON;
  53678. (function (BABYLON) {
  53679. var StandardRenderingPipeline = (function (_super) {
  53680. __extends(StandardRenderingPipeline, _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 (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  53686. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  53687. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53688. */
  53689. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  53690. if (originalPostProcess === void 0) { originalPostProcess = null; }
  53691. var _this = _super.call(this, scene.getEngine(), name) || this;
  53692. _this.downSampleX4PostProcess = null;
  53693. _this.brightPassPostProcess = null;
  53694. _this.blurHPostProcesses = [];
  53695. _this.blurVPostProcesses = [];
  53696. _this.textureAdderPostProcess = null;
  53697. _this.volumetricLightPostProcess = null;
  53698. _this.volumetricLightSmoothXPostProcess = null;
  53699. _this.volumetricLightSmoothYPostProcess = null;
  53700. _this.volumetricLightMergePostProces = null;
  53701. _this.volumetricLightFinalPostProcess = null;
  53702. _this.luminancePostProcess = null;
  53703. _this.luminanceDownSamplePostProcesses = [];
  53704. _this.hdrPostProcess = null;
  53705. _this.textureAdderFinalPostProcess = null;
  53706. _this.lensFlareFinalPostProcess = null;
  53707. _this.hdrFinalPostProcess = null;
  53708. _this.lensFlarePostProcess = null;
  53709. _this.lensFlareComposePostProcess = null;
  53710. _this.motionBlurPostProcess = null;
  53711. _this.depthOfFieldPostProcess = null;
  53712. // Values
  53713. _this.brightThreshold = 1.0;
  53714. _this.blurWidth = 512.0;
  53715. _this.horizontalBlur = false;
  53716. _this.exposure = 1.0;
  53717. _this.lensTexture = null;
  53718. _this.volumetricLightCoefficient = 0.2;
  53719. _this.volumetricLightPower = 4.0;
  53720. _this.volumetricLightBlurScale = 64.0;
  53721. _this.sourceLight = null;
  53722. _this.hdrMinimumLuminance = 1.0;
  53723. _this.hdrDecreaseRate = 0.5;
  53724. _this.hdrIncreaseRate = 0.5;
  53725. _this.lensColorTexture = null;
  53726. _this.lensFlareStrength = 20.0;
  53727. _this.lensFlareGhostDispersal = 1.4;
  53728. _this.lensFlareHaloWidth = 0.7;
  53729. _this.lensFlareDistortionStrength = 16.0;
  53730. _this.lensStarTexture = null;
  53731. _this.lensFlareDirtTexture = null;
  53732. _this.depthOfFieldDistance = 10.0;
  53733. _this.depthOfFieldBlurWidth = 64.0;
  53734. _this.motionStrength = 1.0;
  53735. // IAnimatable
  53736. _this.animations = [];
  53737. _this._currentDepthOfFieldSource = null;
  53738. _this._hdrCurrentLuminance = 1.0;
  53739. // Getters and setters
  53740. _this._bloomEnabled = true;
  53741. _this._depthOfFieldEnabled = false;
  53742. _this._vlsEnabled = false;
  53743. _this._lensFlareEnabled = false;
  53744. _this._hdrEnabled = false;
  53745. _this._motionBlurEnabled = false;
  53746. _this._motionBlurSamples = 64.0;
  53747. _this._volumetricLightStepsCount = 50.0;
  53748. _this._cameras = cameras || [];
  53749. // Initialize
  53750. _this._scene = scene;
  53751. _this._basePostProcess = originalPostProcess;
  53752. _this._ratio = ratio;
  53753. // Misc
  53754. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  53755. // Finish
  53756. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53757. _this._buildPipeline();
  53758. return _this;
  53759. }
  53760. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  53761. get: function () {
  53762. return this._bloomEnabled;
  53763. },
  53764. set: function (enabled) {
  53765. if (this._bloomEnabled === enabled) {
  53766. return;
  53767. }
  53768. this._bloomEnabled = enabled;
  53769. this._buildPipeline();
  53770. },
  53771. enumerable: true,
  53772. configurable: true
  53773. });
  53774. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  53775. get: function () {
  53776. return this._depthOfFieldEnabled;
  53777. },
  53778. set: function (enabled) {
  53779. if (this._depthOfFieldEnabled === enabled) {
  53780. return;
  53781. }
  53782. this._depthOfFieldEnabled = enabled;
  53783. this._buildPipeline();
  53784. },
  53785. enumerable: true,
  53786. configurable: true
  53787. });
  53788. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  53789. get: function () {
  53790. return this._lensFlareEnabled;
  53791. },
  53792. set: function (enabled) {
  53793. if (this._lensFlareEnabled === enabled) {
  53794. return;
  53795. }
  53796. this._lensFlareEnabled = enabled;
  53797. this._buildPipeline();
  53798. },
  53799. enumerable: true,
  53800. configurable: true
  53801. });
  53802. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  53803. get: function () {
  53804. return this._hdrEnabled;
  53805. },
  53806. set: function (enabled) {
  53807. if (this._hdrEnabled === enabled) {
  53808. return;
  53809. }
  53810. this._hdrEnabled = enabled;
  53811. this._buildPipeline();
  53812. },
  53813. enumerable: true,
  53814. configurable: true
  53815. });
  53816. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  53817. get: function () {
  53818. return this._vlsEnabled;
  53819. },
  53820. set: function (enabled) {
  53821. if (this._vlsEnabled === enabled) {
  53822. return;
  53823. }
  53824. if (enabled) {
  53825. var geometry = this._scene.enableGeometryBufferRenderer();
  53826. if (!geometry) {
  53827. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  53828. return;
  53829. }
  53830. }
  53831. this._vlsEnabled = enabled;
  53832. this._buildPipeline();
  53833. },
  53834. enumerable: true,
  53835. configurable: true
  53836. });
  53837. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  53838. get: function () {
  53839. return this._motionBlurEnabled;
  53840. },
  53841. set: function (enabled) {
  53842. if (this._motionBlurEnabled === enabled) {
  53843. return;
  53844. }
  53845. this._motionBlurEnabled = enabled;
  53846. this._buildPipeline();
  53847. },
  53848. enumerable: true,
  53849. configurable: true
  53850. });
  53851. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  53852. get: function () {
  53853. return this._volumetricLightStepsCount;
  53854. },
  53855. set: function (count) {
  53856. if (this.volumetricLightPostProcess) {
  53857. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  53858. }
  53859. this._volumetricLightStepsCount = count;
  53860. },
  53861. enumerable: true,
  53862. configurable: true
  53863. });
  53864. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  53865. get: function () {
  53866. return this._motionBlurSamples;
  53867. },
  53868. set: function (samples) {
  53869. if (this.motionBlurPostProcess) {
  53870. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  53871. }
  53872. this._motionBlurSamples = samples;
  53873. },
  53874. enumerable: true,
  53875. configurable: true
  53876. });
  53877. StandardRenderingPipeline.prototype._buildPipeline = function () {
  53878. var _this = this;
  53879. var ratio = this._ratio;
  53880. var scene = this._scene;
  53881. this._disposePostProcesses();
  53882. this._reset();
  53883. // Create pass post-process
  53884. if (!this._basePostProcess) {
  53885. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  53886. this.originalPostProcess.onApply = function (effect) {
  53887. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  53888. };
  53889. }
  53890. else {
  53891. this.originalPostProcess = this._basePostProcess;
  53892. }
  53893. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  53894. this._currentDepthOfFieldSource = this.originalPostProcess;
  53895. if (this._vlsEnabled) {
  53896. // Create volumetric light
  53897. this._createVolumetricLightPostProcess(scene, ratio);
  53898. // Create volumetric light final post-process
  53899. 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);
  53900. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  53901. }
  53902. if (this._bloomEnabled) {
  53903. // Create down sample X4 post-process
  53904. this._createDownSampleX4PostProcess(scene, ratio / 2);
  53905. // Create bright pass post-process
  53906. this._createBrightPassPostProcess(scene, ratio / 2);
  53907. // Create gaussian blur post-processes (down sampling blurs)
  53908. this._createBlurPostProcesses(scene, ratio / 4, 1);
  53909. // Create texture adder post-process
  53910. this._createTextureAdderPostProcess(scene, ratio);
  53911. // Create depth-of-field source post-process
  53912. 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);
  53913. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  53914. }
  53915. if (this._lensFlareEnabled) {
  53916. // Create lens flare post-process
  53917. this._createLensFlarePostProcess(scene, ratio);
  53918. // Create depth-of-field source post-process post lens-flare and disable it now
  53919. 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);
  53920. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  53921. }
  53922. if (this._hdrEnabled) {
  53923. // Create luminance
  53924. this._createLuminancePostProcesses(scene, this._floatTextureType);
  53925. // Create HDR
  53926. this._createHdrPostProcess(scene, ratio);
  53927. // Create depth-of-field source post-process post hdr and disable it now
  53928. 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);
  53929. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  53930. }
  53931. if (this._depthOfFieldEnabled) {
  53932. // Create gaussian blur used by depth-of-field
  53933. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  53934. // Create depth-of-field post-process
  53935. this._createDepthOfFieldPostProcess(scene, ratio);
  53936. }
  53937. if (this._motionBlurEnabled) {
  53938. // Create motion blur post-process
  53939. this._createMotionBlurPostProcess(scene, ratio);
  53940. }
  53941. if (this._cameras !== null) {
  53942. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  53943. }
  53944. };
  53945. // Down Sample X4 Post-Processs
  53946. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  53947. var _this = this;
  53948. var downSampleX4Offsets = new Array(32);
  53949. 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);
  53950. this.downSampleX4PostProcess.onApply = function (effect) {
  53951. var id = 0;
  53952. for (var i = -2; i < 2; i++) {
  53953. for (var j = -2; j < 2; j++) {
  53954. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  53955. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  53956. id += 2;
  53957. }
  53958. }
  53959. effect.setArray2("dsOffsets", downSampleX4Offsets);
  53960. };
  53961. // Add to pipeline
  53962. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  53963. };
  53964. // Brightpass Post-Process
  53965. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  53966. var _this = this;
  53967. var brightOffsets = new Array(8);
  53968. 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);
  53969. this.brightPassPostProcess.onApply = function (effect) {
  53970. var sU = (1.0 / _this.brightPassPostProcess.width);
  53971. var sV = (1.0 / _this.brightPassPostProcess.height);
  53972. brightOffsets[0] = -0.5 * sU;
  53973. brightOffsets[1] = 0.5 * sV;
  53974. brightOffsets[2] = 0.5 * sU;
  53975. brightOffsets[3] = 0.5 * sV;
  53976. brightOffsets[4] = -0.5 * sU;
  53977. brightOffsets[5] = -0.5 * sV;
  53978. brightOffsets[6] = 0.5 * sU;
  53979. brightOffsets[7] = -0.5 * sV;
  53980. effect.setArray2("dsOffsets", brightOffsets);
  53981. effect.setFloat("brightThreshold", _this.brightThreshold);
  53982. };
  53983. // Add to pipeline
  53984. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  53985. };
  53986. // Create blur H&V post-processes
  53987. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  53988. var _this = this;
  53989. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  53990. var engine = scene.getEngine();
  53991. 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);
  53992. 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);
  53993. blurX.onActivateObservable.add(function () {
  53994. var dw = blurX.width / engine.getRenderingCanvas().width;
  53995. blurX.kernel = _this[blurWidthKey] * dw;
  53996. });
  53997. blurY.onActivateObservable.add(function () {
  53998. var dw = blurY.height / engine.getRenderingCanvas().height;
  53999. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  54000. });
  54001. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  54002. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  54003. this.blurHPostProcesses.push(blurX);
  54004. this.blurVPostProcesses.push(blurY);
  54005. };
  54006. // Create texture adder post-process
  54007. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  54008. var _this = this;
  54009. 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);
  54010. this.textureAdderPostProcess.onApply = function (effect) {
  54011. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  54012. effect.setTexture("lensSampler", _this.lensTexture);
  54013. effect.setFloat("exposure", _this.exposure);
  54014. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  54015. };
  54016. // Add to pipeline
  54017. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  54018. };
  54019. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  54020. var _this = this;
  54021. var geometryRenderer = scene.enableGeometryBufferRenderer();
  54022. geometryRenderer.enablePosition = true;
  54023. var geometry = geometryRenderer.getGBuffer();
  54024. // Base post-process
  54025. 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));
  54026. var depthValues = BABYLON.Vector2.Zero();
  54027. this.volumetricLightPostProcess.onApply = function (effect) {
  54028. if (_this.sourceLight && _this.sourceLight.getShadowGenerator()) {
  54029. var generator = _this.sourceLight.getShadowGenerator();
  54030. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  54031. effect.setTexture("positionSampler", geometry.textures[2]);
  54032. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  54033. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  54034. effect.setVector3("cameraPosition", scene.activeCamera.globalPosition);
  54035. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  54036. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  54037. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  54038. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  54039. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  54040. effect.setVector2("depthValues", depthValues);
  54041. }
  54042. };
  54043. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  54044. // Smooth
  54045. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  54046. // Merge
  54047. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  54048. this.volumetricLightMergePostProces.onApply = function (effect) {
  54049. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  54050. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  54051. };
  54052. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  54053. };
  54054. // Create luminance
  54055. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  54056. var _this = this;
  54057. // Create luminance
  54058. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  54059. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  54060. var offsets = [];
  54061. this.luminancePostProcess.onApply = function (effect) {
  54062. var sU = (1.0 / _this.luminancePostProcess.width);
  54063. var sV = (1.0 / _this.luminancePostProcess.height);
  54064. offsets[0] = -0.5 * sU;
  54065. offsets[1] = 0.5 * sV;
  54066. offsets[2] = 0.5 * sU;
  54067. offsets[3] = 0.5 * sV;
  54068. offsets[4] = -0.5 * sU;
  54069. offsets[5] = -0.5 * sV;
  54070. offsets[6] = 0.5 * sU;
  54071. offsets[7] = -0.5 * sV;
  54072. effect.setArray2("lumOffsets", offsets);
  54073. };
  54074. // Add to pipeline
  54075. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  54076. // Create down sample luminance
  54077. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  54078. var size = Math.pow(3, i);
  54079. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  54080. if (i === 0) {
  54081. defines += "#define FINAL_DOWN_SAMPLER";
  54082. }
  54083. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  54084. this.luminanceDownSamplePostProcesses.push(postProcess);
  54085. }
  54086. // Create callbacks and add effects
  54087. var lastLuminance = this.luminancePostProcess;
  54088. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  54089. var downSampleOffsets = new Array(18);
  54090. pp.onApply = function (effect) {
  54091. var id = 0;
  54092. for (var x = -1; x < 2; x++) {
  54093. for (var y = -1; y < 2; y++) {
  54094. downSampleOffsets[id] = x / lastLuminance.width;
  54095. downSampleOffsets[id + 1] = y / lastLuminance.height;
  54096. id += 2;
  54097. }
  54098. }
  54099. effect.setArray2("dsOffsets", downSampleOffsets);
  54100. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  54101. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  54102. lastLuminance = _this.luminancePostProcess;
  54103. }
  54104. else {
  54105. lastLuminance = pp;
  54106. }
  54107. };
  54108. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  54109. pp.onAfterRender = function (effect) {
  54110. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  54111. 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);
  54112. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  54113. };
  54114. }
  54115. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  54116. });
  54117. };
  54118. // Create HDR post-process
  54119. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  54120. var _this = this;
  54121. 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);
  54122. var outputLiminance = 1;
  54123. var time = 0;
  54124. var lastTime = 0;
  54125. this.hdrPostProcess.onApply = function (effect) {
  54126. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  54127. time += scene.getEngine().getDeltaTime();
  54128. if (outputLiminance < 0) {
  54129. outputLiminance = _this._hdrCurrentLuminance;
  54130. }
  54131. else {
  54132. var dt = (lastTime - time) / 1000.0;
  54133. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  54134. outputLiminance += _this.hdrDecreaseRate * dt;
  54135. }
  54136. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  54137. outputLiminance -= _this.hdrIncreaseRate * dt;
  54138. }
  54139. else {
  54140. outputLiminance = _this._hdrCurrentLuminance;
  54141. }
  54142. }
  54143. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  54144. effect.setFloat("averageLuminance", outputLiminance);
  54145. lastTime = time;
  54146. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  54147. };
  54148. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  54149. };
  54150. // Create lens flare post-process
  54151. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  54152. var _this = this;
  54153. 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);
  54154. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  54155. this._createBlurPostProcesses(scene, ratio / 4, 2);
  54156. 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);
  54157. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  54158. var resolution = new BABYLON.Vector2(0, 0);
  54159. // Lens flare
  54160. this.lensFlarePostProcess.onApply = function (effect) {
  54161. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  54162. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  54163. effect.setFloat("strength", _this.lensFlareStrength);
  54164. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  54165. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  54166. // Shift
  54167. resolution.x = _this.lensFlarePostProcess.width;
  54168. resolution.y = _this.lensFlarePostProcess.height;
  54169. effect.setVector2("resolution", resolution);
  54170. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  54171. };
  54172. // Compose
  54173. 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);
  54174. 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);
  54175. this.lensFlareComposePostProcess.onApply = function (effect) {
  54176. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  54177. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  54178. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  54179. // Lens start rotation matrix
  54180. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  54181. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  54182. 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));
  54183. camRot *= 4.0;
  54184. 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);
  54185. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  54186. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  54187. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  54188. };
  54189. };
  54190. // Create depth-of-field post-process
  54191. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  54192. var _this = this;
  54193. 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);
  54194. this.depthOfFieldPostProcess.onApply = function (effect) {
  54195. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  54196. effect.setTexture("depthSampler", _this._getDepthTexture());
  54197. effect.setFloat("distance", _this.depthOfFieldDistance);
  54198. };
  54199. // Add to pipeline
  54200. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  54201. };
  54202. // Create motion blur post-process
  54203. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  54204. var _this = this;
  54205. 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);
  54206. var motionScale = 0;
  54207. var prevViewProjection = BABYLON.Matrix.Identity();
  54208. var invViewProjection = BABYLON.Matrix.Identity();
  54209. var viewProjection = BABYLON.Matrix.Identity();
  54210. var screenSize = BABYLON.Vector2.Zero();
  54211. this.motionBlurPostProcess.onApply = function (effect) {
  54212. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  54213. viewProjection.invertToRef(invViewProjection);
  54214. effect.setMatrix("inverseViewProjection", invViewProjection);
  54215. effect.setMatrix("prevViewProjection", prevViewProjection);
  54216. prevViewProjection = viewProjection;
  54217. screenSize.x = _this.motionBlurPostProcess.width;
  54218. screenSize.y = _this.motionBlurPostProcess.height;
  54219. effect.setVector2("screenSize", screenSize);
  54220. motionScale = scene.getEngine().getFps() / 60.0;
  54221. effect.setFloat("motionScale", motionScale);
  54222. effect.setFloat("motionStrength", _this.motionStrength);
  54223. effect.setTexture("depthSampler", _this._getDepthTexture());
  54224. };
  54225. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  54226. };
  54227. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  54228. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  54229. return this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  54230. }
  54231. return this._scene.enableDepthRenderer().getDepthMap();
  54232. };
  54233. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  54234. for (var i = 0; i < this._cameras.length; i++) {
  54235. var camera = this._cameras[i];
  54236. if (this.originalPostProcess) {
  54237. this.originalPostProcess.dispose(camera);
  54238. }
  54239. if (this.downSampleX4PostProcess) {
  54240. this.downSampleX4PostProcess.dispose(camera);
  54241. }
  54242. if (this.brightPassPostProcess) {
  54243. this.brightPassPostProcess.dispose(camera);
  54244. }
  54245. if (this.textureAdderPostProcess) {
  54246. this.textureAdderPostProcess.dispose(camera);
  54247. }
  54248. if (this.textureAdderFinalPostProcess) {
  54249. this.textureAdderFinalPostProcess.dispose(camera);
  54250. }
  54251. if (this.volumetricLightPostProcess) {
  54252. this.volumetricLightPostProcess.dispose(camera);
  54253. }
  54254. if (this.volumetricLightSmoothXPostProcess) {
  54255. this.volumetricLightSmoothXPostProcess.dispose(camera);
  54256. }
  54257. if (this.volumetricLightSmoothYPostProcess) {
  54258. this.volumetricLightSmoothYPostProcess.dispose(camera);
  54259. }
  54260. if (this.volumetricLightMergePostProces) {
  54261. this.volumetricLightMergePostProces.dispose(camera);
  54262. }
  54263. if (this.volumetricLightFinalPostProcess) {
  54264. this.volumetricLightFinalPostProcess.dispose(camera);
  54265. }
  54266. if (this.lensFlarePostProcess) {
  54267. this.lensFlarePostProcess.dispose(camera);
  54268. }
  54269. if (this.lensFlareComposePostProcess) {
  54270. this.lensFlareComposePostProcess.dispose(camera);
  54271. }
  54272. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  54273. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  54274. }
  54275. if (this.luminancePostProcess) {
  54276. this.luminancePostProcess.dispose(camera);
  54277. }
  54278. if (this.hdrPostProcess) {
  54279. this.hdrPostProcess.dispose(camera);
  54280. }
  54281. if (this.hdrFinalPostProcess) {
  54282. this.hdrFinalPostProcess.dispose(camera);
  54283. }
  54284. if (this.depthOfFieldPostProcess) {
  54285. this.depthOfFieldPostProcess.dispose(camera);
  54286. }
  54287. if (this.motionBlurPostProcess) {
  54288. this.motionBlurPostProcess.dispose(camera);
  54289. }
  54290. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  54291. this.blurHPostProcesses[j].dispose(camera);
  54292. }
  54293. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  54294. this.blurVPostProcesses[j].dispose(camera);
  54295. }
  54296. }
  54297. this.originalPostProcess = null;
  54298. this.downSampleX4PostProcess = null;
  54299. this.brightPassPostProcess = null;
  54300. this.textureAdderPostProcess = null;
  54301. this.textureAdderFinalPostProcess = null;
  54302. this.volumetricLightPostProcess = null;
  54303. this.volumetricLightSmoothXPostProcess = null;
  54304. this.volumetricLightSmoothYPostProcess = null;
  54305. this.volumetricLightMergePostProces = null;
  54306. this.volumetricLightFinalPostProcess = null;
  54307. this.lensFlarePostProcess = null;
  54308. this.lensFlareComposePostProcess = null;
  54309. this.luminancePostProcess = null;
  54310. this.hdrPostProcess = null;
  54311. this.hdrFinalPostProcess = null;
  54312. this.depthOfFieldPostProcess = null;
  54313. this.motionBlurPostProcess = null;
  54314. this.luminanceDownSamplePostProcesses = [];
  54315. this.blurHPostProcesses = [];
  54316. this.blurVPostProcesses = [];
  54317. };
  54318. // Dispose
  54319. StandardRenderingPipeline.prototype.dispose = function () {
  54320. this._disposePostProcesses();
  54321. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  54322. _super.prototype.dispose.call(this);
  54323. };
  54324. // Serialize rendering pipeline
  54325. StandardRenderingPipeline.prototype.serialize = function () {
  54326. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54327. serializationObject.customType = "StandardRenderingPipeline";
  54328. return serializationObject;
  54329. };
  54330. /**
  54331. * Static members
  54332. */
  54333. // Parse serialized pipeline
  54334. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  54335. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  54336. };
  54337. // Luminance steps
  54338. StandardRenderingPipeline.LuminanceSteps = 6;
  54339. __decorate([
  54340. BABYLON.serialize()
  54341. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  54342. __decorate([
  54343. BABYLON.serialize()
  54344. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  54345. __decorate([
  54346. BABYLON.serialize()
  54347. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  54348. __decorate([
  54349. BABYLON.serialize()
  54350. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  54351. __decorate([
  54352. BABYLON.serializeAsTexture("lensTexture")
  54353. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  54354. __decorate([
  54355. BABYLON.serialize()
  54356. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  54357. __decorate([
  54358. BABYLON.serialize()
  54359. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  54360. __decorate([
  54361. BABYLON.serialize()
  54362. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  54363. __decorate([
  54364. BABYLON.serialize()
  54365. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  54366. __decorate([
  54367. BABYLON.serialize()
  54368. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  54369. __decorate([
  54370. BABYLON.serialize()
  54371. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  54372. __decorate([
  54373. BABYLON.serializeAsTexture("lensColorTexture")
  54374. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  54375. __decorate([
  54376. BABYLON.serialize()
  54377. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  54378. __decorate([
  54379. BABYLON.serialize()
  54380. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  54381. __decorate([
  54382. BABYLON.serialize()
  54383. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  54384. __decorate([
  54385. BABYLON.serialize()
  54386. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  54387. __decorate([
  54388. BABYLON.serializeAsTexture("lensStarTexture")
  54389. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  54390. __decorate([
  54391. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  54392. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  54393. __decorate([
  54394. BABYLON.serialize()
  54395. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  54396. __decorate([
  54397. BABYLON.serialize()
  54398. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  54399. __decorate([
  54400. BABYLON.serialize()
  54401. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  54402. __decorate([
  54403. BABYLON.serialize()
  54404. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  54405. __decorate([
  54406. BABYLON.serialize()
  54407. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  54408. __decorate([
  54409. BABYLON.serialize()
  54410. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  54411. __decorate([
  54412. BABYLON.serialize()
  54413. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  54414. __decorate([
  54415. BABYLON.serialize()
  54416. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  54417. __decorate([
  54418. BABYLON.serialize()
  54419. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  54420. __decorate([
  54421. BABYLON.serialize()
  54422. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  54423. __decorate([
  54424. BABYLON.serialize()
  54425. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  54426. return StandardRenderingPipeline;
  54427. }(BABYLON.PostProcessRenderPipeline));
  54428. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  54429. })(BABYLON || (BABYLON = {}));
  54430. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  54431. var BABYLON;
  54432. (function (BABYLON) {
  54433. var FxaaPostProcess = (function (_super) {
  54434. __extends(FxaaPostProcess, _super);
  54435. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  54436. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54437. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  54438. _this.onApplyObservable.add(function (effect) {
  54439. var texelSize = _this.texelSize;
  54440. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  54441. });
  54442. return _this;
  54443. }
  54444. return FxaaPostProcess;
  54445. }(BABYLON.PostProcess));
  54446. BABYLON.FxaaPostProcess = FxaaPostProcess;
  54447. })(BABYLON || (BABYLON = {}));
  54448. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  54449. var BABYLON;
  54450. (function (BABYLON) {
  54451. var DefaultRenderingPipeline = (function (_super) {
  54452. __extends(DefaultRenderingPipeline, _super);
  54453. /**
  54454. * @constructor
  54455. * @param {string} name - The rendering pipeline name
  54456. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54457. * @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)
  54458. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54459. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  54460. */
  54461. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  54462. if (automaticBuild === void 0) { automaticBuild = true; }
  54463. var _this = _super.call(this, scene.getEngine(), name) || this;
  54464. _this.PassPostProcessId = "PassPostProcessEffect";
  54465. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  54466. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  54467. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  54468. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  54469. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  54470. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  54471. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  54472. // IAnimatable
  54473. _this.animations = [];
  54474. // Values
  54475. _this._bloomEnabled = false;
  54476. _this._fxaaEnabled = false;
  54477. _this._imageProcessingEnabled = true;
  54478. _this._bloomScale = 0.6;
  54479. _this._buildAllowed = true;
  54480. /**
  54481. * Specifies the size of the bloom blur kernel, relative to the final output size
  54482. */
  54483. _this.bloomKernel = 64;
  54484. /**
  54485. * Specifies the weight of the bloom in the final rendering
  54486. */
  54487. _this._bloomWeight = 0.15;
  54488. _this._cameras = cameras || [];
  54489. _this._buildAllowed = automaticBuild;
  54490. // Initialize
  54491. _this._scene = scene;
  54492. var caps = _this._scene.getEngine().getCaps();
  54493. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  54494. // Misc
  54495. if (_this._hdr) {
  54496. if (caps.textureHalfFloatRender) {
  54497. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  54498. }
  54499. else if (caps.textureFloatRender) {
  54500. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  54501. }
  54502. }
  54503. else {
  54504. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  54505. }
  54506. // Attach
  54507. scene.postProcessRenderPipelineManager.addPipeline(_this);
  54508. _this._buildPipeline();
  54509. return _this;
  54510. }
  54511. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  54512. get: function () {
  54513. return this._bloomWeight;
  54514. },
  54515. set: function (value) {
  54516. if (this._bloomWeight === value) {
  54517. return;
  54518. }
  54519. this._bloomWeight = value;
  54520. if (this._hdr && this.copyBack) {
  54521. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  54522. }
  54523. },
  54524. enumerable: true,
  54525. configurable: true
  54526. });
  54527. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  54528. get: function () {
  54529. return this._bloomScale;
  54530. },
  54531. set: function (value) {
  54532. if (this._bloomScale === value) {
  54533. return;
  54534. }
  54535. this._bloomScale = value;
  54536. this._buildPipeline();
  54537. },
  54538. enumerable: true,
  54539. configurable: true
  54540. });
  54541. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  54542. get: function () {
  54543. return this._bloomEnabled;
  54544. },
  54545. set: function (enabled) {
  54546. if (this._bloomEnabled === enabled) {
  54547. return;
  54548. }
  54549. this._bloomEnabled = enabled;
  54550. this._buildPipeline();
  54551. },
  54552. enumerable: true,
  54553. configurable: true
  54554. });
  54555. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  54556. get: function () {
  54557. return this._fxaaEnabled;
  54558. },
  54559. set: function (enabled) {
  54560. if (this._fxaaEnabled === enabled) {
  54561. return;
  54562. }
  54563. this._fxaaEnabled = enabled;
  54564. this._buildPipeline();
  54565. },
  54566. enumerable: true,
  54567. configurable: true
  54568. });
  54569. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  54570. get: function () {
  54571. return this._imageProcessingEnabled;
  54572. },
  54573. set: function (enabled) {
  54574. if (this._imageProcessingEnabled === enabled) {
  54575. return;
  54576. }
  54577. this._imageProcessingEnabled = enabled;
  54578. this._buildPipeline();
  54579. },
  54580. enumerable: true,
  54581. configurable: true
  54582. });
  54583. /**
  54584. * Force the compilation of the entire pipeline.
  54585. */
  54586. DefaultRenderingPipeline.prototype.prepare = function () {
  54587. var previousState = this._buildAllowed;
  54588. this._buildAllowed = true;
  54589. this._buildPipeline();
  54590. this._buildAllowed = previousState;
  54591. };
  54592. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  54593. var _this = this;
  54594. if (!this._buildAllowed) {
  54595. return;
  54596. }
  54597. var engine = this._scene.getEngine();
  54598. this._disposePostProcesses();
  54599. this._reset();
  54600. if (this.bloomEnabled) {
  54601. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  54602. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  54603. if (!this._hdr) {
  54604. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  54605. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  54606. this.highlights.autoClear = false;
  54607. this.highlights.alwaysForcePOT = true;
  54608. }
  54609. 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);
  54610. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  54611. this.blurX.alwaysForcePOT = true;
  54612. this.blurX.autoClear = false;
  54613. this.blurX.onActivateObservable.add(function () {
  54614. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  54615. _this.blurX.kernel = _this.bloomKernel * dw;
  54616. });
  54617. 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);
  54618. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  54619. this.blurY.alwaysForcePOT = true;
  54620. this.blurY.autoClear = false;
  54621. this.blurY.onActivateObservable.add(function () {
  54622. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  54623. _this.blurY.kernel = _this.bloomKernel * dh;
  54624. });
  54625. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  54626. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  54627. this.copyBack.alwaysForcePOT = true;
  54628. if (this._hdr) {
  54629. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  54630. var w = this.bloomWeight;
  54631. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  54632. }
  54633. else {
  54634. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  54635. }
  54636. this.copyBack.autoClear = false;
  54637. }
  54638. if (this._imageProcessingEnabled) {
  54639. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  54640. if (this._hdr) {
  54641. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  54642. }
  54643. else {
  54644. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  54645. }
  54646. }
  54647. if (this.fxaaEnabled) {
  54648. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  54649. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  54650. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  54651. }
  54652. else {
  54653. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  54654. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  54655. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  54656. }
  54657. if (this.bloomEnabled) {
  54658. if (this._hdr) {
  54659. this.copyBack.shareOutputWith(this.blurX);
  54660. if (this.imageProcessing) {
  54661. this.imageProcessing.shareOutputWith(this.pass);
  54662. this.imageProcessing.autoClear = false;
  54663. }
  54664. else if (this.fxaa) {
  54665. this.fxaa.shareOutputWith(this.pass);
  54666. }
  54667. else {
  54668. this.finalMerge.shareOutputWith(this.pass);
  54669. }
  54670. }
  54671. else {
  54672. if (this.fxaa) {
  54673. this.fxaa.shareOutputWith(this.pass);
  54674. }
  54675. else {
  54676. this.finalMerge.shareOutputWith(this.pass);
  54677. }
  54678. }
  54679. }
  54680. if (this._cameras !== null) {
  54681. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  54682. }
  54683. };
  54684. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  54685. for (var i = 0; i < this._cameras.length; i++) {
  54686. var camera = this._cameras[i];
  54687. if (this.pass) {
  54688. this.pass.dispose(camera);
  54689. }
  54690. if (this.highlights) {
  54691. this.highlights.dispose(camera);
  54692. }
  54693. if (this.blurX) {
  54694. this.blurX.dispose(camera);
  54695. }
  54696. if (this.blurY) {
  54697. this.blurY.dispose(camera);
  54698. }
  54699. if (this.copyBack) {
  54700. this.copyBack.dispose(camera);
  54701. }
  54702. if (this.imageProcessing) {
  54703. this.imageProcessing.dispose(camera);
  54704. }
  54705. if (this.fxaa) {
  54706. this.fxaa.dispose(camera);
  54707. }
  54708. if (this.finalMerge) {
  54709. this.finalMerge.dispose(camera);
  54710. }
  54711. }
  54712. this.pass = null;
  54713. this.highlights = null;
  54714. this.blurX = null;
  54715. this.blurY = null;
  54716. this.copyBack = null;
  54717. this.imageProcessing = null;
  54718. this.fxaa = null;
  54719. this.finalMerge = null;
  54720. };
  54721. // Dispose
  54722. DefaultRenderingPipeline.prototype.dispose = function () {
  54723. this._disposePostProcesses();
  54724. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  54725. _super.prototype.dispose.call(this);
  54726. };
  54727. // Serialize rendering pipeline
  54728. DefaultRenderingPipeline.prototype.serialize = function () {
  54729. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54730. serializationObject.customType = "DefaultRenderingPipeline";
  54731. return serializationObject;
  54732. };
  54733. // Parse serialized pipeline
  54734. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  54735. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  54736. };
  54737. __decorate([
  54738. BABYLON.serialize()
  54739. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  54740. __decorate([
  54741. BABYLON.serialize()
  54742. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  54743. __decorate([
  54744. BABYLON.serialize()
  54745. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  54746. __decorate([
  54747. BABYLON.serialize()
  54748. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  54749. __decorate([
  54750. BABYLON.serialize()
  54751. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  54752. __decorate([
  54753. BABYLON.serialize()
  54754. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  54755. __decorate([
  54756. BABYLON.serialize()
  54757. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  54758. __decorate([
  54759. BABYLON.serialize()
  54760. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  54761. return DefaultRenderingPipeline;
  54762. }(BABYLON.PostProcessRenderPipeline));
  54763. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  54764. })(BABYLON || (BABYLON = {}));
  54765. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  54766. var BABYLON;
  54767. (function (BABYLON) {
  54768. var GeometryBufferRenderer = (function () {
  54769. function GeometryBufferRenderer(scene, ratio) {
  54770. if (ratio === void 0) { ratio = 1; }
  54771. this._viewMatrix = BABYLON.Matrix.Zero();
  54772. this._projectionMatrix = BABYLON.Matrix.Zero();
  54773. this._transformMatrix = BABYLON.Matrix.Zero();
  54774. this._worldViewProjection = BABYLON.Matrix.Zero();
  54775. this._enablePosition = false;
  54776. this._scene = scene;
  54777. this._ratio = ratio;
  54778. // Render target
  54779. this._createRenderTargets();
  54780. }
  54781. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  54782. set: function (meshes) {
  54783. this._multiRenderTarget.renderList = meshes;
  54784. },
  54785. enumerable: true,
  54786. configurable: true
  54787. });
  54788. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  54789. get: function () {
  54790. return this._multiRenderTarget.isSupported;
  54791. },
  54792. enumerable: true,
  54793. configurable: true
  54794. });
  54795. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  54796. get: function () {
  54797. return this._enablePosition;
  54798. },
  54799. set: function (enable) {
  54800. this._enablePosition = enable;
  54801. this.dispose();
  54802. this._createRenderTargets();
  54803. },
  54804. enumerable: true,
  54805. configurable: true
  54806. });
  54807. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  54808. var material = subMesh.getMaterial();
  54809. if (material && material.disableDepthWrite) {
  54810. return false;
  54811. }
  54812. var defines = [];
  54813. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  54814. var mesh = subMesh.getMesh();
  54815. var scene = mesh.getScene();
  54816. // Alpha test
  54817. if (material && material.needAlphaTesting()) {
  54818. defines.push("#define ALPHATEST");
  54819. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54820. attribs.push(BABYLON.VertexBuffer.UVKind);
  54821. defines.push("#define UV1");
  54822. }
  54823. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  54824. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  54825. defines.push("#define UV2");
  54826. }
  54827. }
  54828. // Buffers
  54829. if (this._enablePosition) {
  54830. defines.push("#define POSITION");
  54831. }
  54832. // Bones
  54833. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54834. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54835. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54836. if (mesh.numBoneInfluencers > 4) {
  54837. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  54838. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  54839. }
  54840. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54841. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54842. }
  54843. else {
  54844. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54845. }
  54846. // Instances
  54847. if (useInstances) {
  54848. defines.push("#define INSTANCES");
  54849. attribs.push("world0");
  54850. attribs.push("world1");
  54851. attribs.push("world2");
  54852. attribs.push("world3");
  54853. }
  54854. // Get correct effect
  54855. var join = defines.join("\n");
  54856. if (this._cachedDefines !== join) {
  54857. this._cachedDefines = join;
  54858. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, null, null, null, { buffersCount: this._enablePosition ? 3 : 2 });
  54859. }
  54860. return this._effect.isReady();
  54861. };
  54862. GeometryBufferRenderer.prototype.getGBuffer = function () {
  54863. return this._multiRenderTarget;
  54864. };
  54865. // Methods
  54866. GeometryBufferRenderer.prototype.dispose = function () {
  54867. this.getGBuffer().dispose();
  54868. };
  54869. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  54870. var _this = this;
  54871. var engine = this._scene.getEngine();
  54872. var count = this._enablePosition ? 3 : 2;
  54873. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  54874. if (!this.isSupported) {
  54875. return null;
  54876. }
  54877. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54878. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54879. this._multiRenderTarget.refreshRate = 1;
  54880. this._multiRenderTarget.renderParticles = false;
  54881. this._multiRenderTarget.renderList = null;
  54882. // set default depth value to 1.0 (far away)
  54883. this._multiRenderTarget.onClearObservable.add(function (engine) {
  54884. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  54885. });
  54886. // Custom render function
  54887. var renderSubMesh = function (subMesh) {
  54888. var mesh = subMesh.getRenderingMesh();
  54889. var scene = _this._scene;
  54890. var engine = scene.getEngine();
  54891. // Culling
  54892. engine.setState(subMesh.getMaterial().backFaceCulling);
  54893. // Managing instances
  54894. var batch = mesh._getInstancesRenderList(subMesh._id);
  54895. if (batch.mustReturn) {
  54896. return;
  54897. }
  54898. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  54899. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  54900. engine.enableEffect(_this._effect);
  54901. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  54902. var material = subMesh.getMaterial();
  54903. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  54904. _this._effect.setMatrix("view", scene.getViewMatrix());
  54905. // Alpha test
  54906. if (material && material.needAlphaTesting()) {
  54907. var alphaTexture = material.getAlphaTestTexture();
  54908. _this._effect.setTexture("diffuseSampler", alphaTexture);
  54909. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  54910. }
  54911. // Bones
  54912. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54913. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  54914. }
  54915. // Draw
  54916. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  54917. }
  54918. };
  54919. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  54920. var index;
  54921. if (depthOnlySubMeshes.length) {
  54922. engine.setColorWrite(false);
  54923. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  54924. renderSubMesh(depthOnlySubMeshes.data[index]);
  54925. }
  54926. engine.setColorWrite(true);
  54927. }
  54928. for (index = 0; index < opaqueSubMeshes.length; index++) {
  54929. renderSubMesh(opaqueSubMeshes.data[index]);
  54930. }
  54931. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  54932. renderSubMesh(alphaTestSubMeshes.data[index]);
  54933. }
  54934. };
  54935. };
  54936. return GeometryBufferRenderer;
  54937. }());
  54938. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  54939. })(BABYLON || (BABYLON = {}));
  54940. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  54941. var BABYLON;
  54942. (function (BABYLON) {
  54943. var RefractionPostProcess = (function (_super) {
  54944. __extends(RefractionPostProcess, _super);
  54945. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  54946. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  54947. _this.color = color;
  54948. _this.depth = depth;
  54949. _this.colorLevel = colorLevel;
  54950. _this.onActivateObservable.add(function (cam) {
  54951. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  54952. });
  54953. _this.onApplyObservable.add(function (effect) {
  54954. effect.setColor3("baseColor", _this.color);
  54955. effect.setFloat("depth", _this.depth);
  54956. effect.setFloat("colorLevel", _this.colorLevel);
  54957. effect.setTexture("refractionSampler", _this._refRexture);
  54958. });
  54959. return _this;
  54960. }
  54961. // Methods
  54962. RefractionPostProcess.prototype.dispose = function (camera) {
  54963. if (this._refRexture) {
  54964. this._refRexture.dispose();
  54965. }
  54966. _super.prototype.dispose.call(this, camera);
  54967. };
  54968. return RefractionPostProcess;
  54969. }(BABYLON.PostProcess));
  54970. BABYLON.RefractionPostProcess = RefractionPostProcess;
  54971. })(BABYLON || (BABYLON = {}));
  54972. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  54973. var BABYLON;
  54974. (function (BABYLON) {
  54975. var BlackAndWhitePostProcess = (function (_super) {
  54976. __extends(BlackAndWhitePostProcess, _super);
  54977. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  54978. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  54979. _this.degree = 1;
  54980. _this.onApplyObservable.add(function (effect) {
  54981. effect.setFloat("degree", _this.degree);
  54982. });
  54983. return _this;
  54984. }
  54985. return BlackAndWhitePostProcess;
  54986. }(BABYLON.PostProcess));
  54987. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  54988. })(BABYLON || (BABYLON = {}));
  54989. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  54990. var BABYLON;
  54991. (function (BABYLON) {
  54992. var ConvolutionPostProcess = (function (_super) {
  54993. __extends(ConvolutionPostProcess, _super);
  54994. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  54995. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  54996. _this.kernel = kernel;
  54997. _this.onApply = function (effect) {
  54998. effect.setFloat2("screenSize", _this.width, _this.height);
  54999. effect.setArray("kernel", _this.kernel);
  55000. };
  55001. return _this;
  55002. }
  55003. // Statics
  55004. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  55005. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  55006. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  55007. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  55008. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  55009. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  55010. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  55011. return ConvolutionPostProcess;
  55012. }(BABYLON.PostProcess));
  55013. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  55014. })(BABYLON || (BABYLON = {}));
  55015. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  55016. var BABYLON;
  55017. (function (BABYLON) {
  55018. var FilterPostProcess = (function (_super) {
  55019. __extends(FilterPostProcess, _super);
  55020. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  55021. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  55022. _this.kernelMatrix = kernelMatrix;
  55023. _this.onApply = function (effect) {
  55024. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  55025. };
  55026. return _this;
  55027. }
  55028. return FilterPostProcess;
  55029. }(BABYLON.PostProcess));
  55030. BABYLON.FilterPostProcess = FilterPostProcess;
  55031. })(BABYLON || (BABYLON = {}));
  55032. //# sourceMappingURL=babylon.filterPostProcess.js.map
  55033. var BABYLON;
  55034. (function (BABYLON) {
  55035. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  55036. var VolumetricLightScatteringPostProcess = (function (_super) {
  55037. __extends(VolumetricLightScatteringPostProcess, _super);
  55038. /**
  55039. * @constructor
  55040. * @param {string} name - The post-process name
  55041. * @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)
  55042. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  55043. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  55044. * @param {number} samples - The post-process quality, default 100
  55045. * @param {number} samplingMode - The post-process filtering mode
  55046. * @param {BABYLON.Engine} engine - The babylon engine
  55047. * @param {boolean} reusable - If the post-process is reusable
  55048. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  55049. */
  55050. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  55051. if (samples === void 0) { samples = 100; }
  55052. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55053. 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;
  55054. _this._screenCoordinates = BABYLON.Vector2.Zero();
  55055. /**
  55056. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  55057. * @type {Vector3}
  55058. */
  55059. _this.customMeshPosition = BABYLON.Vector3.Zero();
  55060. /**
  55061. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  55062. * @type {boolean}
  55063. */
  55064. _this.useCustomMeshPosition = false;
  55065. /**
  55066. * If the post-process should inverse the light scattering direction
  55067. * @type {boolean}
  55068. */
  55069. _this.invert = true;
  55070. /**
  55071. * Array containing the excluded meshes not rendered in the internal pass
  55072. */
  55073. _this.excludedMeshes = new Array();
  55074. /**
  55075. * Controls the overall intensity of the post-process
  55076. * @type {number}
  55077. */
  55078. _this.exposure = 0.3;
  55079. /**
  55080. * Dissipates each sample's contribution in range [0, 1]
  55081. * @type {number}
  55082. */
  55083. _this.decay = 0.96815;
  55084. /**
  55085. * Controls the overall intensity of each sample
  55086. * @type {number}
  55087. */
  55088. _this.weight = 0.58767;
  55089. /**
  55090. * Controls the density of each sample
  55091. * @type {number}
  55092. */
  55093. _this.density = 0.926;
  55094. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  55095. var engine = scene.getEngine();
  55096. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  55097. // Configure mesh
  55098. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  55099. // Configure
  55100. _this._createPass(scene, ratio.passRatio || ratio);
  55101. _this.onActivate = function (camera) {
  55102. if (!_this.isSupported) {
  55103. _this.dispose(camera);
  55104. }
  55105. _this.onActivate = null;
  55106. };
  55107. _this.onApplyObservable.add(function (effect) {
  55108. _this._updateMeshScreenCoordinates(scene);
  55109. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  55110. effect.setFloat("exposure", _this.exposure);
  55111. effect.setFloat("decay", _this.decay);
  55112. effect.setFloat("weight", _this.weight);
  55113. effect.setFloat("density", _this.density);
  55114. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  55115. });
  55116. return _this;
  55117. }
  55118. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  55119. get: function () {
  55120. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  55121. return false;
  55122. },
  55123. set: function (useDiffuseColor) {
  55124. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  55125. },
  55126. enumerable: true,
  55127. configurable: true
  55128. });
  55129. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  55130. return "VolumetricLightScatteringPostProcess";
  55131. };
  55132. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  55133. var mesh = subMesh.getMesh();
  55134. // Render this.mesh as default
  55135. if (mesh === this.mesh) {
  55136. return mesh.material.isReady(mesh);
  55137. }
  55138. var defines = [];
  55139. var attribs = [BABYLON.VertexBuffer.PositionKind];
  55140. var material = subMesh.getMaterial();
  55141. var needUV = false;
  55142. // Alpha test
  55143. if (material) {
  55144. if (material.needAlphaTesting()) {
  55145. defines.push("#define ALPHATEST");
  55146. }
  55147. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55148. attribs.push(BABYLON.VertexBuffer.UVKind);
  55149. defines.push("#define UV1");
  55150. }
  55151. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55152. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55153. defines.push("#define UV2");
  55154. }
  55155. }
  55156. // Bones
  55157. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55158. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55159. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55160. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55161. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55162. }
  55163. else {
  55164. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55165. }
  55166. // Instances
  55167. if (useInstances) {
  55168. defines.push("#define INSTANCES");
  55169. attribs.push("world0");
  55170. attribs.push("world1");
  55171. attribs.push("world2");
  55172. attribs.push("world3");
  55173. }
  55174. // Get correct effect
  55175. var join = defines.join("\n");
  55176. if (this._cachedDefines !== join) {
  55177. this._cachedDefines = join;
  55178. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  55179. }
  55180. return this._volumetricLightScatteringPass.isReady();
  55181. };
  55182. /**
  55183. * Sets the new light position for light scattering effect
  55184. * @param {BABYLON.Vector3} The new custom light position
  55185. */
  55186. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  55187. this.customMeshPosition = position;
  55188. };
  55189. /**
  55190. * Returns the light position for light scattering effect
  55191. * @return {BABYLON.Vector3} The custom light position
  55192. */
  55193. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  55194. return this.customMeshPosition;
  55195. };
  55196. /**
  55197. * Disposes the internal assets and detaches the post-process from the camera
  55198. */
  55199. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  55200. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  55201. if (rttIndex !== -1) {
  55202. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  55203. }
  55204. this._volumetricLightScatteringRTT.dispose();
  55205. _super.prototype.dispose.call(this, camera);
  55206. };
  55207. /**
  55208. * Returns the render target texture used by the post-process
  55209. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  55210. */
  55211. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  55212. return this._volumetricLightScatteringRTT;
  55213. };
  55214. // Private methods
  55215. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  55216. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  55217. return true;
  55218. }
  55219. return false;
  55220. };
  55221. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  55222. var _this = this;
  55223. var engine = scene.getEngine();
  55224. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  55225. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55226. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55227. this._volumetricLightScatteringRTT.renderList = null;
  55228. this._volumetricLightScatteringRTT.renderParticles = false;
  55229. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  55230. // Custom render function for submeshes
  55231. var renderSubMesh = function (subMesh) {
  55232. var mesh = subMesh.getRenderingMesh();
  55233. if (_this._meshExcluded(mesh)) {
  55234. return;
  55235. }
  55236. var scene = mesh.getScene();
  55237. var engine = scene.getEngine();
  55238. // Culling
  55239. engine.setState(subMesh.getMaterial().backFaceCulling);
  55240. // Managing instances
  55241. var batch = mesh._getInstancesRenderList(subMesh._id);
  55242. if (batch.mustReturn) {
  55243. return;
  55244. }
  55245. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  55246. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  55247. var effect = _this._volumetricLightScatteringPass;
  55248. if (mesh === _this.mesh) {
  55249. if (subMesh.effect) {
  55250. effect = subMesh.effect;
  55251. }
  55252. else {
  55253. effect = subMesh.getMaterial().getEffect();
  55254. }
  55255. }
  55256. engine.enableEffect(effect);
  55257. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  55258. if (mesh === _this.mesh) {
  55259. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  55260. }
  55261. else {
  55262. var material = subMesh.getMaterial();
  55263. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  55264. // Alpha test
  55265. if (material && material.needAlphaTesting()) {
  55266. var alphaTexture = material.getAlphaTestTexture();
  55267. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  55268. if (alphaTexture) {
  55269. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  55270. }
  55271. }
  55272. // Bones
  55273. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55274. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  55275. }
  55276. }
  55277. // Draw
  55278. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  55279. }
  55280. };
  55281. // Render target texture callbacks
  55282. var savedSceneClearColor;
  55283. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  55284. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  55285. savedSceneClearColor = scene.clearColor;
  55286. scene.clearColor = sceneClearColor;
  55287. });
  55288. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  55289. scene.clearColor = savedSceneClearColor;
  55290. });
  55291. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  55292. var engine = scene.getEngine();
  55293. var index;
  55294. if (depthOnlySubMeshes.length) {
  55295. engine.setColorWrite(false);
  55296. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  55297. renderSubMesh(depthOnlySubMeshes.data[index]);
  55298. }
  55299. engine.setColorWrite(true);
  55300. }
  55301. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55302. renderSubMesh(opaqueSubMeshes.data[index]);
  55303. }
  55304. engine.setAlphaTesting(true);
  55305. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55306. renderSubMesh(alphaTestSubMeshes.data[index]);
  55307. }
  55308. engine.setAlphaTesting(false);
  55309. if (transparentSubMeshes.length) {
  55310. // Sort sub meshes
  55311. for (index = 0; index < transparentSubMeshes.length; index++) {
  55312. var submesh = transparentSubMeshes.data[index];
  55313. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  55314. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  55315. }
  55316. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  55317. sortedArray.sort(function (a, b) {
  55318. // Alpha index first
  55319. if (a._alphaIndex > b._alphaIndex) {
  55320. return 1;
  55321. }
  55322. if (a._alphaIndex < b._alphaIndex) {
  55323. return -1;
  55324. }
  55325. // Then distance to camera
  55326. if (a._distanceToCamera < b._distanceToCamera) {
  55327. return 1;
  55328. }
  55329. if (a._distanceToCamera > b._distanceToCamera) {
  55330. return -1;
  55331. }
  55332. return 0;
  55333. });
  55334. // Render sub meshes
  55335. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55336. for (index = 0; index < sortedArray.length; index++) {
  55337. renderSubMesh(sortedArray[index]);
  55338. }
  55339. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55340. }
  55341. };
  55342. };
  55343. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  55344. var transform = scene.getTransformMatrix();
  55345. var meshPosition;
  55346. if (this.useCustomMeshPosition) {
  55347. meshPosition = this.customMeshPosition;
  55348. }
  55349. else if (this.attachedNode) {
  55350. meshPosition = this.attachedNode.position;
  55351. }
  55352. else {
  55353. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  55354. }
  55355. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  55356. this._screenCoordinates.x = pos.x / this._viewPort.width;
  55357. this._screenCoordinates.y = pos.y / this._viewPort.height;
  55358. if (this.invert)
  55359. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  55360. };
  55361. // Static methods
  55362. /**
  55363. * Creates a default mesh for the Volumeric Light Scattering post-process
  55364. * @param {string} The mesh name
  55365. * @param {BABYLON.Scene} The scene where to create the mesh
  55366. * @return {BABYLON.Mesh} the default mesh
  55367. */
  55368. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  55369. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  55370. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55371. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  55372. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  55373. mesh.material = material;
  55374. return mesh;
  55375. };
  55376. __decorate([
  55377. BABYLON.serializeAsVector3()
  55378. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  55379. __decorate([
  55380. BABYLON.serialize()
  55381. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  55382. __decorate([
  55383. BABYLON.serialize()
  55384. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  55385. __decorate([
  55386. BABYLON.serializeAsMeshReference()
  55387. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  55388. __decorate([
  55389. BABYLON.serialize()
  55390. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  55391. __decorate([
  55392. BABYLON.serialize()
  55393. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  55394. __decorate([
  55395. BABYLON.serialize()
  55396. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  55397. __decorate([
  55398. BABYLON.serialize()
  55399. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  55400. __decorate([
  55401. BABYLON.serialize()
  55402. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  55403. return VolumetricLightScatteringPostProcess;
  55404. }(BABYLON.PostProcess));
  55405. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  55406. })(BABYLON || (BABYLON = {}));
  55407. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  55408. //
  55409. // This post-process allows the modification of rendered colors by using
  55410. // a 'look-up table' (LUT). This effect is also called Color Grading.
  55411. //
  55412. // The object needs to be provided an url to a texture containing the color
  55413. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  55414. // Use an image editing software to tweak the LUT to match your needs.
  55415. //
  55416. // For an example of a color LUT, see here:
  55417. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  55418. // For explanations on color grading, see here:
  55419. // http://udn.epicgames.com/Three/ColorGrading.html
  55420. //
  55421. var BABYLON;
  55422. (function (BABYLON) {
  55423. var ColorCorrectionPostProcess = (function (_super) {
  55424. __extends(ColorCorrectionPostProcess, _super);
  55425. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  55426. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  55427. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  55428. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  55429. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55430. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55431. _this.onApply = function (effect) {
  55432. effect.setTexture("colorTable", _this._colorTableTexture);
  55433. };
  55434. return _this;
  55435. }
  55436. return ColorCorrectionPostProcess;
  55437. }(BABYLON.PostProcess));
  55438. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  55439. })(BABYLON || (BABYLON = {}));
  55440. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  55441. var BABYLON;
  55442. (function (BABYLON) {
  55443. var TonemappingOperator;
  55444. (function (TonemappingOperator) {
  55445. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  55446. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  55447. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  55448. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  55449. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  55450. ;
  55451. var TonemapPostProcess = (function (_super) {
  55452. __extends(TonemapPostProcess, _super);
  55453. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  55454. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55455. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55456. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  55457. _this._operator = _operator;
  55458. _this.exposureAdjustment = exposureAdjustment;
  55459. var defines = "#define ";
  55460. if (_this._operator === TonemappingOperator.Hable)
  55461. defines += "HABLE_TONEMAPPING";
  55462. else if (_this._operator === TonemappingOperator.Reinhard)
  55463. defines += "REINHARD_TONEMAPPING";
  55464. else if (_this._operator === TonemappingOperator.HejiDawson)
  55465. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  55466. else if (_this._operator === TonemappingOperator.Photographic)
  55467. defines += "PHOTOGRAPHIC_TONEMAPPING";
  55468. //sadly a second call to create the effect.
  55469. _this.updateEffect(defines);
  55470. _this.onApply = function (effect) {
  55471. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  55472. };
  55473. return _this;
  55474. }
  55475. return TonemapPostProcess;
  55476. }(BABYLON.PostProcess));
  55477. BABYLON.TonemapPostProcess = TonemapPostProcess;
  55478. })(BABYLON || (BABYLON = {}));
  55479. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  55480. var BABYLON;
  55481. (function (BABYLON) {
  55482. var DisplayPassPostProcess = (function (_super) {
  55483. __extends(DisplayPassPostProcess, _super);
  55484. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  55485. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  55486. }
  55487. return DisplayPassPostProcess;
  55488. }(BABYLON.PostProcess));
  55489. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  55490. })(BABYLON || (BABYLON = {}));
  55491. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  55492. var BABYLON;
  55493. (function (BABYLON) {
  55494. var HighlightsPostProcess = (function (_super) {
  55495. __extends(HighlightsPostProcess, _super);
  55496. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  55497. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55498. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  55499. }
  55500. return HighlightsPostProcess;
  55501. }(BABYLON.PostProcess));
  55502. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  55503. })(BABYLON || (BABYLON = {}));
  55504. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  55505. var BABYLON;
  55506. (function (BABYLON) {
  55507. var ImageProcessingPostProcess = (function (_super) {
  55508. __extends(ImageProcessingPostProcess, _super);
  55509. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  55510. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55511. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  55512. _this._fromLinearSpace = true;
  55513. /**
  55514. * Defines cache preventing GC.
  55515. */
  55516. _this._defines = {
  55517. IMAGEPROCESSING: false,
  55518. VIGNETTE: false,
  55519. VIGNETTEBLENDMODEMULTIPLY: false,
  55520. VIGNETTEBLENDMODEOPAQUE: false,
  55521. TONEMAPPING: false,
  55522. CONTRAST: false,
  55523. COLORCURVES: false,
  55524. COLORGRADING: false,
  55525. FROMLINEARSPACE: false,
  55526. SAMPLER3DGREENDEPTH: false,
  55527. SAMPLER3DBGRMAP: false,
  55528. IMAGEPROCESSINGPOSTPROCESS: false,
  55529. EXPOSURE: false,
  55530. };
  55531. // Setup the default processing configuration to the scene.
  55532. _this._attachImageProcessingConfiguration(null, true);
  55533. _this.imageProcessingConfiguration.applyByPostProcess = true;
  55534. _this.onApply = function (effect) {
  55535. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  55536. };
  55537. return _this;
  55538. }
  55539. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  55540. /**
  55541. * Gets the image processing configuration used either in this material.
  55542. */
  55543. get: function () {
  55544. return this._imageProcessingConfiguration;
  55545. },
  55546. /**
  55547. * Sets the Default image processing configuration used either in the this material.
  55548. *
  55549. * If sets to null, the scene one is in use.
  55550. */
  55551. set: function (value) {
  55552. this._attachImageProcessingConfiguration(value);
  55553. },
  55554. enumerable: true,
  55555. configurable: true
  55556. });
  55557. /**
  55558. * Attaches a new image processing configuration to the PBR Material.
  55559. * @param configuration
  55560. */
  55561. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  55562. var _this = this;
  55563. if (doNotBuild === void 0) { doNotBuild = false; }
  55564. if (configuration === this._imageProcessingConfiguration) {
  55565. return;
  55566. }
  55567. // Detaches observer.
  55568. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  55569. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  55570. }
  55571. // Pick the scene configuration if needed.
  55572. if (!configuration) {
  55573. var camera = this.getCamera();
  55574. var scene = camera ? camera.getScene() : BABYLON.Engine.LastCreatedScene;
  55575. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  55576. }
  55577. else {
  55578. this._imageProcessingConfiguration = configuration;
  55579. }
  55580. // Attaches observer.
  55581. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  55582. _this._updateParameters();
  55583. });
  55584. // Ensure the effect will be rebuilt.
  55585. if (!doNotBuild) {
  55586. this._updateParameters();
  55587. }
  55588. };
  55589. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  55590. /**
  55591. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  55592. */
  55593. get: function () {
  55594. return this.imageProcessingConfiguration.colorCurves;
  55595. },
  55596. /**
  55597. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  55598. */
  55599. set: function (value) {
  55600. this.imageProcessingConfiguration.colorCurves = value;
  55601. },
  55602. enumerable: true,
  55603. configurable: true
  55604. });
  55605. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  55606. /**
  55607. * Gets wether the color curves effect is enabled.
  55608. */
  55609. get: function () {
  55610. return this.imageProcessingConfiguration.colorCurvesEnabled;
  55611. },
  55612. /**
  55613. * Sets wether the color curves effect is enabled.
  55614. */
  55615. set: function (value) {
  55616. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  55617. },
  55618. enumerable: true,
  55619. configurable: true
  55620. });
  55621. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  55622. /**
  55623. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  55624. */
  55625. get: function () {
  55626. return this.imageProcessingConfiguration.colorGradingTexture;
  55627. },
  55628. /**
  55629. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  55630. */
  55631. set: function (value) {
  55632. this.imageProcessingConfiguration.colorGradingTexture = value;
  55633. },
  55634. enumerable: true,
  55635. configurable: true
  55636. });
  55637. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  55638. /**
  55639. * Gets wether the color grading effect is enabled.
  55640. */
  55641. get: function () {
  55642. return this.imageProcessingConfiguration.colorGradingEnabled;
  55643. },
  55644. /**
  55645. * Gets wether the color grading effect is enabled.
  55646. */
  55647. set: function (value) {
  55648. this.imageProcessingConfiguration.colorGradingEnabled = value;
  55649. },
  55650. enumerable: true,
  55651. configurable: true
  55652. });
  55653. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  55654. /**
  55655. * Gets exposure used in the effect.
  55656. */
  55657. get: function () {
  55658. return this.imageProcessingConfiguration.exposure;
  55659. },
  55660. /**
  55661. * Sets exposure used in the effect.
  55662. */
  55663. set: function (value) {
  55664. this.imageProcessingConfiguration.exposure = value;
  55665. },
  55666. enumerable: true,
  55667. configurable: true
  55668. });
  55669. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  55670. /**
  55671. * Gets wether tonemapping is enabled or not.
  55672. */
  55673. get: function () {
  55674. return this._imageProcessingConfiguration.toneMappingEnabled;
  55675. },
  55676. /**
  55677. * Sets wether tonemapping is enabled or not
  55678. */
  55679. set: function (value) {
  55680. this._imageProcessingConfiguration.toneMappingEnabled = value;
  55681. },
  55682. enumerable: true,
  55683. configurable: true
  55684. });
  55685. ;
  55686. ;
  55687. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  55688. /**
  55689. * Gets contrast used in the effect.
  55690. */
  55691. get: function () {
  55692. return this.imageProcessingConfiguration.contrast;
  55693. },
  55694. /**
  55695. * Sets contrast used in the effect.
  55696. */
  55697. set: function (value) {
  55698. this.imageProcessingConfiguration.contrast = value;
  55699. },
  55700. enumerable: true,
  55701. configurable: true
  55702. });
  55703. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  55704. /**
  55705. * Gets Vignette stretch size.
  55706. */
  55707. get: function () {
  55708. return this.imageProcessingConfiguration.vignetteStretch;
  55709. },
  55710. /**
  55711. * Sets Vignette stretch size.
  55712. */
  55713. set: function (value) {
  55714. this.imageProcessingConfiguration.vignetteStretch = value;
  55715. },
  55716. enumerable: true,
  55717. configurable: true
  55718. });
  55719. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  55720. /**
  55721. * Gets Vignette centre X Offset.
  55722. */
  55723. get: function () {
  55724. return this.imageProcessingConfiguration.vignetteCentreX;
  55725. },
  55726. /**
  55727. * Sets Vignette centre X Offset.
  55728. */
  55729. set: function (value) {
  55730. this.imageProcessingConfiguration.vignetteCentreX = value;
  55731. },
  55732. enumerable: true,
  55733. configurable: true
  55734. });
  55735. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  55736. /**
  55737. * Gets Vignette centre Y Offset.
  55738. */
  55739. get: function () {
  55740. return this.imageProcessingConfiguration.vignetteCentreY;
  55741. },
  55742. /**
  55743. * Sets Vignette centre Y Offset.
  55744. */
  55745. set: function (value) {
  55746. this.imageProcessingConfiguration.vignetteCentreY = value;
  55747. },
  55748. enumerable: true,
  55749. configurable: true
  55750. });
  55751. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  55752. /**
  55753. * Gets Vignette weight or intensity of the vignette effect.
  55754. */
  55755. get: function () {
  55756. return this.imageProcessingConfiguration.vignetteWeight;
  55757. },
  55758. /**
  55759. * Sets Vignette weight or intensity of the vignette effect.
  55760. */
  55761. set: function (value) {
  55762. this.imageProcessingConfiguration.vignetteWeight = value;
  55763. },
  55764. enumerable: true,
  55765. configurable: true
  55766. });
  55767. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  55768. /**
  55769. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  55770. * if vignetteEnabled is set to true.
  55771. */
  55772. get: function () {
  55773. return this.imageProcessingConfiguration.vignetteColor;
  55774. },
  55775. /**
  55776. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  55777. * if vignetteEnabled is set to true.
  55778. */
  55779. set: function (value) {
  55780. this.imageProcessingConfiguration.vignetteColor = value;
  55781. },
  55782. enumerable: true,
  55783. configurable: true
  55784. });
  55785. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  55786. /**
  55787. * Gets Camera field of view used by the Vignette effect.
  55788. */
  55789. get: function () {
  55790. return this.imageProcessingConfiguration.vignetteCameraFov;
  55791. },
  55792. /**
  55793. * Sets Camera field of view used by the Vignette effect.
  55794. */
  55795. set: function (value) {
  55796. this.imageProcessingConfiguration.vignetteCameraFov = value;
  55797. },
  55798. enumerable: true,
  55799. configurable: true
  55800. });
  55801. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  55802. /**
  55803. * Gets the vignette blend mode allowing different kind of effect.
  55804. */
  55805. get: function () {
  55806. return this.imageProcessingConfiguration.vignetteBlendMode;
  55807. },
  55808. /**
  55809. * Sets the vignette blend mode allowing different kind of effect.
  55810. */
  55811. set: function (value) {
  55812. this.imageProcessingConfiguration.vignetteBlendMode = value;
  55813. },
  55814. enumerable: true,
  55815. configurable: true
  55816. });
  55817. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  55818. /**
  55819. * Gets wether the vignette effect is enabled.
  55820. */
  55821. get: function () {
  55822. return this.imageProcessingConfiguration.vignetteEnabled;
  55823. },
  55824. /**
  55825. * Sets wether the vignette effect is enabled.
  55826. */
  55827. set: function (value) {
  55828. this.imageProcessingConfiguration.vignetteEnabled = value;
  55829. },
  55830. enumerable: true,
  55831. configurable: true
  55832. });
  55833. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  55834. /**
  55835. * Gets wether the input of the processing is in Gamma or Linear Space.
  55836. */
  55837. get: function () {
  55838. return this._fromLinearSpace;
  55839. },
  55840. /**
  55841. * Sets wether the input of the processing is in Gamma or Linear Space.
  55842. */
  55843. set: function (value) {
  55844. if (this._fromLinearSpace === value) {
  55845. return;
  55846. }
  55847. this._fromLinearSpace = value;
  55848. this._updateParameters();
  55849. },
  55850. enumerable: true,
  55851. configurable: true
  55852. });
  55853. ImageProcessingPostProcess.prototype.getClassName = function () {
  55854. return "ImageProcessingPostProcess";
  55855. };
  55856. ImageProcessingPostProcess.prototype._updateParameters = function () {
  55857. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  55858. this.imageProcessingConfiguration.prepareDefines(this._defines);
  55859. var defines = "";
  55860. for (var define in this._defines) {
  55861. if (this._defines[define]) {
  55862. defines += "#define " + define + ";\r\n";
  55863. }
  55864. }
  55865. var samplers = ["textureSampler"];
  55866. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  55867. var uniforms = ["scale"];
  55868. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  55869. this.updateEffect(defines, uniforms, samplers);
  55870. };
  55871. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  55872. _super.prototype.dispose.call(this, camera);
  55873. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  55874. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  55875. }
  55876. this.imageProcessingConfiguration.applyByPostProcess = false;
  55877. };
  55878. __decorate([
  55879. BABYLON.serialize()
  55880. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  55881. return ImageProcessingPostProcess;
  55882. }(BABYLON.PostProcess));
  55883. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  55884. })(BABYLON || (BABYLON = {}));
  55885. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  55886. var BABYLON;
  55887. (function (BABYLON) {
  55888. var BlurPostProcess = (function (_super) {
  55889. __extends(BlurPostProcess, _super);
  55890. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  55891. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55892. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55893. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  55894. _this.direction = direction;
  55895. _this._packedFloat = false;
  55896. _this.onApplyObservable.add(function (effect) {
  55897. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  55898. });
  55899. _this.kernel = kernel;
  55900. return _this;
  55901. }
  55902. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  55903. /**
  55904. * Gets the length in pixels of the blur sample region
  55905. */
  55906. get: function () {
  55907. return this._idealKernel;
  55908. },
  55909. /**
  55910. * Sets the length in pixels of the blur sample region
  55911. */
  55912. set: function (v) {
  55913. if (this._idealKernel === v) {
  55914. return;
  55915. }
  55916. v = Math.max(v, 1);
  55917. this._idealKernel = v;
  55918. this._kernel = this._nearestBestKernel(v);
  55919. this._updateParameters();
  55920. },
  55921. enumerable: true,
  55922. configurable: true
  55923. });
  55924. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  55925. /**
  55926. * Gets wether or not the blur is unpacking/repacking floats
  55927. */
  55928. get: function () {
  55929. return this._packedFloat;
  55930. },
  55931. /**
  55932. * Sets wether or not the blur needs to unpack/repack floats
  55933. */
  55934. set: function (v) {
  55935. if (this._packedFloat === v) {
  55936. return;
  55937. }
  55938. this._packedFloat = v;
  55939. this._updateParameters();
  55940. },
  55941. enumerable: true,
  55942. configurable: true
  55943. });
  55944. BlurPostProcess.prototype._updateParameters = function () {
  55945. // Generate sampling offsets and weights
  55946. var N = this._kernel;
  55947. var centerIndex = (N - 1) / 2;
  55948. // Generate Gaussian sampling weights over kernel
  55949. var offsets = [];
  55950. var weights = [];
  55951. var totalWeight = 0;
  55952. for (var i = 0; i < N; i++) {
  55953. var u = i / (N - 1);
  55954. var w = this._gaussianWeight(u * 2.0 - 1);
  55955. offsets[i] = (i - centerIndex);
  55956. weights[i] = w;
  55957. totalWeight += w;
  55958. }
  55959. // Normalize weights
  55960. for (var i = 0; i < weights.length; i++) {
  55961. weights[i] /= totalWeight;
  55962. }
  55963. // Optimize: combine samples to take advantage of hardware linear sampling
  55964. // Walk from left to center, combining pairs (symmetrically)
  55965. var linearSamplingWeights = [];
  55966. var linearSamplingOffsets = [];
  55967. var linearSamplingMap = [];
  55968. for (var i = 0; i <= centerIndex; i += 2) {
  55969. var j = Math.min(i + 1, Math.floor(centerIndex));
  55970. var singleCenterSample = i === j;
  55971. if (singleCenterSample) {
  55972. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  55973. }
  55974. else {
  55975. var sharedCell = j === centerIndex;
  55976. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  55977. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  55978. if (offsetLinear === 0) {
  55979. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  55980. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  55981. }
  55982. else {
  55983. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  55984. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  55985. }
  55986. }
  55987. }
  55988. for (var i = 0; i < linearSamplingMap.length; i++) {
  55989. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  55990. linearSamplingWeights[i] = linearSamplingMap[i].w;
  55991. }
  55992. // Replace with optimized
  55993. offsets = linearSamplingOffsets;
  55994. weights = linearSamplingWeights;
  55995. // Generate shaders
  55996. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  55997. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  55998. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  55999. var defines = "";
  56000. for (var i = 0; i < varyingCount; i++) {
  56001. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  56002. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  56003. }
  56004. var depCount = 0;
  56005. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  56006. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  56007. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  56008. depCount++;
  56009. }
  56010. if (this.packedFloat) {
  56011. defines += "#define PACKEDFLOAT 1";
  56012. }
  56013. this.updateEffect(defines, null, null, {
  56014. varyingCount: varyingCount,
  56015. depCount: depCount
  56016. });
  56017. };
  56018. /**
  56019. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  56020. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  56021. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  56022. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  56023. * The gaps between physical kernels are compensated for in the weighting of the samples
  56024. * @param idealKernel Ideal blur kernel.
  56025. * @return Nearest best kernel.
  56026. */
  56027. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  56028. var v = Math.round(idealKernel);
  56029. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  56030. var k = _a[_i];
  56031. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  56032. return Math.max(k, 3);
  56033. }
  56034. }
  56035. return Math.max(v, 3);
  56036. };
  56037. /**
  56038. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  56039. * @param x The point on the Gaussian distribution to sample.
  56040. * @return the value of the Gaussian function at x.
  56041. */
  56042. BlurPostProcess.prototype._gaussianWeight = function (x) {
  56043. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  56044. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  56045. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  56046. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  56047. // truncated at around 1.3% of peak strength.
  56048. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  56049. var sigma = (1 / 3);
  56050. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  56051. var exponent = -((x * x) / (2.0 * sigma * sigma));
  56052. var weight = (1.0 / denominator) * Math.exp(exponent);
  56053. return weight;
  56054. };
  56055. /**
  56056. * Generates a string that can be used as a floating point number in GLSL.
  56057. * @param x Value to print.
  56058. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  56059. * @return GLSL float string.
  56060. */
  56061. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  56062. if (decimalFigures === void 0) { decimalFigures = 8; }
  56063. return x.toFixed(decimalFigures).replace(/0+$/, '');
  56064. };
  56065. return BlurPostProcess;
  56066. }(BABYLON.PostProcess));
  56067. BABYLON.BlurPostProcess = BlurPostProcess;
  56068. })(BABYLON || (BABYLON = {}));
  56069. //# sourceMappingURL=babylon.blurPostProcess.js.map
  56070. /// <reference path="..\babylon.node.ts" />
  56071. var BABYLON;
  56072. (function (BABYLON) {
  56073. var Bone = (function (_super) {
  56074. __extends(Bone, _super);
  56075. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  56076. if (parentBone === void 0) { parentBone = null; }
  56077. var _this = _super.call(this, name, skeleton.getScene()) || this;
  56078. _this.name = name;
  56079. _this.children = new Array();
  56080. _this.animations = new Array();
  56081. _this._worldTransform = new BABYLON.Matrix();
  56082. _this._absoluteTransform = new BABYLON.Matrix();
  56083. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  56084. _this._scaleMatrix = BABYLON.Matrix.Identity();
  56085. _this._scaleVector = BABYLON.Vector3.One();
  56086. _this._negateScaleChildren = BABYLON.Vector3.One();
  56087. _this._scalingDeterminant = 1;
  56088. _this._skeleton = skeleton;
  56089. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  56090. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  56091. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  56092. _this._index = index;
  56093. skeleton.bones.push(_this);
  56094. _this.setParent(parentBone, false);
  56095. _this._updateDifferenceMatrix();
  56096. return _this;
  56097. }
  56098. Object.defineProperty(Bone.prototype, "_matrix", {
  56099. get: function () {
  56100. return this._localMatrix;
  56101. },
  56102. set: function (val) {
  56103. if (this._localMatrix) {
  56104. this._localMatrix.copyFrom(val);
  56105. }
  56106. else {
  56107. this._localMatrix = val;
  56108. }
  56109. },
  56110. enumerable: true,
  56111. configurable: true
  56112. });
  56113. // Members
  56114. Bone.prototype.getSkeleton = function () {
  56115. return this._skeleton;
  56116. };
  56117. Bone.prototype.getParent = function () {
  56118. return this._parent;
  56119. };
  56120. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  56121. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  56122. if (this._parent === parent) {
  56123. return;
  56124. }
  56125. if (this._parent) {
  56126. var index = this._parent.children.indexOf(this);
  56127. if (index !== -1) {
  56128. this._parent.children.splice(index);
  56129. }
  56130. }
  56131. this._parent = parent;
  56132. if (this._parent) {
  56133. this._parent.children.push(this);
  56134. }
  56135. if (updateDifferenceMatrix) {
  56136. this._updateDifferenceMatrix();
  56137. }
  56138. };
  56139. Bone.prototype.getLocalMatrix = function () {
  56140. return this._localMatrix;
  56141. };
  56142. Bone.prototype.getBaseMatrix = function () {
  56143. return this._baseMatrix;
  56144. };
  56145. Bone.prototype.getRestPose = function () {
  56146. return this._restPose;
  56147. };
  56148. Bone.prototype.returnToRest = function () {
  56149. this.updateMatrix(this._restPose.clone());
  56150. };
  56151. Bone.prototype.getWorldMatrix = function () {
  56152. return this._worldTransform;
  56153. };
  56154. Bone.prototype.getInvertedAbsoluteTransform = function () {
  56155. return this._invertedAbsoluteTransform;
  56156. };
  56157. Bone.prototype.getAbsoluteTransform = function () {
  56158. return this._absoluteTransform;
  56159. };
  56160. Object.defineProperty(Bone.prototype, "position", {
  56161. // Properties (matches AbstractMesh properties)
  56162. get: function () {
  56163. return this.getPosition();
  56164. },
  56165. set: function (newPosition) {
  56166. this.setPosition(newPosition);
  56167. },
  56168. enumerable: true,
  56169. configurable: true
  56170. });
  56171. Object.defineProperty(Bone.prototype, "rotation", {
  56172. get: function () {
  56173. return this.getRotation();
  56174. },
  56175. set: function (newRotation) {
  56176. this.setRotation(newRotation);
  56177. },
  56178. enumerable: true,
  56179. configurable: true
  56180. });
  56181. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  56182. get: function () {
  56183. return this.getRotationQuaternion();
  56184. },
  56185. set: function (newRotation) {
  56186. this.setRotationQuaternion(newRotation);
  56187. },
  56188. enumerable: true,
  56189. configurable: true
  56190. });
  56191. Object.defineProperty(Bone.prototype, "scaling", {
  56192. get: function () {
  56193. return this.getScale();
  56194. },
  56195. set: function (newScaling) {
  56196. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  56197. },
  56198. enumerable: true,
  56199. configurable: true
  56200. });
  56201. // Methods
  56202. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  56203. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  56204. this._baseMatrix = matrix.clone();
  56205. this._localMatrix = matrix.clone();
  56206. this._skeleton._markAsDirty();
  56207. if (updateDifferenceMatrix) {
  56208. this._updateDifferenceMatrix();
  56209. }
  56210. };
  56211. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  56212. if (!rootMatrix) {
  56213. rootMatrix = this._baseMatrix;
  56214. }
  56215. if (this._parent) {
  56216. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  56217. }
  56218. else {
  56219. this._absoluteTransform.copyFrom(rootMatrix);
  56220. }
  56221. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  56222. for (var index = 0; index < this.children.length; index++) {
  56223. this.children[index]._updateDifferenceMatrix();
  56224. }
  56225. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  56226. };
  56227. Bone.prototype.markAsDirty = function () {
  56228. this._currentRenderId++;
  56229. this._skeleton._markAsDirty();
  56230. };
  56231. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  56232. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  56233. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  56234. // all animation may be coming from a library skeleton, so may need to create animation
  56235. if (this.animations.length === 0) {
  56236. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  56237. this.animations[0].setKeys([]);
  56238. }
  56239. // get animation info / verify there is such a range from the source bone
  56240. var sourceRange = source.animations[0].getRange(rangeName);
  56241. if (!sourceRange) {
  56242. return false;
  56243. }
  56244. var from = sourceRange.from;
  56245. var to = sourceRange.to;
  56246. var sourceKeys = source.animations[0].getKeys();
  56247. // rescaling prep
  56248. var sourceBoneLength = source.length;
  56249. var sourceParent = source.getParent();
  56250. var parent = this.getParent();
  56251. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  56252. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  56253. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  56254. var destKeys = this.animations[0].getKeys();
  56255. // loop vars declaration
  56256. var orig;
  56257. var origTranslation;
  56258. var mat;
  56259. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  56260. orig = sourceKeys[key];
  56261. if (orig.frame >= from && orig.frame <= to) {
  56262. if (rescaleAsRequired) {
  56263. mat = orig.value.clone();
  56264. // scale based on parent ratio, when bone has parent
  56265. if (parentScalingReqd) {
  56266. origTranslation = mat.getTranslation();
  56267. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  56268. // scale based on skeleton dimension ratio when root bone, and value is passed
  56269. }
  56270. else if (dimensionsScalingReqd) {
  56271. origTranslation = mat.getTranslation();
  56272. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  56273. // use original when root bone, and no data for skelDimensionsRatio
  56274. }
  56275. else {
  56276. mat = orig.value;
  56277. }
  56278. }
  56279. else {
  56280. mat = orig.value;
  56281. }
  56282. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  56283. }
  56284. }
  56285. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  56286. return true;
  56287. };
  56288. /**
  56289. * Translate the bone in local or world space.
  56290. * @param vec The amount to translate the bone.
  56291. * @param space The space that the translation is in.
  56292. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56293. */
  56294. Bone.prototype.translate = function (vec, space, mesh) {
  56295. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56296. var lm = this.getLocalMatrix();
  56297. if (space == BABYLON.Space.LOCAL) {
  56298. lm.m[12] += vec.x;
  56299. lm.m[13] += vec.y;
  56300. lm.m[14] += vec.z;
  56301. }
  56302. else {
  56303. var wm;
  56304. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  56305. if (mesh) {
  56306. wm = mesh.getWorldMatrix();
  56307. }
  56308. this._skeleton.computeAbsoluteTransforms();
  56309. var tmat = Bone._tmpMats[0];
  56310. var tvec = Bone._tmpVecs[0];
  56311. if (mesh) {
  56312. tmat.copyFrom(this._parent.getAbsoluteTransform());
  56313. tmat.multiplyToRef(wm, tmat);
  56314. }
  56315. else {
  56316. tmat.copyFrom(this._parent.getAbsoluteTransform());
  56317. }
  56318. tmat.m[12] = 0;
  56319. tmat.m[13] = 0;
  56320. tmat.m[14] = 0;
  56321. tmat.invert();
  56322. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  56323. lm.m[12] += tvec.x;
  56324. lm.m[13] += tvec.y;
  56325. lm.m[14] += tvec.z;
  56326. }
  56327. this.markAsDirty();
  56328. };
  56329. /**
  56330. * Set the postion of the bone in local or world space.
  56331. * @param position The position to set the bone.
  56332. * @param space The space that the position is in.
  56333. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56334. */
  56335. Bone.prototype.setPosition = function (position, space, mesh) {
  56336. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56337. var lm = this.getLocalMatrix();
  56338. if (space == BABYLON.Space.LOCAL) {
  56339. lm.m[12] = position.x;
  56340. lm.m[13] = position.y;
  56341. lm.m[14] = position.z;
  56342. }
  56343. else {
  56344. var wm;
  56345. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  56346. if (mesh) {
  56347. wm = mesh.getWorldMatrix();
  56348. }
  56349. this._skeleton.computeAbsoluteTransforms();
  56350. var tmat = Bone._tmpMats[0];
  56351. var vec = Bone._tmpVecs[0];
  56352. if (mesh) {
  56353. tmat.copyFrom(this._parent.getAbsoluteTransform());
  56354. tmat.multiplyToRef(wm, tmat);
  56355. }
  56356. else {
  56357. tmat.copyFrom(this._parent.getAbsoluteTransform());
  56358. }
  56359. tmat.invert();
  56360. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  56361. lm.m[12] = vec.x;
  56362. lm.m[13] = vec.y;
  56363. lm.m[14] = vec.z;
  56364. }
  56365. this.markAsDirty();
  56366. };
  56367. /**
  56368. * Set the absolute postion of the bone (world space).
  56369. * @param position The position to set the bone.
  56370. * @param mesh The mesh that this bone is attached to.
  56371. */
  56372. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  56373. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  56374. };
  56375. /**
  56376. * Set the scale of the bone on the x, y and z axes.
  56377. * @param x The scale of the bone on the x axis.
  56378. * @param x The scale of the bone on the y axis.
  56379. * @param z The scale of the bone on the z axis.
  56380. * @param scaleChildren Set this to true if children of the bone should be scaled.
  56381. */
  56382. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  56383. if (scaleChildren === void 0) { scaleChildren = false; }
  56384. if (this.animations[0] && !this.animations[0].isStopped()) {
  56385. if (!scaleChildren) {
  56386. this._negateScaleChildren.x = 1 / x;
  56387. this._negateScaleChildren.y = 1 / y;
  56388. this._negateScaleChildren.z = 1 / z;
  56389. }
  56390. this._syncScaleVector();
  56391. }
  56392. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  56393. };
  56394. /**
  56395. * Scale the bone on the x, y and z axes.
  56396. * @param x The amount to scale the bone on the x axis.
  56397. * @param x The amount to scale the bone on the y axis.
  56398. * @param z The amount to scale the bone on the z axis.
  56399. * @param scaleChildren Set this to true if children of the bone should be scaled.
  56400. */
  56401. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  56402. if (scaleChildren === void 0) { scaleChildren = false; }
  56403. var locMat = this.getLocalMatrix();
  56404. var origLocMat = Bone._tmpMats[0];
  56405. origLocMat.copyFrom(locMat);
  56406. var origLocMatInv = Bone._tmpMats[1];
  56407. origLocMatInv.copyFrom(origLocMat);
  56408. origLocMatInv.invert();
  56409. var scaleMat = Bone._tmpMats[2];
  56410. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  56411. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  56412. this._scaleVector.x *= x;
  56413. this._scaleVector.y *= y;
  56414. this._scaleVector.z *= z;
  56415. locMat.multiplyToRef(origLocMatInv, locMat);
  56416. locMat.multiplyToRef(scaleMat, locMat);
  56417. locMat.multiplyToRef(origLocMat, locMat);
  56418. var parent = this.getParent();
  56419. if (parent) {
  56420. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  56421. }
  56422. else {
  56423. this.getAbsoluteTransform().copyFrom(locMat);
  56424. }
  56425. var len = this.children.length;
  56426. scaleMat.invert();
  56427. for (var i = 0; i < len; i++) {
  56428. var child = this.children[i];
  56429. var cm = child.getLocalMatrix();
  56430. cm.multiplyToRef(scaleMat, cm);
  56431. var lm = child.getLocalMatrix();
  56432. lm.m[12] *= x;
  56433. lm.m[13] *= y;
  56434. lm.m[14] *= z;
  56435. }
  56436. this.computeAbsoluteTransforms();
  56437. if (scaleChildren) {
  56438. for (var i = 0; i < len; i++) {
  56439. this.children[i].scale(x, y, z, scaleChildren);
  56440. }
  56441. }
  56442. this.markAsDirty();
  56443. };
  56444. /**
  56445. * Set the yaw, pitch, and roll of the bone in local or world space.
  56446. * @param yaw The rotation of the bone on the y axis.
  56447. * @param pitch The rotation of the bone on the x axis.
  56448. * @param roll The rotation of the bone on the z axis.
  56449. * @param space The space that the axes of rotation are in.
  56450. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56451. */
  56452. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  56453. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56454. var rotMat = Bone._tmpMats[0];
  56455. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  56456. var rotMatInv = Bone._tmpMats[1];
  56457. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  56458. rotMatInv.multiplyToRef(rotMat, rotMat);
  56459. this._rotateWithMatrix(rotMat, space, mesh);
  56460. };
  56461. /**
  56462. * Rotate the bone on an axis in local or world space.
  56463. * @param axis The axis to rotate the bone on.
  56464. * @param amount The amount to rotate the bone.
  56465. * @param space The space that the axis is in.
  56466. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56467. */
  56468. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  56469. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56470. var rmat = Bone._tmpMats[0];
  56471. rmat.m[12] = 0;
  56472. rmat.m[13] = 0;
  56473. rmat.m[14] = 0;
  56474. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  56475. this._rotateWithMatrix(rmat, space, mesh);
  56476. };
  56477. /**
  56478. * Set the rotation of the bone to a particular axis angle in local or world space.
  56479. * @param axis The axis to rotate the bone on.
  56480. * @param angle The angle that the bone should be rotated to.
  56481. * @param space The space that the axis is in.
  56482. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56483. */
  56484. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  56485. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56486. var rotMat = Bone._tmpMats[0];
  56487. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  56488. var rotMatInv = Bone._tmpMats[1];
  56489. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  56490. rotMatInv.multiplyToRef(rotMat, rotMat);
  56491. this._rotateWithMatrix(rotMat, space, mesh);
  56492. };
  56493. /**
  56494. * Set the euler rotation of the bone in local of world space.
  56495. * @param rotation The euler rotation that the bone should be set to.
  56496. * @param space The space that the rotation is in.
  56497. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56498. */
  56499. Bone.prototype.setRotation = function (rotation, space, mesh) {
  56500. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56501. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  56502. };
  56503. /**
  56504. * Set the quaternion rotation of the bone in local of world space.
  56505. * @param quat The quaternion rotation that the bone should be set to.
  56506. * @param space The space that the rotation is in.
  56507. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56508. */
  56509. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  56510. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56511. var rotMatInv = Bone._tmpMats[0];
  56512. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  56513. var rotMat = Bone._tmpMats[1];
  56514. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  56515. rotMatInv.multiplyToRef(rotMat, rotMat);
  56516. this._rotateWithMatrix(rotMat, space, mesh);
  56517. };
  56518. /**
  56519. * Set the rotation matrix of the bone in local of world space.
  56520. * @param rotMat The rotation matrix that the bone should be set to.
  56521. * @param space The space that the rotation is in.
  56522. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56523. */
  56524. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  56525. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56526. var rotMatInv = Bone._tmpMats[0];
  56527. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  56528. var rotMat2 = Bone._tmpMats[1];
  56529. rotMat2.copyFrom(rotMat);
  56530. rotMatInv.multiplyToRef(rotMat, rotMat2);
  56531. this._rotateWithMatrix(rotMat2, space, mesh);
  56532. };
  56533. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  56534. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56535. var lmat = this.getLocalMatrix();
  56536. var lx = lmat.m[12];
  56537. var ly = lmat.m[13];
  56538. var lz = lmat.m[14];
  56539. var parent = this.getParent();
  56540. var parentScale = Bone._tmpMats[3];
  56541. var parentScaleInv = Bone._tmpMats[4];
  56542. if (parent) {
  56543. if (space == BABYLON.Space.WORLD) {
  56544. if (mesh) {
  56545. parentScale.copyFrom(mesh.getWorldMatrix());
  56546. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  56547. }
  56548. else {
  56549. parentScale.copyFrom(parent.getAbsoluteTransform());
  56550. }
  56551. }
  56552. else {
  56553. parentScale = parent._scaleMatrix;
  56554. }
  56555. parentScaleInv.copyFrom(parentScale);
  56556. parentScaleInv.invert();
  56557. lmat.multiplyToRef(parentScale, lmat);
  56558. lmat.multiplyToRef(rmat, lmat);
  56559. lmat.multiplyToRef(parentScaleInv, lmat);
  56560. }
  56561. else {
  56562. if (space == BABYLON.Space.WORLD && mesh) {
  56563. parentScale.copyFrom(mesh.getWorldMatrix());
  56564. parentScaleInv.copyFrom(parentScale);
  56565. parentScaleInv.invert();
  56566. lmat.multiplyToRef(parentScale, lmat);
  56567. lmat.multiplyToRef(rmat, lmat);
  56568. lmat.multiplyToRef(parentScaleInv, lmat);
  56569. }
  56570. else {
  56571. lmat.multiplyToRef(rmat, lmat);
  56572. }
  56573. }
  56574. lmat.m[12] = lx;
  56575. lmat.m[13] = ly;
  56576. lmat.m[14] = lz;
  56577. this.computeAbsoluteTransforms();
  56578. this.markAsDirty();
  56579. };
  56580. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  56581. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56582. if (space == BABYLON.Space.WORLD) {
  56583. var scaleMatrix = Bone._tmpMats[2];
  56584. scaleMatrix.copyFrom(this._scaleMatrix);
  56585. rotMatInv.copyFrom(this.getAbsoluteTransform());
  56586. if (mesh) {
  56587. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  56588. var meshScale = Bone._tmpMats[3];
  56589. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  56590. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  56591. }
  56592. rotMatInv.invert();
  56593. scaleMatrix.m[0] *= this._scalingDeterminant;
  56594. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  56595. }
  56596. else {
  56597. rotMatInv.copyFrom(this.getLocalMatrix());
  56598. rotMatInv.invert();
  56599. var scaleMatrix = Bone._tmpMats[2];
  56600. scaleMatrix.copyFrom(this._scaleMatrix);
  56601. if (this._parent) {
  56602. var pscaleMatrix = Bone._tmpMats[3];
  56603. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  56604. pscaleMatrix.invert();
  56605. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  56606. }
  56607. else {
  56608. scaleMatrix.m[0] *= this._scalingDeterminant;
  56609. }
  56610. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  56611. }
  56612. };
  56613. /**
  56614. * Get the scale of the bone
  56615. * @returns the scale of the bone
  56616. */
  56617. Bone.prototype.getScale = function () {
  56618. return this._scaleVector.clone();
  56619. };
  56620. /**
  56621. * Copy the scale of the bone to a vector3.
  56622. * @param result The vector3 to copy the scale to
  56623. */
  56624. Bone.prototype.getScaleToRef = function (result) {
  56625. result.copyFrom(this._scaleVector);
  56626. };
  56627. /**
  56628. * Get the position of the bone in local or world space.
  56629. * @param space The space that the returned position is in.
  56630. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56631. * @returns The position of the bone
  56632. */
  56633. Bone.prototype.getPosition = function (space, mesh) {
  56634. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56635. var pos = BABYLON.Vector3.Zero();
  56636. this.getPositionToRef(space, mesh, pos);
  56637. return pos;
  56638. };
  56639. /**
  56640. * Copy the position of the bone to a vector3 in local or world space.
  56641. * @param space The space that the returned position is in.
  56642. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56643. * @param result The vector3 to copy the position to.
  56644. */
  56645. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  56646. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56647. if (space == BABYLON.Space.LOCAL) {
  56648. var lm = this.getLocalMatrix();
  56649. result.x = lm.m[12];
  56650. result.y = lm.m[13];
  56651. result.z = lm.m[14];
  56652. }
  56653. else {
  56654. var wm;
  56655. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  56656. if (mesh) {
  56657. wm = mesh.getWorldMatrix();
  56658. }
  56659. this._skeleton.computeAbsoluteTransforms();
  56660. var tmat = Bone._tmpMats[0];
  56661. if (mesh) {
  56662. tmat.copyFrom(this.getAbsoluteTransform());
  56663. tmat.multiplyToRef(wm, tmat);
  56664. }
  56665. else {
  56666. tmat = this.getAbsoluteTransform();
  56667. }
  56668. result.x = tmat.m[12];
  56669. result.y = tmat.m[13];
  56670. result.z = tmat.m[14];
  56671. }
  56672. };
  56673. /**
  56674. * Get the absolute position of the bone (world space).
  56675. * @param mesh The mesh that this bone is attached to.
  56676. * @returns The absolute position of the bone
  56677. */
  56678. Bone.prototype.getAbsolutePosition = function (mesh) {
  56679. var pos = BABYLON.Vector3.Zero();
  56680. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  56681. return pos;
  56682. };
  56683. /**
  56684. * Copy the absolute position of the bone (world space) to the result param.
  56685. * @param mesh The mesh that this bone is attached to.
  56686. * @param result The vector3 to copy the absolute position to.
  56687. */
  56688. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  56689. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  56690. };
  56691. /**
  56692. * Compute the absolute transforms of this bone and its children.
  56693. */
  56694. Bone.prototype.computeAbsoluteTransforms = function () {
  56695. if (this._parent) {
  56696. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  56697. }
  56698. else {
  56699. this._absoluteTransform.copyFrom(this._localMatrix);
  56700. var poseMatrix = this._skeleton.getPoseMatrix();
  56701. if (poseMatrix) {
  56702. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  56703. }
  56704. }
  56705. var children = this.children;
  56706. var len = children.length;
  56707. for (var i = 0; i < len; i++) {
  56708. children[i].computeAbsoluteTransforms();
  56709. }
  56710. };
  56711. Bone.prototype._syncScaleVector = function () {
  56712. var lm = this.getLocalMatrix();
  56713. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  56714. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  56715. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  56716. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  56717. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  56718. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  56719. this._scaleVector.x = xs * Math.sqrt(xsq);
  56720. this._scaleVector.y = ys * Math.sqrt(ysq);
  56721. this._scaleVector.z = zs * Math.sqrt(zsq);
  56722. if (this._parent) {
  56723. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  56724. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  56725. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  56726. }
  56727. 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);
  56728. };
  56729. /**
  56730. * Get the world direction from an axis that is in the local space of the bone.
  56731. * @param localAxis The local direction that is used to compute the world direction.
  56732. * @param mesh The mesh that this bone is attached to.
  56733. * @returns The world direction
  56734. */
  56735. Bone.prototype.getDirection = function (localAxis, mesh) {
  56736. var result = BABYLON.Vector3.Zero();
  56737. this.getDirectionToRef(localAxis, mesh, result);
  56738. return result;
  56739. };
  56740. /**
  56741. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  56742. * @param localAxis The local direction that is used to compute the world direction.
  56743. * @param mesh The mesh that this bone is attached to.
  56744. * @param result The vector3 that the world direction will be copied to.
  56745. */
  56746. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  56747. var wm;
  56748. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  56749. if (mesh) {
  56750. wm = mesh.getWorldMatrix();
  56751. }
  56752. this._skeleton.computeAbsoluteTransforms();
  56753. var mat = Bone._tmpMats[0];
  56754. mat.copyFrom(this.getAbsoluteTransform());
  56755. if (mesh) {
  56756. mat.multiplyToRef(wm, mat);
  56757. }
  56758. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  56759. result.normalize();
  56760. };
  56761. /**
  56762. * Get the euler rotation of the bone in local or world space.
  56763. * @param space The space that the rotation should be in.
  56764. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56765. * @returns The euler rotation
  56766. */
  56767. Bone.prototype.getRotation = function (space, mesh) {
  56768. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56769. var result = BABYLON.Vector3.Zero();
  56770. this.getRotationToRef(space, mesh, result);
  56771. return result;
  56772. };
  56773. /**
  56774. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  56775. * @param space The space that the rotation should be in.
  56776. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56777. * @param result The vector3 that the rotation should be copied to.
  56778. */
  56779. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  56780. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56781. var quat = Bone._tmpQuat;
  56782. this.getRotationQuaternionToRef(space, mesh, quat);
  56783. quat.toEulerAnglesToRef(result);
  56784. };
  56785. /**
  56786. * Get the quaternion rotation of the bone in either local or world space.
  56787. * @param space The space that the rotation should be in.
  56788. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56789. * @returns The quaternion rotation
  56790. */
  56791. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  56792. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56793. var result = BABYLON.Quaternion.Identity();
  56794. this.getRotationQuaternionToRef(space, mesh, result);
  56795. return result;
  56796. };
  56797. /**
  56798. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  56799. * @param space The space that the rotation should be in.
  56800. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56801. * @param result The quaternion that the rotation should be copied to.
  56802. */
  56803. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  56804. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56805. if (space == BABYLON.Space.LOCAL) {
  56806. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  56807. }
  56808. else {
  56809. var mat = Bone._tmpMats[0];
  56810. var amat = this.getAbsoluteTransform();
  56811. if (mesh) {
  56812. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  56813. }
  56814. else {
  56815. mat.copyFrom(amat);
  56816. }
  56817. mat.m[0] *= this._scalingDeterminant;
  56818. mat.m[1] *= this._scalingDeterminant;
  56819. mat.m[2] *= this._scalingDeterminant;
  56820. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  56821. }
  56822. };
  56823. /**
  56824. * Get the rotation matrix of the bone in local or world space.
  56825. * @param space The space that the rotation should be in.
  56826. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56827. * @returns The rotation matrix
  56828. */
  56829. Bone.prototype.getRotationMatrix = function (space, mesh) {
  56830. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56831. var result = BABYLON.Matrix.Identity();
  56832. this.getRotationMatrixToRef(space, mesh, result);
  56833. return result;
  56834. };
  56835. /**
  56836. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  56837. * @param space The space that the rotation should be in.
  56838. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56839. * @param result The quaternion that the rotation should be copied to.
  56840. */
  56841. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  56842. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56843. if (space == BABYLON.Space.LOCAL) {
  56844. this.getLocalMatrix().getRotationMatrixToRef(result);
  56845. }
  56846. else {
  56847. var mat = Bone._tmpMats[0];
  56848. var amat = this.getAbsoluteTransform();
  56849. if (mesh) {
  56850. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  56851. }
  56852. else {
  56853. mat.copyFrom(amat);
  56854. }
  56855. mat.m[0] *= this._scalingDeterminant;
  56856. mat.m[1] *= this._scalingDeterminant;
  56857. mat.m[2] *= this._scalingDeterminant;
  56858. mat.getRotationMatrixToRef(result);
  56859. }
  56860. };
  56861. /**
  56862. * Get the world position of a point that is in the local space of the bone.
  56863. * @param position The local position
  56864. * @param mesh The mesh that this bone is attached to.
  56865. * @returns The world position
  56866. */
  56867. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  56868. var result = BABYLON.Vector3.Zero();
  56869. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  56870. return result;
  56871. };
  56872. /**
  56873. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  56874. * @param position The local position
  56875. * @param mesh The mesh that this bone is attached to.
  56876. * @param result The vector3 that the world position should be copied to.
  56877. */
  56878. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  56879. var wm;
  56880. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  56881. if (mesh) {
  56882. wm = mesh.getWorldMatrix();
  56883. }
  56884. this._skeleton.computeAbsoluteTransforms();
  56885. var tmat = Bone._tmpMats[0];
  56886. if (mesh) {
  56887. tmat.copyFrom(this.getAbsoluteTransform());
  56888. tmat.multiplyToRef(wm, tmat);
  56889. }
  56890. else {
  56891. tmat = this.getAbsoluteTransform();
  56892. }
  56893. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  56894. };
  56895. /**
  56896. * Get the local position of a point that is in world space.
  56897. * @param position The world position
  56898. * @param mesh The mesh that this bone is attached to.
  56899. * @returns The local position
  56900. */
  56901. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  56902. var result = BABYLON.Vector3.Zero();
  56903. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  56904. return result;
  56905. };
  56906. /**
  56907. * Get the local position of a point that is in world space and copy it to the result param.
  56908. * @param position The world position
  56909. * @param mesh The mesh that this bone is attached to.
  56910. * @param result The vector3 that the local position should be copied to.
  56911. */
  56912. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  56913. var wm;
  56914. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  56915. if (mesh) {
  56916. wm = mesh.getWorldMatrix();
  56917. }
  56918. this._skeleton.computeAbsoluteTransforms();
  56919. var tmat = Bone._tmpMats[0];
  56920. tmat.copyFrom(this.getAbsoluteTransform());
  56921. if (mesh) {
  56922. tmat.multiplyToRef(wm, tmat);
  56923. }
  56924. tmat.invert();
  56925. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  56926. };
  56927. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56928. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  56929. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  56930. return Bone;
  56931. }(BABYLON.Node));
  56932. BABYLON.Bone = Bone;
  56933. })(BABYLON || (BABYLON = {}));
  56934. //# sourceMappingURL=babylon.bone.js.map
  56935. var BABYLON;
  56936. (function (BABYLON) {
  56937. var BoneIKController = (function () {
  56938. function BoneIKController(mesh, bone, options) {
  56939. this.targetPosition = BABYLON.Vector3.Zero();
  56940. this.poleTargetPosition = BABYLON.Vector3.Zero();
  56941. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  56942. this.poleAngle = 0;
  56943. this.slerpAmount = 1;
  56944. this._bone1Quat = BABYLON.Quaternion.Identity();
  56945. this._bone1Mat = BABYLON.Matrix.Identity();
  56946. this._bone2Ang = Math.PI;
  56947. this._maxAngle = Math.PI;
  56948. this._rightHandedSystem = false;
  56949. this._bendAxis = BABYLON.Vector3.Right();
  56950. this._slerping = false;
  56951. this._adjustRoll = 0;
  56952. this._bone2 = bone;
  56953. this._bone1 = bone.getParent();
  56954. this.mesh = mesh;
  56955. var bonePos = bone.getPosition();
  56956. if (bone.getAbsoluteTransform().determinant() > 0) {
  56957. this._rightHandedSystem = true;
  56958. this._bendAxis.x = 0;
  56959. this._bendAxis.y = 0;
  56960. this._bendAxis.z = -1;
  56961. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  56962. this._adjustRoll = Math.PI * .5;
  56963. this._bendAxis.z = 1;
  56964. }
  56965. }
  56966. if (this._bone1.length) {
  56967. var boneScale1 = this._bone1.getScale();
  56968. var boneScale2 = this._bone2.getScale();
  56969. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  56970. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  56971. }
  56972. else if (this._bone1.children[0]) {
  56973. mesh.computeWorldMatrix(true);
  56974. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  56975. var pos2 = this._bone2.getAbsolutePosition(mesh);
  56976. var pos3 = this._bone1.getAbsolutePosition(mesh);
  56977. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  56978. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  56979. }
  56980. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  56981. this.maxAngle = Math.PI;
  56982. if (options) {
  56983. if (options.targetMesh) {
  56984. this.targetMesh = options.targetMesh;
  56985. this.targetMesh.computeWorldMatrix(true);
  56986. }
  56987. if (options.poleTargetMesh) {
  56988. this.poleTargetMesh = options.poleTargetMesh;
  56989. this.poleTargetMesh.computeWorldMatrix(true);
  56990. }
  56991. else if (options.poleTargetBone) {
  56992. this.poleTargetBone = options.poleTargetBone;
  56993. }
  56994. else if (this._bone1.getParent()) {
  56995. this.poleTargetBone = this._bone1.getParent();
  56996. }
  56997. if (options.poleTargetLocalOffset) {
  56998. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  56999. }
  57000. if (options.poleAngle) {
  57001. this.poleAngle = options.poleAngle;
  57002. }
  57003. if (options.bendAxis) {
  57004. this._bendAxis.copyFrom(options.bendAxis);
  57005. }
  57006. if (options.maxAngle) {
  57007. this.maxAngle = options.maxAngle;
  57008. }
  57009. if (options.slerpAmount) {
  57010. this.slerpAmount = options.slerpAmount;
  57011. }
  57012. }
  57013. }
  57014. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  57015. get: function () {
  57016. return this._maxAngle;
  57017. },
  57018. set: function (value) {
  57019. this._setMaxAngle(value);
  57020. },
  57021. enumerable: true,
  57022. configurable: true
  57023. });
  57024. BoneIKController.prototype._setMaxAngle = function (ang) {
  57025. if (ang < 0) {
  57026. ang = 0;
  57027. }
  57028. if (ang > Math.PI || ang == undefined) {
  57029. ang = Math.PI;
  57030. }
  57031. this._maxAngle = ang;
  57032. var a = this._bone1Length;
  57033. var b = this._bone2Length;
  57034. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  57035. };
  57036. BoneIKController.prototype.update = function () {
  57037. var bone1 = this._bone1;
  57038. var target = this.targetPosition;
  57039. var poleTarget = this.poleTargetPosition;
  57040. var mat1 = BoneIKController._tmpMats[0];
  57041. var mat2 = BoneIKController._tmpMats[1];
  57042. if (this.targetMesh) {
  57043. target.copyFrom(this.targetMesh.getAbsolutePosition());
  57044. }
  57045. if (this.poleTargetBone) {
  57046. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  57047. }
  57048. else if (this.poleTargetMesh) {
  57049. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  57050. }
  57051. var bonePos = BoneIKController._tmpVecs[0];
  57052. var zaxis = BoneIKController._tmpVecs[1];
  57053. var xaxis = BoneIKController._tmpVecs[2];
  57054. var yaxis = BoneIKController._tmpVecs[3];
  57055. var upAxis = BoneIKController._tmpVecs[4];
  57056. var _tmpQuat = BoneIKController._tmpQuat;
  57057. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  57058. poleTarget.subtractToRef(bonePos, upAxis);
  57059. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  57060. upAxis.y = 1;
  57061. }
  57062. else {
  57063. upAxis.normalize();
  57064. }
  57065. target.subtractToRef(bonePos, yaxis);
  57066. yaxis.normalize();
  57067. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  57068. zaxis.normalize();
  57069. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  57070. xaxis.normalize();
  57071. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  57072. var a = this._bone1Length;
  57073. var b = this._bone2Length;
  57074. var c = BABYLON.Vector3.Distance(bonePos, target);
  57075. if (this._maxReach > 0) {
  57076. c = Math.min(this._maxReach, c);
  57077. }
  57078. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  57079. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  57080. if (acosa > 1) {
  57081. acosa = 1;
  57082. }
  57083. if (acosb > 1) {
  57084. acosb = 1;
  57085. }
  57086. if (acosa < -1) {
  57087. acosa = -1;
  57088. }
  57089. if (acosb < -1) {
  57090. acosb = -1;
  57091. }
  57092. var angA = Math.acos(acosa);
  57093. var angB = Math.acos(acosb);
  57094. var angC = -angA - angB;
  57095. if (this._rightHandedSystem) {
  57096. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  57097. mat2.multiplyToRef(mat1, mat1);
  57098. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  57099. mat2.multiplyToRef(mat1, mat1);
  57100. }
  57101. else {
  57102. var _tmpVec = BoneIKController._tmpVecs[5];
  57103. _tmpVec.copyFrom(this._bendAxis);
  57104. _tmpVec.x *= -1;
  57105. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  57106. mat2.multiplyToRef(mat1, mat1);
  57107. }
  57108. if (this.poleAngle) {
  57109. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  57110. mat1.multiplyToRef(mat2, mat1);
  57111. }
  57112. if (this.slerpAmount < 1) {
  57113. if (!this._slerping) {
  57114. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  57115. }
  57116. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  57117. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  57118. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  57119. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  57120. this._slerping = true;
  57121. }
  57122. else {
  57123. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  57124. this._bone1Mat.copyFrom(mat1);
  57125. this._slerping = false;
  57126. }
  57127. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  57128. this._bone2Ang = angC;
  57129. };
  57130. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57131. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  57132. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  57133. return BoneIKController;
  57134. }());
  57135. BABYLON.BoneIKController = BoneIKController;
  57136. })(BABYLON || (BABYLON = {}));
  57137. //# sourceMappingURL=babylon.boneIKController.js.map
  57138. var BABYLON;
  57139. (function (BABYLON) {
  57140. var BoneLookController = (function () {
  57141. /**
  57142. * Create a BoneLookController
  57143. * @param mesh the mesh that the bone belongs to
  57144. * @param bone the bone that will be looking to the target
  57145. * @param target the target Vector3 to look at
  57146. * @param settings optional settings:
  57147. * - maxYaw: the maximum angle the bone will yaw to
  57148. * - minYaw: the minimum angle the bone will yaw to
  57149. * - maxPitch: the maximum angle the bone will pitch to
  57150. * - minPitch: the minimum angle the bone will yaw to
  57151. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  57152. * - upAxis: the up axis of the coordinate system
  57153. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  57154. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  57155. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  57156. * - adjustYaw: used to make an adjustment to the yaw of the bone
  57157. * - adjustPitch: used to make an adjustment to the pitch of the bone
  57158. * - adjustRoll: used to make an adjustment to the roll of the bone
  57159. **/
  57160. function BoneLookController(mesh, bone, target, options) {
  57161. /**
  57162. * The up axis of the coordinate system that is used when the bone is rotated.
  57163. */
  57164. this.upAxis = BABYLON.Vector3.Up();
  57165. /**
  57166. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  57167. */
  57168. this.upAxisSpace = BABYLON.Space.LOCAL;
  57169. /**
  57170. * Used to make an adjustment to the yaw of the bone.
  57171. */
  57172. this.adjustYaw = 0;
  57173. /**
  57174. * Used to make an adjustment to the pitch of the bone.
  57175. */
  57176. this.adjustPitch = 0;
  57177. /**
  57178. * Used to make an adjustment to the roll of the bone.
  57179. */
  57180. this.adjustRoll = 0;
  57181. /**
  57182. * 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).
  57183. */
  57184. this.slerpAmount = 1;
  57185. this._boneQuat = BABYLON.Quaternion.Identity();
  57186. this._slerping = false;
  57187. this._firstFrameSkipped = false;
  57188. this._fowardAxis = BABYLON.Vector3.Forward();
  57189. this.mesh = mesh;
  57190. this.bone = bone;
  57191. this.target = target;
  57192. if (options) {
  57193. if (options.adjustYaw) {
  57194. this.adjustYaw = options.adjustYaw;
  57195. }
  57196. if (options.adjustPitch) {
  57197. this.adjustPitch = options.adjustPitch;
  57198. }
  57199. if (options.adjustRoll) {
  57200. this.adjustRoll = options.adjustRoll;
  57201. }
  57202. if (options.maxYaw != null) {
  57203. this.maxYaw = options.maxYaw;
  57204. }
  57205. else {
  57206. this.maxYaw = Math.PI;
  57207. }
  57208. if (options.minYaw != null) {
  57209. this.minYaw = options.minYaw;
  57210. }
  57211. else {
  57212. this.minYaw = -Math.PI;
  57213. }
  57214. if (options.maxPitch != null) {
  57215. this.maxPitch = options.maxPitch;
  57216. }
  57217. else {
  57218. this.maxPitch = Math.PI;
  57219. }
  57220. if (options.minPitch != null) {
  57221. this.minPitch = options.minPitch;
  57222. }
  57223. else {
  57224. this.minPitch = -Math.PI;
  57225. }
  57226. if (options.slerpAmount != null) {
  57227. this.slerpAmount = options.slerpAmount;
  57228. }
  57229. if (options.upAxis != null) {
  57230. this.upAxis = options.upAxis;
  57231. }
  57232. if (options.upAxisSpace != null) {
  57233. this.upAxisSpace = options.upAxisSpace;
  57234. }
  57235. if (options.yawAxis != null || options.pitchAxis != null) {
  57236. var newYawAxis = BABYLON.Axis.Y;
  57237. var newPitchAxis = BABYLON.Axis.X;
  57238. if (options.yawAxis != null) {
  57239. newYawAxis = options.yawAxis.clone();
  57240. newYawAxis.normalize();
  57241. }
  57242. if (options.pitchAxis != null) {
  57243. newPitchAxis = options.pitchAxis.clone();
  57244. newPitchAxis.normalize();
  57245. }
  57246. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  57247. this._transformYawPitch = BABYLON.Matrix.Identity();
  57248. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  57249. this._transformYawPitchInv = this._transformYawPitch.clone();
  57250. this._transformYawPitch.invert();
  57251. }
  57252. }
  57253. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  57254. this.upAxisSpace = BABYLON.Space.LOCAL;
  57255. }
  57256. }
  57257. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  57258. /**
  57259. * Get/set the minimum yaw angle that the bone can look to.
  57260. */
  57261. get: function () {
  57262. return this._minYaw;
  57263. },
  57264. set: function (value) {
  57265. this._minYaw = value;
  57266. this._minYawSin = Math.sin(value);
  57267. this._minYawCos = Math.cos(value);
  57268. if (this._maxYaw != null) {
  57269. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  57270. this._yawRange = this._maxYaw - this._minYaw;
  57271. }
  57272. },
  57273. enumerable: true,
  57274. configurable: true
  57275. });
  57276. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  57277. /**
  57278. * Get/set the maximum yaw angle that the bone can look to.
  57279. */
  57280. get: function () {
  57281. return this._maxYaw;
  57282. },
  57283. set: function (value) {
  57284. this._maxYaw = value;
  57285. this._maxYawSin = Math.sin(value);
  57286. this._maxYawCos = Math.cos(value);
  57287. if (this._minYaw != null) {
  57288. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  57289. this._yawRange = this._maxYaw - this._minYaw;
  57290. }
  57291. },
  57292. enumerable: true,
  57293. configurable: true
  57294. });
  57295. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  57296. /**
  57297. * Get/set the minimum pitch angle that the bone can look to.
  57298. */
  57299. get: function () {
  57300. return this._minPitch;
  57301. },
  57302. set: function (value) {
  57303. this._minPitch = value;
  57304. this._minPitchTan = Math.tan(value);
  57305. },
  57306. enumerable: true,
  57307. configurable: true
  57308. });
  57309. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  57310. /**
  57311. * Get/set the maximum pitch angle that the bone can look to.
  57312. */
  57313. get: function () {
  57314. return this._maxPitch;
  57315. },
  57316. set: function (value) {
  57317. this._maxPitch = value;
  57318. this._maxPitchTan = Math.tan(value);
  57319. },
  57320. enumerable: true,
  57321. configurable: true
  57322. });
  57323. /**
  57324. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  57325. */
  57326. BoneLookController.prototype.update = function () {
  57327. //skip the first frame when slerping so that the mesh rotation is correct
  57328. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  57329. this._firstFrameSkipped = true;
  57330. return;
  57331. }
  57332. var bone = this.bone;
  57333. var bonePos = BoneLookController._tmpVecs[0];
  57334. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  57335. var target = this.target;
  57336. var _tmpMat1 = BoneLookController._tmpMats[0];
  57337. var _tmpMat2 = BoneLookController._tmpMats[1];
  57338. var mesh = this.mesh;
  57339. var parentBone = bone.getParent();
  57340. var upAxis = BoneLookController._tmpVecs[1];
  57341. upAxis.copyFrom(this.upAxis);
  57342. if (this.upAxisSpace == BABYLON.Space.BONE) {
  57343. if (this._transformYawPitch) {
  57344. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  57345. }
  57346. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  57347. }
  57348. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  57349. mesh.getDirectionToRef(upAxis, upAxis);
  57350. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  57351. upAxis.normalize();
  57352. }
  57353. }
  57354. var checkYaw = false;
  57355. var checkPitch = false;
  57356. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  57357. checkYaw = true;
  57358. }
  57359. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  57360. checkPitch = true;
  57361. }
  57362. if (checkYaw || checkPitch) {
  57363. var spaceMat = BoneLookController._tmpMats[2];
  57364. var spaceMatInv = BoneLookController._tmpMats[3];
  57365. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  57366. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  57367. }
  57368. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  57369. spaceMat.copyFrom(mesh.getWorldMatrix());
  57370. }
  57371. else {
  57372. var forwardAxis = BoneLookController._tmpVecs[2];
  57373. forwardAxis.copyFrom(this._fowardAxis);
  57374. if (this._transformYawPitch) {
  57375. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  57376. }
  57377. if (parentBone) {
  57378. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  57379. }
  57380. else {
  57381. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  57382. }
  57383. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  57384. rightAxis.normalize();
  57385. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  57386. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  57387. }
  57388. spaceMat.invertToRef(spaceMatInv);
  57389. var xzlen;
  57390. if (checkPitch) {
  57391. var localTarget = BoneLookController._tmpVecs[3];
  57392. target.subtractToRef(bonePos, localTarget);
  57393. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  57394. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  57395. var pitch = Math.atan2(localTarget.y, xzlen);
  57396. var newPitch = pitch;
  57397. if (pitch > this._maxPitch) {
  57398. localTarget.y = this._maxPitchTan * xzlen;
  57399. newPitch = this._maxPitch;
  57400. }
  57401. else if (pitch < this._minPitch) {
  57402. localTarget.y = this._minPitchTan * xzlen;
  57403. newPitch = this._minPitch;
  57404. }
  57405. if (pitch != newPitch) {
  57406. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  57407. localTarget.addInPlace(bonePos);
  57408. target = localTarget;
  57409. }
  57410. }
  57411. if (checkYaw) {
  57412. var localTarget = BoneLookController._tmpVecs[4];
  57413. target.subtractToRef(bonePos, localTarget);
  57414. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  57415. var yaw = Math.atan2(localTarget.x, localTarget.z);
  57416. var newYaw = yaw;
  57417. if (yaw > this._maxYaw || yaw < this._minYaw) {
  57418. if (xzlen == null) {
  57419. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  57420. }
  57421. if (this._yawRange > Math.PI) {
  57422. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  57423. localTarget.z = this._maxYawCos * xzlen;
  57424. localTarget.x = this._maxYawSin * xzlen;
  57425. newYaw = this._maxYaw;
  57426. }
  57427. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  57428. localTarget.z = this._minYawCos * xzlen;
  57429. localTarget.x = this._minYawSin * xzlen;
  57430. newYaw = this._minYaw;
  57431. }
  57432. }
  57433. else {
  57434. if (yaw > this._maxYaw) {
  57435. localTarget.z = this._maxYawCos * xzlen;
  57436. localTarget.x = this._maxYawSin * xzlen;
  57437. newYaw = this._maxYaw;
  57438. }
  57439. else if (yaw < this._minYaw) {
  57440. localTarget.z = this._minYawCos * xzlen;
  57441. localTarget.x = this._minYawSin * xzlen;
  57442. newYaw = this._minYaw;
  57443. }
  57444. }
  57445. }
  57446. if (this._slerping && this._yawRange > Math.PI) {
  57447. //are we going to be crossing into the min/max region?
  57448. var boneFwd = BoneLookController._tmpVecs[8];
  57449. boneFwd.copyFrom(BABYLON.Axis.Z);
  57450. if (this._transformYawPitch) {
  57451. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  57452. }
  57453. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  57454. this._boneQuat.toRotationMatrix(boneRotMat);
  57455. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  57456. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  57457. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  57458. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  57459. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  57460. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  57461. if (angBtwTar > angBtwMidYaw) {
  57462. if (xzlen == null) {
  57463. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  57464. }
  57465. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  57466. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  57467. if (angBtwMin < angBtwMax) {
  57468. newYaw = boneYaw + Math.PI * .75;
  57469. localTarget.z = Math.cos(newYaw) * xzlen;
  57470. localTarget.x = Math.sin(newYaw) * xzlen;
  57471. }
  57472. else {
  57473. newYaw = boneYaw - Math.PI * .75;
  57474. localTarget.z = Math.cos(newYaw) * xzlen;
  57475. localTarget.x = Math.sin(newYaw) * xzlen;
  57476. }
  57477. }
  57478. }
  57479. if (yaw != newYaw) {
  57480. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  57481. localTarget.addInPlace(bonePos);
  57482. target = localTarget;
  57483. }
  57484. }
  57485. }
  57486. var zaxis = BoneLookController._tmpVecs[5];
  57487. var xaxis = BoneLookController._tmpVecs[6];
  57488. var yaxis = BoneLookController._tmpVecs[7];
  57489. var _tmpQuat = BoneLookController._tmpQuat;
  57490. target.subtractToRef(bonePos, zaxis);
  57491. zaxis.normalize();
  57492. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  57493. xaxis.normalize();
  57494. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  57495. yaxis.normalize();
  57496. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  57497. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  57498. return;
  57499. }
  57500. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  57501. return;
  57502. }
  57503. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  57504. return;
  57505. }
  57506. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  57507. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  57508. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  57509. }
  57510. if (this.slerpAmount < 1) {
  57511. if (!this._slerping) {
  57512. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  57513. }
  57514. if (this._transformYawPitch) {
  57515. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  57516. }
  57517. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  57518. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  57519. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  57520. this._slerping = true;
  57521. }
  57522. else {
  57523. if (this._transformYawPitch) {
  57524. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  57525. }
  57526. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  57527. this._slerping = false;
  57528. }
  57529. };
  57530. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  57531. var angDiff = ang2 - ang1;
  57532. angDiff %= Math.PI * 2;
  57533. if (angDiff > Math.PI) {
  57534. angDiff -= Math.PI * 2;
  57535. }
  57536. else if (angDiff < -Math.PI) {
  57537. angDiff += Math.PI * 2;
  57538. }
  57539. return angDiff;
  57540. };
  57541. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  57542. ang1 %= (2 * Math.PI);
  57543. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  57544. ang2 %= (2 * Math.PI);
  57545. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  57546. var ab = 0;
  57547. if (ang1 < ang2) {
  57548. ab = ang2 - ang1;
  57549. }
  57550. else {
  57551. ab = ang1 - ang2;
  57552. }
  57553. if (ab > Math.PI) {
  57554. ab = Math.PI * 2 - ab;
  57555. }
  57556. return ab;
  57557. };
  57558. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  57559. ang %= (2 * Math.PI);
  57560. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  57561. ang1 %= (2 * Math.PI);
  57562. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  57563. ang2 %= (2 * Math.PI);
  57564. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  57565. if (ang1 < ang2) {
  57566. if (ang > ang1 && ang < ang2) {
  57567. return true;
  57568. }
  57569. }
  57570. else {
  57571. if (ang > ang2 && ang < ang1) {
  57572. return true;
  57573. }
  57574. }
  57575. return false;
  57576. };
  57577. 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()];
  57578. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  57579. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  57580. return BoneLookController;
  57581. }());
  57582. BABYLON.BoneLookController = BoneLookController;
  57583. })(BABYLON || (BABYLON = {}));
  57584. //# sourceMappingURL=babylon.boneLookController.js.map
  57585. var BABYLON;
  57586. (function (BABYLON) {
  57587. var Skeleton = (function () {
  57588. function Skeleton(name, id, scene) {
  57589. this.name = name;
  57590. this.id = id;
  57591. this.bones = new Array();
  57592. this.needInitialSkinMatrix = false;
  57593. this._isDirty = true;
  57594. this._meshesWithPoseMatrix = new Array();
  57595. this._identity = BABYLON.Matrix.Identity();
  57596. this._ranges = {};
  57597. this._lastAbsoluteTransformsUpdateId = -1;
  57598. // Events
  57599. /**
  57600. * An event triggered before computing the skeleton's matrices
  57601. * @type {BABYLON.Observable}
  57602. */
  57603. this.onBeforeComputeObservable = new BABYLON.Observable();
  57604. this.bones = [];
  57605. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57606. scene.skeletons.push(this);
  57607. //make sure it will recalculate the matrix next time prepare is called.
  57608. this._isDirty = true;
  57609. }
  57610. // Members
  57611. Skeleton.prototype.getTransformMatrices = function (mesh) {
  57612. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  57613. return mesh._bonesTransformMatrices;
  57614. }
  57615. if (!this._transformMatrices) {
  57616. this.prepare();
  57617. }
  57618. return this._transformMatrices;
  57619. };
  57620. Skeleton.prototype.getScene = function () {
  57621. return this._scene;
  57622. };
  57623. // Methods
  57624. /**
  57625. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  57626. */
  57627. Skeleton.prototype.toString = function (fullDetails) {
  57628. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  57629. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  57630. if (fullDetails) {
  57631. ret += ", Ranges: {";
  57632. var first = true;
  57633. for (var name_1 in this._ranges) {
  57634. if (first) {
  57635. ret += ", ";
  57636. first = false;
  57637. }
  57638. ret += name_1;
  57639. }
  57640. ret += "}";
  57641. }
  57642. return ret;
  57643. };
  57644. /**
  57645. * Get bone's index searching by name
  57646. * @param {string} name is bone's name to search for
  57647. * @return {number} Indice of the bone. Returns -1 if not found
  57648. */
  57649. Skeleton.prototype.getBoneIndexByName = function (name) {
  57650. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  57651. if (this.bones[boneIndex].name === name) {
  57652. return boneIndex;
  57653. }
  57654. }
  57655. return -1;
  57656. };
  57657. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  57658. // check name not already in use
  57659. if (!this._ranges[name]) {
  57660. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  57661. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  57662. if (this.bones[i].animations[0]) {
  57663. this.bones[i].animations[0].createRange(name, from, to);
  57664. }
  57665. }
  57666. }
  57667. };
  57668. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  57669. if (deleteFrames === void 0) { deleteFrames = true; }
  57670. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  57671. if (this.bones[i].animations[0]) {
  57672. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  57673. }
  57674. }
  57675. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  57676. };
  57677. Skeleton.prototype.getAnimationRange = function (name) {
  57678. return this._ranges[name];
  57679. };
  57680. /**
  57681. * Returns as an Array, all AnimationRanges defined on this skeleton
  57682. */
  57683. Skeleton.prototype.getAnimationRanges = function () {
  57684. var animationRanges = [];
  57685. var name;
  57686. var i = 0;
  57687. for (name in this._ranges) {
  57688. animationRanges[i] = this._ranges[name];
  57689. i++;
  57690. }
  57691. return animationRanges;
  57692. };
  57693. /**
  57694. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  57695. */
  57696. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  57697. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  57698. if (this._ranges[name] || !source.getAnimationRange(name)) {
  57699. return false;
  57700. }
  57701. var ret = true;
  57702. var frameOffset = this._getHighestAnimationFrame() + 1;
  57703. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  57704. var boneDict = {};
  57705. var sourceBones = source.bones;
  57706. var nBones;
  57707. var i;
  57708. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  57709. boneDict[sourceBones[i].name] = sourceBones[i];
  57710. }
  57711. if (this.bones.length !== sourceBones.length) {
  57712. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  57713. ret = false;
  57714. }
  57715. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  57716. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  57717. var boneName = this.bones[i].name;
  57718. var sourceBone = boneDict[boneName];
  57719. if (sourceBone) {
  57720. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  57721. }
  57722. else {
  57723. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  57724. ret = false;
  57725. }
  57726. }
  57727. // do not call createAnimationRange(), since it also is done to bones, which was already done
  57728. var range = source.getAnimationRange(name);
  57729. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  57730. return ret;
  57731. };
  57732. Skeleton.prototype.returnToRest = function () {
  57733. for (var index = 0; index < this.bones.length; index++) {
  57734. this.bones[index].returnToRest();
  57735. }
  57736. };
  57737. Skeleton.prototype._getHighestAnimationFrame = function () {
  57738. var ret = 0;
  57739. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  57740. if (this.bones[i].animations[0]) {
  57741. var highest = this.bones[i].animations[0].getHighestFrame();
  57742. if (ret < highest) {
  57743. ret = highest;
  57744. }
  57745. }
  57746. }
  57747. return ret;
  57748. };
  57749. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  57750. var range = this.getAnimationRange(name);
  57751. if (!range) {
  57752. return null;
  57753. }
  57754. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  57755. };
  57756. Skeleton.prototype._markAsDirty = function () {
  57757. this._isDirty = true;
  57758. };
  57759. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  57760. this._meshesWithPoseMatrix.push(mesh);
  57761. };
  57762. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  57763. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  57764. if (index > -1) {
  57765. this._meshesWithPoseMatrix.splice(index, 1);
  57766. }
  57767. };
  57768. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  57769. this.onBeforeComputeObservable.notifyObservers(this);
  57770. for (var index = 0; index < this.bones.length; index++) {
  57771. var bone = this.bones[index];
  57772. var parentBone = bone.getParent();
  57773. if (parentBone) {
  57774. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  57775. }
  57776. else {
  57777. if (initialSkinMatrix) {
  57778. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  57779. }
  57780. else {
  57781. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  57782. }
  57783. }
  57784. if (bone._index !== -1) {
  57785. var mappedIndex = bone._index === undefined ? index : bone._index;
  57786. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  57787. }
  57788. }
  57789. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  57790. };
  57791. Skeleton.prototype.prepare = function () {
  57792. if (!this._isDirty) {
  57793. return;
  57794. }
  57795. if (this.needInitialSkinMatrix) {
  57796. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  57797. var mesh = this._meshesWithPoseMatrix[index];
  57798. var poseMatrix = mesh.getPoseMatrix();
  57799. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  57800. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  57801. }
  57802. if (this._synchronizedWithMesh !== mesh) {
  57803. this._synchronizedWithMesh = mesh;
  57804. // Prepare bones
  57805. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  57806. var bone = this.bones[boneIndex];
  57807. if (!bone.getParent()) {
  57808. var matrix = bone.getBaseMatrix();
  57809. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  57810. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  57811. }
  57812. }
  57813. }
  57814. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  57815. }
  57816. }
  57817. else {
  57818. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  57819. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  57820. }
  57821. this._computeTransformMatrices(this._transformMatrices, null);
  57822. }
  57823. this._isDirty = false;
  57824. this._scene._activeBones.addCount(this.bones.length, false);
  57825. };
  57826. Skeleton.prototype.getAnimatables = function () {
  57827. if (!this._animatables || this._animatables.length !== this.bones.length) {
  57828. this._animatables = [];
  57829. for (var index = 0; index < this.bones.length; index++) {
  57830. this._animatables.push(this.bones[index]);
  57831. }
  57832. }
  57833. return this._animatables;
  57834. };
  57835. Skeleton.prototype.clone = function (name, id) {
  57836. var result = new Skeleton(name, id || name, this._scene);
  57837. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  57838. for (var index = 0; index < this.bones.length; index++) {
  57839. var source = this.bones[index];
  57840. var parentBone = null;
  57841. if (source.getParent()) {
  57842. var parentIndex = this.bones.indexOf(source.getParent());
  57843. parentBone = result.bones[parentIndex];
  57844. }
  57845. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  57846. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  57847. }
  57848. if (this._ranges) {
  57849. result._ranges = {};
  57850. for (var rangeName in this._ranges) {
  57851. result._ranges[rangeName] = this._ranges[rangeName].clone();
  57852. }
  57853. }
  57854. this._isDirty = true;
  57855. return result;
  57856. };
  57857. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  57858. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  57859. this.bones.forEach(function (bone) {
  57860. bone.animations.forEach(function (animation) {
  57861. animation.enableBlending = true;
  57862. animation.blendingSpeed = blendingSpeed;
  57863. });
  57864. });
  57865. };
  57866. Skeleton.prototype.dispose = function () {
  57867. this._meshesWithPoseMatrix = [];
  57868. // Animations
  57869. this.getScene().stopAnimation(this);
  57870. // Remove from scene
  57871. this.getScene().removeSkeleton(this);
  57872. };
  57873. Skeleton.prototype.serialize = function () {
  57874. var serializationObject = {};
  57875. serializationObject.name = this.name;
  57876. serializationObject.id = this.id;
  57877. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  57878. serializationObject.bones = [];
  57879. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  57880. for (var index = 0; index < this.bones.length; index++) {
  57881. var bone = this.bones[index];
  57882. var serializedBone = {
  57883. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  57884. name: bone.name,
  57885. matrix: bone.getBaseMatrix().toArray(),
  57886. rest: bone.getRestPose().toArray()
  57887. };
  57888. serializationObject.bones.push(serializedBone);
  57889. if (bone.length) {
  57890. serializedBone.length = bone.length;
  57891. }
  57892. if (bone.animations && bone.animations.length > 0) {
  57893. serializedBone.animation = bone.animations[0].serialize();
  57894. }
  57895. serializationObject.ranges = [];
  57896. for (var name in this._ranges) {
  57897. var range = {};
  57898. range.name = name;
  57899. range.from = this._ranges[name].from;
  57900. range.to = this._ranges[name].to;
  57901. serializationObject.ranges.push(range);
  57902. }
  57903. }
  57904. return serializationObject;
  57905. };
  57906. Skeleton.Parse = function (parsedSkeleton, scene) {
  57907. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  57908. if (parsedSkeleton.dimensionsAtRest) {
  57909. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  57910. }
  57911. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  57912. var index;
  57913. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  57914. var parsedBone = parsedSkeleton.bones[index];
  57915. var parentBone = null;
  57916. if (parsedBone.parentBoneIndex > -1) {
  57917. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  57918. }
  57919. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  57920. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  57921. if (parsedBone.length) {
  57922. bone.length = parsedBone.length;
  57923. }
  57924. if (parsedBone.animation) {
  57925. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  57926. }
  57927. }
  57928. // placed after bones, so createAnimationRange can cascade down
  57929. if (parsedSkeleton.ranges) {
  57930. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  57931. var data = parsedSkeleton.ranges[index];
  57932. skeleton.createAnimationRange(data.name, data.from, data.to);
  57933. }
  57934. }
  57935. return skeleton;
  57936. };
  57937. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  57938. if (forceUpdate === void 0) { forceUpdate = false; }
  57939. var renderId = this._scene.getRenderId();
  57940. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  57941. this.bones[0].computeAbsoluteTransforms();
  57942. this._lastAbsoluteTransformsUpdateId = renderId;
  57943. }
  57944. };
  57945. Skeleton.prototype.getPoseMatrix = function () {
  57946. var poseMatrix;
  57947. if (this._meshesWithPoseMatrix.length > 0) {
  57948. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  57949. }
  57950. return poseMatrix;
  57951. };
  57952. Skeleton.prototype.sortBones = function () {
  57953. var bones = new Array();
  57954. var visited = new Array(this.bones.length);
  57955. for (var index = 0; index < this.bones.length; index++) {
  57956. this._sortBones(index, bones, visited);
  57957. }
  57958. this.bones = bones;
  57959. };
  57960. Skeleton.prototype._sortBones = function (index, bones, visited) {
  57961. if (visited[index]) {
  57962. return;
  57963. }
  57964. visited[index] = true;
  57965. var bone = this.bones[index];
  57966. if (bone._index === undefined) {
  57967. bone._index = index;
  57968. }
  57969. var parentBone = bone.getParent();
  57970. if (parentBone) {
  57971. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  57972. }
  57973. bones.push(bone);
  57974. };
  57975. return Skeleton;
  57976. }());
  57977. BABYLON.Skeleton = Skeleton;
  57978. })(BABYLON || (BABYLON = {}));
  57979. //# sourceMappingURL=babylon.skeleton.js.map
  57980. var BABYLON;
  57981. (function (BABYLON) {
  57982. var SphericalPolynomial = (function () {
  57983. function SphericalPolynomial() {
  57984. this.x = BABYLON.Vector3.Zero();
  57985. this.y = BABYLON.Vector3.Zero();
  57986. this.z = BABYLON.Vector3.Zero();
  57987. this.xx = BABYLON.Vector3.Zero();
  57988. this.yy = BABYLON.Vector3.Zero();
  57989. this.zz = BABYLON.Vector3.Zero();
  57990. this.xy = BABYLON.Vector3.Zero();
  57991. this.yz = BABYLON.Vector3.Zero();
  57992. this.zx = BABYLON.Vector3.Zero();
  57993. }
  57994. SphericalPolynomial.prototype.addAmbient = function (color) {
  57995. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  57996. this.xx = this.xx.add(colorVector);
  57997. this.yy = this.yy.add(colorVector);
  57998. this.zz = this.zz.add(colorVector);
  57999. };
  58000. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  58001. var result = new SphericalPolynomial();
  58002. result.x = harmonics.L11.scale(1.02333);
  58003. result.y = harmonics.L1_1.scale(1.02333);
  58004. result.z = harmonics.L10.scale(1.02333);
  58005. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  58006. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  58007. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  58008. result.yz = harmonics.L2_1.scale(0.858086);
  58009. result.zx = harmonics.L21.scale(0.858086);
  58010. result.xy = harmonics.L2_2.scale(0.858086);
  58011. result.scale(1.0 / Math.PI);
  58012. return result;
  58013. };
  58014. SphericalPolynomial.prototype.scale = function (scale) {
  58015. this.x = this.x.scale(scale);
  58016. this.y = this.y.scale(scale);
  58017. this.z = this.z.scale(scale);
  58018. this.xx = this.xx.scale(scale);
  58019. this.yy = this.yy.scale(scale);
  58020. this.zz = this.zz.scale(scale);
  58021. this.yz = this.yz.scale(scale);
  58022. this.zx = this.zx.scale(scale);
  58023. this.xy = this.xy.scale(scale);
  58024. };
  58025. return SphericalPolynomial;
  58026. }());
  58027. BABYLON.SphericalPolynomial = SphericalPolynomial;
  58028. var SphericalHarmonics = (function () {
  58029. function SphericalHarmonics() {
  58030. this.L00 = BABYLON.Vector3.Zero();
  58031. this.L1_1 = BABYLON.Vector3.Zero();
  58032. this.L10 = BABYLON.Vector3.Zero();
  58033. this.L11 = BABYLON.Vector3.Zero();
  58034. this.L2_2 = BABYLON.Vector3.Zero();
  58035. this.L2_1 = BABYLON.Vector3.Zero();
  58036. this.L20 = BABYLON.Vector3.Zero();
  58037. this.L21 = BABYLON.Vector3.Zero();
  58038. this.L22 = BABYLON.Vector3.Zero();
  58039. }
  58040. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  58041. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  58042. var c = colorVector.scale(deltaSolidAngle);
  58043. this.L00 = this.L00.add(c.scale(0.282095));
  58044. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  58045. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  58046. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  58047. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  58048. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  58049. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  58050. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  58051. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  58052. };
  58053. SphericalHarmonics.prototype.scale = function (scale) {
  58054. this.L00 = this.L00.scale(scale);
  58055. this.L1_1 = this.L1_1.scale(scale);
  58056. this.L10 = this.L10.scale(scale);
  58057. this.L11 = this.L11.scale(scale);
  58058. this.L2_2 = this.L2_2.scale(scale);
  58059. this.L2_1 = this.L2_1.scale(scale);
  58060. this.L20 = this.L20.scale(scale);
  58061. this.L21 = this.L21.scale(scale);
  58062. this.L22 = this.L22.scale(scale);
  58063. };
  58064. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  58065. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  58066. //
  58067. // E_lm = A_l * L_lm
  58068. //
  58069. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  58070. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  58071. // the scaling factors are given in equation 9.
  58072. // Constant (Band 0)
  58073. this.L00 = this.L00.scale(3.141593);
  58074. // Linear (Band 1)
  58075. this.L1_1 = this.L1_1.scale(2.094395);
  58076. this.L10 = this.L10.scale(2.094395);
  58077. this.L11 = this.L11.scale(2.094395);
  58078. // Quadratic (Band 2)
  58079. this.L2_2 = this.L2_2.scale(0.785398);
  58080. this.L2_1 = this.L2_1.scale(0.785398);
  58081. this.L20 = this.L20.scale(0.785398);
  58082. this.L21 = this.L21.scale(0.785398);
  58083. this.L22 = this.L22.scale(0.785398);
  58084. };
  58085. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  58086. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  58087. // L = (1/pi) * E * rho
  58088. //
  58089. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  58090. this.scale(1.0 / Math.PI);
  58091. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  58092. // (The pixel shader must apply albedo after texture fetches, etc).
  58093. };
  58094. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  58095. var result = new SphericalHarmonics();
  58096. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  58097. result.L1_1 = polynomial.y.scale(0.977204);
  58098. result.L10 = polynomial.z.scale(0.977204);
  58099. result.L11 = polynomial.x.scale(0.977204);
  58100. result.L2_2 = polynomial.xy.scale(1.16538);
  58101. result.L2_1 = polynomial.yz.scale(1.16538);
  58102. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  58103. result.L21 = polynomial.zx.scale(1.16538);
  58104. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  58105. result.scale(Math.PI);
  58106. return result;
  58107. };
  58108. return SphericalHarmonics;
  58109. }());
  58110. BABYLON.SphericalHarmonics = SphericalHarmonics;
  58111. })(BABYLON || (BABYLON = {}));
  58112. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  58113. var BABYLON;
  58114. (function (BABYLON) {
  58115. var Internals;
  58116. (function (Internals) {
  58117. var FileFaceOrientation = (function () {
  58118. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  58119. this.name = name;
  58120. this.worldAxisForNormal = worldAxisForNormal;
  58121. this.worldAxisForFileX = worldAxisForFileX;
  58122. this.worldAxisForFileY = worldAxisForFileY;
  58123. }
  58124. return FileFaceOrientation;
  58125. }());
  58126. ;
  58127. /**
  58128. * Helper class dealing with the extraction of spherical polynomial dataArray
  58129. * from a cube map.
  58130. */
  58131. var CubeMapToSphericalPolynomialTools = (function () {
  58132. function CubeMapToSphericalPolynomialTools() {
  58133. }
  58134. /**
  58135. * Converts a texture to the according Spherical Polynomial data.
  58136. * This extracts the first 3 orders only as they are the only one used in the lighting.
  58137. *
  58138. * @param texture The texture to extract the information from.
  58139. * @return The Spherical Polynomial data.
  58140. */
  58141. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  58142. if (!texture.isCube) {
  58143. // Only supports cube Textures currently.
  58144. return null;
  58145. }
  58146. var size = texture.getSize().width;
  58147. var right = texture.readPixels(0);
  58148. var left = texture.readPixels(1);
  58149. var up;
  58150. var down;
  58151. if (texture.isRenderTarget) {
  58152. up = texture.readPixels(3);
  58153. down = texture.readPixels(2);
  58154. }
  58155. else {
  58156. up = texture.readPixels(2);
  58157. down = texture.readPixels(3);
  58158. }
  58159. var front = texture.readPixels(4);
  58160. var back = texture.readPixels(5);
  58161. var gammaSpace = texture.gammaSpace;
  58162. // Always read as RGBA.
  58163. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  58164. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58165. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58166. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58167. }
  58168. var cubeInfo = {
  58169. size: size,
  58170. right: right,
  58171. left: left,
  58172. up: up,
  58173. down: down,
  58174. front: front,
  58175. back: back,
  58176. format: format,
  58177. type: type,
  58178. gammaSpace: gammaSpace,
  58179. };
  58180. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  58181. };
  58182. /**
  58183. * Converts a cubemap to the according Spherical Polynomial data.
  58184. * This extracts the first 3 orders only as they are the only one used in the lighting.
  58185. *
  58186. * @param cubeInfo The Cube map to extract the information from.
  58187. * @return The Spherical Polynomial data.
  58188. */
  58189. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  58190. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  58191. var totalSolidAngle = 0.0;
  58192. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  58193. var du = 2.0 / cubeInfo.size;
  58194. var dv = du;
  58195. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  58196. var minUV = du * 0.5 - 1.0;
  58197. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  58198. var fileFace = this.FileFaces[faceIndex];
  58199. var dataArray = cubeInfo[fileFace.name];
  58200. var v = minUV;
  58201. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  58202. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  58203. // Because SP is still linear, so summation is fine in that basis.
  58204. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  58205. for (var y = 0; y < cubeInfo.size; y++) {
  58206. var u = minUV;
  58207. for (var x = 0; x < cubeInfo.size; x++) {
  58208. // World direction (not normalised)
  58209. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  58210. worldDirection.normalize();
  58211. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  58212. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  58213. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  58214. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  58215. // Handle Integer types.
  58216. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58217. r /= 255;
  58218. g /= 255;
  58219. b /= 255;
  58220. }
  58221. // Handle Gamma space textures.
  58222. if (cubeInfo.gammaSpace) {
  58223. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  58224. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  58225. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  58226. }
  58227. var color = new BABYLON.Color3(r, g, b);
  58228. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  58229. totalSolidAngle += deltaSolidAngle;
  58230. u += du;
  58231. }
  58232. v += dv;
  58233. }
  58234. }
  58235. // Solid angle for entire sphere is 4*pi
  58236. var sphereSolidAngle = 4.0 * Math.PI;
  58237. // Adjust the solid angle to allow for how many faces we processed.
  58238. var facesProcessed = 6.0;
  58239. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  58240. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  58241. // This is needed because the numerical integration over the cube uses a
  58242. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  58243. // and also to compensate for accumulative error due to float precision in the summation.
  58244. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  58245. sphericalHarmonics.scale(correctionFactor);
  58246. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  58247. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  58248. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  58249. };
  58250. CubeMapToSphericalPolynomialTools.FileFaces = [
  58251. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  58252. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  58253. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  58254. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  58255. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  58256. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  58257. ];
  58258. return CubeMapToSphericalPolynomialTools;
  58259. }());
  58260. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  58261. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58262. })(BABYLON || (BABYLON = {}));
  58263. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  58264. var BABYLON;
  58265. (function (BABYLON) {
  58266. var Internals;
  58267. (function (Internals) {
  58268. /**
  58269. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  58270. */
  58271. var PanoramaToCubeMapTools = (function () {
  58272. function PanoramaToCubeMapTools() {
  58273. }
  58274. /**
  58275. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  58276. *
  58277. * @param float32Array The source data.
  58278. * @param inputWidth The width of the input panorama.
  58279. * @param inputhHeight The height of the input panorama.
  58280. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  58281. * @return The cubemap data
  58282. */
  58283. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  58284. if (!float32Array) {
  58285. throw "ConvertPanoramaToCubemap: input cannot be null";
  58286. }
  58287. if (float32Array.length != inputWidth * inputHeight * 3) {
  58288. throw "ConvertPanoramaToCubemap: input size is wrong";
  58289. }
  58290. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  58291. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  58292. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  58293. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  58294. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  58295. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  58296. return {
  58297. front: textureFront,
  58298. back: textureBack,
  58299. left: textureLeft,
  58300. right: textureRight,
  58301. up: textureUp,
  58302. down: textureDown,
  58303. size: size,
  58304. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  58305. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  58306. gammaSpace: false,
  58307. };
  58308. };
  58309. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  58310. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  58311. var textureArray = new Float32Array(buffer);
  58312. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  58313. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  58314. var dy = 1 / texSize;
  58315. var fy = 0;
  58316. for (var y = 0; y < texSize; y++) {
  58317. var xv1 = faceData[0];
  58318. var xv2 = faceData[2];
  58319. for (var x = 0; x < texSize; x++) {
  58320. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  58321. v.normalize();
  58322. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  58323. // 3 channels per pixels
  58324. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  58325. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  58326. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  58327. xv1 = xv1.add(rotDX1);
  58328. xv2 = xv2.add(rotDX2);
  58329. }
  58330. fy += dy;
  58331. }
  58332. return textureArray;
  58333. };
  58334. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  58335. var theta = Math.atan2(vDir.z, vDir.x);
  58336. var phi = Math.acos(vDir.y);
  58337. while (theta < -Math.PI)
  58338. theta += 2 * Math.PI;
  58339. while (theta > Math.PI)
  58340. theta -= 2 * Math.PI;
  58341. var dx = theta / Math.PI;
  58342. var dy = phi / Math.PI;
  58343. // recenter.
  58344. dx = dx * 0.5 + 0.5;
  58345. var px = Math.round(dx * inputWidth);
  58346. if (px < 0)
  58347. px = 0;
  58348. else if (px >= inputWidth)
  58349. px = inputWidth - 1;
  58350. var py = Math.round(dy * inputHeight);
  58351. if (py < 0)
  58352. py = 0;
  58353. else if (py >= inputHeight)
  58354. py = inputHeight - 1;
  58355. var inputY = (inputHeight - py - 1);
  58356. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  58357. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  58358. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  58359. return {
  58360. r: r,
  58361. g: g,
  58362. b: b
  58363. };
  58364. };
  58365. PanoramaToCubeMapTools.FACE_FRONT = [
  58366. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  58367. new BABYLON.Vector3(1.0, -1.0, -1.0),
  58368. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  58369. new BABYLON.Vector3(1.0, 1.0, -1.0)
  58370. ];
  58371. PanoramaToCubeMapTools.FACE_BACK = [
  58372. new BABYLON.Vector3(1.0, -1.0, 1.0),
  58373. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  58374. new BABYLON.Vector3(1.0, 1.0, 1.0),
  58375. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  58376. ];
  58377. PanoramaToCubeMapTools.FACE_RIGHT = [
  58378. new BABYLON.Vector3(1.0, -1.0, -1.0),
  58379. new BABYLON.Vector3(1.0, -1.0, 1.0),
  58380. new BABYLON.Vector3(1.0, 1.0, -1.0),
  58381. new BABYLON.Vector3(1.0, 1.0, 1.0)
  58382. ];
  58383. PanoramaToCubeMapTools.FACE_LEFT = [
  58384. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  58385. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  58386. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  58387. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  58388. ];
  58389. PanoramaToCubeMapTools.FACE_DOWN = [
  58390. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  58391. new BABYLON.Vector3(1.0, 1.0, -1.0),
  58392. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  58393. new BABYLON.Vector3(1.0, 1.0, 1.0)
  58394. ];
  58395. PanoramaToCubeMapTools.FACE_UP = [
  58396. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  58397. new BABYLON.Vector3(1.0, -1.0, 1.0),
  58398. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  58399. new BABYLON.Vector3(1.0, -1.0, -1.0)
  58400. ];
  58401. return PanoramaToCubeMapTools;
  58402. }());
  58403. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  58404. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58405. })(BABYLON || (BABYLON = {}));
  58406. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  58407. var BABYLON;
  58408. (function (BABYLON) {
  58409. var Internals;
  58410. (function (Internals) {
  58411. ;
  58412. /**
  58413. * This groups tools to convert HDR texture to native colors array.
  58414. */
  58415. var HDRTools = (function () {
  58416. function HDRTools() {
  58417. }
  58418. HDRTools.Ldexp = function (mantissa, exponent) {
  58419. if (exponent > 1023) {
  58420. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  58421. }
  58422. if (exponent < -1074) {
  58423. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  58424. }
  58425. return mantissa * Math.pow(2, exponent);
  58426. };
  58427. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  58428. if (exponent > 0) {
  58429. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  58430. float32array[index + 0] = red * exponent;
  58431. float32array[index + 1] = green * exponent;
  58432. float32array[index + 2] = blue * exponent;
  58433. }
  58434. else {
  58435. float32array[index + 0] = 0;
  58436. float32array[index + 1] = 0;
  58437. float32array[index + 2] = 0;
  58438. }
  58439. };
  58440. HDRTools.readStringLine = function (uint8array, startIndex) {
  58441. var line = "";
  58442. var character = "";
  58443. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  58444. character = String.fromCharCode(uint8array[i]);
  58445. if (character == "\n") {
  58446. break;
  58447. }
  58448. line += character;
  58449. }
  58450. return line;
  58451. };
  58452. /**
  58453. * Reads header information from an RGBE texture stored in a native array.
  58454. * More information on this format are available here:
  58455. * https://en.wikipedia.org/wiki/RGBE_image_format
  58456. *
  58457. * @param uint8array The binary file stored in native array.
  58458. * @return The header information.
  58459. */
  58460. HDRTools.RGBE_ReadHeader = function (uint8array) {
  58461. var height = 0;
  58462. var width = 0;
  58463. var line = this.readStringLine(uint8array, 0);
  58464. if (line[0] != '#' || line[1] != '?') {
  58465. throw "Bad HDR Format.";
  58466. }
  58467. var endOfHeader = false;
  58468. var findFormat = false;
  58469. var lineIndex = 0;
  58470. do {
  58471. lineIndex += (line.length + 1);
  58472. line = this.readStringLine(uint8array, lineIndex);
  58473. if (line == "FORMAT=32-bit_rle_rgbe") {
  58474. findFormat = true;
  58475. }
  58476. else if (line.length == 0) {
  58477. endOfHeader = true;
  58478. }
  58479. } while (!endOfHeader);
  58480. if (!findFormat) {
  58481. throw "HDR Bad header format, unsupported FORMAT";
  58482. }
  58483. lineIndex += (line.length + 1);
  58484. line = this.readStringLine(uint8array, lineIndex);
  58485. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  58486. var match = sizeRegexp.exec(line);
  58487. // TODO. Support +Y and -X if needed.
  58488. if (match.length < 3) {
  58489. throw "HDR Bad header format, no size";
  58490. }
  58491. width = parseInt(match[2]);
  58492. height = parseInt(match[1]);
  58493. if (width < 8 || width > 0x7fff) {
  58494. throw "HDR Bad header format, unsupported size";
  58495. }
  58496. lineIndex += (line.length + 1);
  58497. return {
  58498. height: height,
  58499. width: width,
  58500. dataPosition: lineIndex
  58501. };
  58502. };
  58503. /**
  58504. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  58505. * This RGBE texture needs to store the information as a panorama.
  58506. *
  58507. * More information on this format are available here:
  58508. * https://en.wikipedia.org/wiki/RGBE_image_format
  58509. *
  58510. * @param buffer The binary file stored in an array buffer.
  58511. * @param size The expected size of the extracted cubemap.
  58512. * @return The Cube Map information.
  58513. */
  58514. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  58515. var uint8array = new Uint8Array(buffer);
  58516. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  58517. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  58518. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  58519. return cubeMapData;
  58520. };
  58521. /**
  58522. * Returns the pixels data extracted from an RGBE texture.
  58523. * This pixels will be stored left to right up to down in the R G B order in one array.
  58524. *
  58525. * More information on this format are available here:
  58526. * https://en.wikipedia.org/wiki/RGBE_image_format
  58527. *
  58528. * @param uint8array The binary file stored in an array buffer.
  58529. * @param hdrInfo The header information of the file.
  58530. * @return The pixels data in RGB right to left up to down order.
  58531. */
  58532. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  58533. // Keep for multi format supports.
  58534. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  58535. };
  58536. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  58537. var num_scanlines = hdrInfo.height;
  58538. var scanline_width = hdrInfo.width;
  58539. var a, b, c, d, count;
  58540. var dataIndex = hdrInfo.dataPosition;
  58541. var index = 0, endIndex = 0, i = 0;
  58542. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  58543. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  58544. // 3 channels of 4 bytes per pixel in float.
  58545. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  58546. var resultArray = new Float32Array(resultBuffer);
  58547. // read in each successive scanline
  58548. while (num_scanlines > 0) {
  58549. a = uint8array[dataIndex++];
  58550. b = uint8array[dataIndex++];
  58551. c = uint8array[dataIndex++];
  58552. d = uint8array[dataIndex++];
  58553. if (a != 2 || b != 2 || (c & 0x80)) {
  58554. // this file is not run length encoded
  58555. throw "HDR Bad header format, not RLE";
  58556. }
  58557. if (((c << 8) | d) != scanline_width) {
  58558. throw "HDR Bad header format, wrong scan line width";
  58559. }
  58560. index = 0;
  58561. // read each of the four channels for the scanline into the buffer
  58562. for (i = 0; i < 4; i++) {
  58563. endIndex = (i + 1) * scanline_width;
  58564. while (index < endIndex) {
  58565. a = uint8array[dataIndex++];
  58566. b = uint8array[dataIndex++];
  58567. if (a > 128) {
  58568. // a run of the same value
  58569. count = a - 128;
  58570. if ((count == 0) || (count > endIndex - index)) {
  58571. throw "HDR Bad Format, bad scanline data (run)";
  58572. }
  58573. while (count-- > 0) {
  58574. scanLineArray[index++] = b;
  58575. }
  58576. }
  58577. else {
  58578. // a non-run
  58579. count = a;
  58580. if ((count == 0) || (count > endIndex - index)) {
  58581. throw "HDR Bad Format, bad scanline data (non-run)";
  58582. }
  58583. scanLineArray[index++] = b;
  58584. if (--count > 0) {
  58585. for (var j = 0; j < count; j++) {
  58586. scanLineArray[index++] = uint8array[dataIndex++];
  58587. }
  58588. }
  58589. }
  58590. }
  58591. }
  58592. // now convert data from buffer into floats
  58593. for (i = 0; i < scanline_width; i++) {
  58594. a = scanLineArray[i];
  58595. b = scanLineArray[i + scanline_width];
  58596. c = scanLineArray[i + 2 * scanline_width];
  58597. d = scanLineArray[i + 3 * scanline_width];
  58598. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  58599. }
  58600. num_scanlines--;
  58601. }
  58602. return resultArray;
  58603. };
  58604. return HDRTools;
  58605. }());
  58606. Internals.HDRTools = HDRTools;
  58607. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58608. })(BABYLON || (BABYLON = {}));
  58609. //# sourceMappingURL=babylon.hdr.js.map
  58610. var BABYLON;
  58611. (function (BABYLON) {
  58612. /**
  58613. * This represents a texture coming from an HDR input.
  58614. *
  58615. * The only supported format is currently panorama picture stored in RGBE format.
  58616. * Example of such files can be found on HDRLib: http://hdrlib.com/
  58617. */
  58618. var HDRCubeTexture = (function (_super) {
  58619. __extends(HDRCubeTexture, _super);
  58620. /**
  58621. * Instantiates an HDRTexture from the following parameters.
  58622. *
  58623. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  58624. * @param scene The scene the texture will be used in
  58625. * @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.
  58626. * @param noMipmap Forces to not generate the mipmap if true
  58627. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  58628. * @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)
  58629. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  58630. */
  58631. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  58632. if (noMipmap === void 0) { noMipmap = false; }
  58633. if (generateHarmonics === void 0) { generateHarmonics = true; }
  58634. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  58635. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  58636. if (onLoad === void 0) { onLoad = null; }
  58637. if (onError === void 0) { onError = null; }
  58638. var _this = _super.call(this, scene) || this;
  58639. _this._useInGammaSpace = false;
  58640. _this._generateHarmonics = true;
  58641. _this._isBABYLONPreprocessed = false;
  58642. _this._onLoad = null;
  58643. _this._onError = null;
  58644. /**
  58645. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  58646. */
  58647. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58648. /**
  58649. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  58650. * This is usefull at run time to apply the good shader.
  58651. */
  58652. _this.isPMREM = false;
  58653. _this._isBlocking = true;
  58654. if (!url) {
  58655. return _this;
  58656. }
  58657. _this.name = url;
  58658. _this.url = url;
  58659. _this.hasAlpha = false;
  58660. _this.isCube = true;
  58661. _this._textureMatrix = BABYLON.Matrix.Identity();
  58662. _this._onLoad = onLoad;
  58663. _this._onError = onError;
  58664. _this.gammaSpace = false;
  58665. if (size) {
  58666. _this._isBABYLONPreprocessed = false;
  58667. _this._noMipmap = noMipmap;
  58668. _this._size = size;
  58669. _this._useInGammaSpace = useInGammaSpace;
  58670. _this._usePMREMGenerator = usePMREMGenerator &&
  58671. scene.getEngine().getCaps().textureLOD &&
  58672. _this.getScene().getEngine().getCaps().textureFloat &&
  58673. !_this._useInGammaSpace;
  58674. }
  58675. else {
  58676. _this._isBABYLONPreprocessed = true;
  58677. _this._noMipmap = false;
  58678. _this._useInGammaSpace = false;
  58679. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  58680. _this.getScene().getEngine().getCaps().textureFloat &&
  58681. !_this._useInGammaSpace;
  58682. }
  58683. _this.isPMREM = _this._usePMREMGenerator;
  58684. _this._texture = _this._getFromCache(url, _this._noMipmap);
  58685. if (!_this._texture) {
  58686. if (!scene.useDelayedTextureLoading) {
  58687. _this.loadTexture();
  58688. }
  58689. else {
  58690. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58691. }
  58692. }
  58693. return _this;
  58694. }
  58695. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  58696. /**
  58697. * Gets wether or not the texture is blocking during loading.
  58698. */
  58699. get: function () {
  58700. return this._isBlocking;
  58701. },
  58702. /**
  58703. * Sets wether or not the texture is blocking during loading.
  58704. */
  58705. set: function (value) {
  58706. this._isBlocking = value;
  58707. },
  58708. enumerable: true,
  58709. configurable: true
  58710. });
  58711. /**
  58712. * Occurs when the file is a preprocessed .babylon.hdr file.
  58713. */
  58714. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  58715. var _this = this;
  58716. var mipLevels = 0;
  58717. var floatArrayView = null;
  58718. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  58719. var mips = [];
  58720. var startIndex = 30;
  58721. for (var level = 0; level < mipLevels; level++) {
  58722. mips.push([]);
  58723. // Fill each pixel of the mip level.
  58724. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  58725. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  58726. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  58727. mips[level].push(faceData);
  58728. startIndex += faceSize;
  58729. }
  58730. }
  58731. return mips;
  58732. } : null;
  58733. var callback = function (buffer) {
  58734. // Create Native Array Views
  58735. var intArrayView = new Int32Array(buffer);
  58736. floatArrayView = new Float32Array(buffer);
  58737. // Fill header.
  58738. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  58739. _this._size = intArrayView[1]; // CubeMap max mip face size.
  58740. // Update Texture Information.
  58741. _this._texture.updateSize(_this._size, _this._size);
  58742. // Fill polynomial information.
  58743. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  58744. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  58745. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  58746. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  58747. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  58748. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  58749. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  58750. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  58751. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  58752. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  58753. _this.sphericalPolynomial = sphericalPolynomial;
  58754. // Fill pixel data.
  58755. mipLevels = intArrayView[29]; // Number of mip levels.
  58756. var startIndex = 30;
  58757. var data = [];
  58758. var faceSize = Math.pow(_this._size, 2) * 3;
  58759. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  58760. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  58761. startIndex += faceSize;
  58762. }
  58763. var results = [];
  58764. var byteArray = null;
  58765. // Push each faces.
  58766. for (var k = 0; k < 6; k++) {
  58767. var dataFace = null;
  58768. // To be deprecated.
  58769. if (version === 1) {
  58770. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  58771. dataFace = data[j];
  58772. }
  58773. // If special cases.
  58774. if (!mipmapGenerator) {
  58775. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  58776. // 3 channels of 1 bytes per pixel in bytes.
  58777. var byteBuffer = new ArrayBuffer(faceSize);
  58778. byteArray = new Uint8Array(byteBuffer);
  58779. }
  58780. for (var i = 0; i < _this._size * _this._size; i++) {
  58781. // Put in gamma space if requested.
  58782. if (_this._useInGammaSpace) {
  58783. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  58784. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  58785. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  58786. }
  58787. // Convert to int texture for fallback.
  58788. if (byteArray) {
  58789. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  58790. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  58791. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  58792. // May use luminance instead if the result is not accurate.
  58793. var max = Math.max(Math.max(r, g), b);
  58794. if (max > 255) {
  58795. var scale = 255 / max;
  58796. r *= scale;
  58797. g *= scale;
  58798. b *= scale;
  58799. }
  58800. byteArray[(i * 3) + 0] = r;
  58801. byteArray[(i * 3) + 1] = g;
  58802. byteArray[(i * 3) + 2] = b;
  58803. }
  58804. }
  58805. }
  58806. // Fill the array accordingly.
  58807. if (byteArray) {
  58808. results.push(byteArray);
  58809. }
  58810. else {
  58811. results.push(dataFace);
  58812. }
  58813. }
  58814. return results;
  58815. };
  58816. 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);
  58817. };
  58818. /**
  58819. * Occurs when the file is raw .hdr file.
  58820. */
  58821. HDRCubeTexture.prototype.loadHDRTexture = function () {
  58822. var _this = this;
  58823. var callback = function (buffer) {
  58824. // Extract the raw linear data.
  58825. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  58826. // Generate harmonics if needed.
  58827. if (_this._generateHarmonics) {
  58828. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  58829. _this.sphericalPolynomial = sphericalPolynomial;
  58830. }
  58831. var results = [];
  58832. var byteArray = null;
  58833. // Push each faces.
  58834. for (var j = 0; j < 6; j++) {
  58835. // Create uintarray fallback.
  58836. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  58837. // 3 channels of 1 bytes per pixel in bytes.
  58838. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  58839. byteArray = new Uint8Array(byteBuffer);
  58840. }
  58841. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  58842. // If special cases.
  58843. if (_this._useInGammaSpace || byteArray) {
  58844. for (var i = 0; i < _this._size * _this._size; i++) {
  58845. // Put in gamma space if requested.
  58846. if (_this._useInGammaSpace) {
  58847. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  58848. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  58849. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  58850. }
  58851. // Convert to int texture for fallback.
  58852. if (byteArray) {
  58853. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  58854. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  58855. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  58856. // May use luminance instead if the result is not accurate.
  58857. var max = Math.max(Math.max(r, g), b);
  58858. if (max > 255) {
  58859. var scale = 255 / max;
  58860. r *= scale;
  58861. g *= scale;
  58862. b *= scale;
  58863. }
  58864. byteArray[(i * 3) + 0] = r;
  58865. byteArray[(i * 3) + 1] = g;
  58866. byteArray[(i * 3) + 2] = b;
  58867. }
  58868. }
  58869. }
  58870. if (byteArray) {
  58871. results.push(byteArray);
  58872. }
  58873. else {
  58874. results.push(dataFace);
  58875. }
  58876. }
  58877. return results;
  58878. };
  58879. var mipmapGenerator = null;
  58880. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  58881. // if (!this._noMipmap &&
  58882. // this._usePMREMGenerator) {
  58883. // mipmapGenerator = (data: ArrayBufferView[]) => {
  58884. // // Custom setup of the generator matching with the PBR shader values.
  58885. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  58886. // this._size,
  58887. // this._size,
  58888. // 0,
  58889. // 3,
  58890. // this.getScene().getEngine().getCaps().textureFloat,
  58891. // 2048,
  58892. // 0.25,
  58893. // false,
  58894. // true);
  58895. // return generator.filterCubeMap();
  58896. // };
  58897. // }
  58898. 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);
  58899. };
  58900. /**
  58901. * Starts the loading process of the texture.
  58902. */
  58903. HDRCubeTexture.prototype.loadTexture = function () {
  58904. if (this._isBABYLONPreprocessed) {
  58905. this.loadBabylonTexture();
  58906. }
  58907. else {
  58908. this.loadHDRTexture();
  58909. }
  58910. };
  58911. HDRCubeTexture.prototype.clone = function () {
  58912. var size = this._isBABYLONPreprocessed ? null : this._size;
  58913. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  58914. // Base texture
  58915. newTexture.level = this.level;
  58916. newTexture.wrapU = this.wrapU;
  58917. newTexture.wrapV = this.wrapV;
  58918. newTexture.coordinatesIndex = this.coordinatesIndex;
  58919. newTexture.coordinatesMode = this.coordinatesMode;
  58920. return newTexture;
  58921. };
  58922. // Methods
  58923. HDRCubeTexture.prototype.delayLoad = function () {
  58924. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58925. return;
  58926. }
  58927. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58928. this._texture = this._getFromCache(this.url, this._noMipmap);
  58929. if (!this._texture) {
  58930. this.loadTexture();
  58931. }
  58932. };
  58933. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  58934. return this._textureMatrix;
  58935. };
  58936. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  58937. this._textureMatrix = value;
  58938. };
  58939. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58940. var texture = null;
  58941. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  58942. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  58943. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  58944. texture.name = parsedTexture.name;
  58945. texture.hasAlpha = parsedTexture.hasAlpha;
  58946. texture.level = parsedTexture.level;
  58947. texture.coordinatesMode = parsedTexture.coordinatesMode;
  58948. texture.isBlocking = parsedTexture.isBlocking;
  58949. }
  58950. return texture;
  58951. };
  58952. HDRCubeTexture.prototype.serialize = function () {
  58953. if (!this.name) {
  58954. return null;
  58955. }
  58956. var serializationObject = {};
  58957. serializationObject.name = this.name;
  58958. serializationObject.hasAlpha = this.hasAlpha;
  58959. serializationObject.isCube = true;
  58960. serializationObject.level = this.level;
  58961. serializationObject.size = this._size;
  58962. serializationObject.coordinatesMode = this.coordinatesMode;
  58963. serializationObject.useInGammaSpace = this._useInGammaSpace;
  58964. serializationObject.generateHarmonics = this._generateHarmonics;
  58965. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  58966. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  58967. serializationObject.customType = "BABYLON.HDRCubeTexture";
  58968. serializationObject.noMipmap = this._noMipmap;
  58969. serializationObject.isBlocking = this._isBlocking;
  58970. return serializationObject;
  58971. };
  58972. /**
  58973. * Saves as a file the data contained in the texture in a binary format.
  58974. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  58975. * as the spherical used in the lighting.
  58976. * @param url The HDR file url.
  58977. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  58978. * @param onError Method called if any error happens during download.
  58979. * @return The packed binary data.
  58980. */
  58981. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  58982. if (onError === void 0) { onError = null; }
  58983. var callback = function (buffer) {
  58984. var data = new Blob([buffer], { type: 'application/octet-stream' });
  58985. // Returns a URL you can use as a href.
  58986. var objUrl = window.URL.createObjectURL(data);
  58987. // Simulates a link to it and click to dowload.
  58988. var a = document.createElement("a");
  58989. document.body.appendChild(a);
  58990. a.style.display = "none";
  58991. a.href = objUrl;
  58992. a.download = "envmap.babylon.hdr";
  58993. a.click();
  58994. };
  58995. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  58996. };
  58997. /**
  58998. * Serializes the data contained in the texture in a binary format.
  58999. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  59000. * as the spherical used in the lighting.
  59001. * @param url The HDR file url.
  59002. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  59003. * @param onError Method called if any error happens during download.
  59004. * @return The packed binary data.
  59005. */
  59006. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  59007. if (onError === void 0) { onError = null; }
  59008. // Needs the url tho create the texture.
  59009. if (!url) {
  59010. return null;
  59011. }
  59012. // Check Power of two size.
  59013. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  59014. return null;
  59015. }
  59016. // Coming Back in 3.1.
  59017. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  59018. return null;
  59019. };
  59020. HDRCubeTexture._facesMapping = [
  59021. "right",
  59022. "left",
  59023. "up",
  59024. "down",
  59025. "front",
  59026. "back"
  59027. ];
  59028. return HDRCubeTexture;
  59029. }(BABYLON.BaseTexture));
  59030. BABYLON.HDRCubeTexture = HDRCubeTexture;
  59031. })(BABYLON || (BABYLON = {}));
  59032. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  59033. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  59034. // Huge respect for a such great lib.
  59035. // Earcut license:
  59036. // Copyright (c) 2016, Mapbox
  59037. //
  59038. // Permission to use, copy, modify, and/or distribute this software for any purpose
  59039. // with or without fee is hereby granted, provided that the above copyright notice
  59040. // and this permission notice appear in all copies.
  59041. //
  59042. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  59043. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  59044. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  59045. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  59046. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  59047. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  59048. // THIS SOFTWARE.
  59049. var Earcut;
  59050. (function (Earcut) {
  59051. /**
  59052. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  59053. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  59054. * @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).
  59055. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  59056. */
  59057. function earcut(data, holeIndices, dim) {
  59058. dim = dim || 2;
  59059. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  59060. if (!outerNode)
  59061. return triangles;
  59062. var minX, minY, maxX, maxY, x, y, size;
  59063. if (hasHoles)
  59064. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  59065. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  59066. if (data.length > 80 * dim) {
  59067. minX = maxX = data[0];
  59068. minY = maxY = data[1];
  59069. for (var i = dim; i < outerLen; i += dim) {
  59070. x = data[i];
  59071. y = data[i + 1];
  59072. if (x < minX)
  59073. minX = x;
  59074. if (y < minY)
  59075. minY = y;
  59076. if (x > maxX)
  59077. maxX = x;
  59078. if (y > maxY)
  59079. maxY = y;
  59080. }
  59081. // minX, minY and size are later used to transform coords into integers for z-order calculation
  59082. size = Math.max(maxX - minX, maxY - minY);
  59083. }
  59084. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  59085. return triangles;
  59086. }
  59087. Earcut.earcut = earcut;
  59088. // create a circular doubly linked list from polygon points in the specified winding order
  59089. function linkedList(data, start, end, dim, clockwise) {
  59090. var i, last;
  59091. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  59092. for (i = start; i < end; i += dim)
  59093. last = insertNode(i, data[i], data[i + 1], last);
  59094. }
  59095. else {
  59096. for (i = end - dim; i >= start; i -= dim)
  59097. last = insertNode(i, data[i], data[i + 1], last);
  59098. }
  59099. if (last && equals(last, last.next)) {
  59100. removeNode(last);
  59101. last = last.next;
  59102. }
  59103. return last;
  59104. }
  59105. // eliminate colinear or duplicate points
  59106. function filterPoints(start, end) {
  59107. if (!start)
  59108. return start;
  59109. if (!end)
  59110. end = start;
  59111. var p = start, again;
  59112. do {
  59113. again = false;
  59114. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  59115. removeNode(p);
  59116. p = end = p.prev;
  59117. if (p === p.next)
  59118. return null;
  59119. again = true;
  59120. }
  59121. else {
  59122. p = p.next;
  59123. }
  59124. } while (again || p !== end);
  59125. return end;
  59126. }
  59127. // main ear slicing loop which triangulates a polygon (given as a linked list)
  59128. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  59129. if (!ear)
  59130. return;
  59131. // interlink polygon nodes in z-order
  59132. if (!pass && size)
  59133. indexCurve(ear, minX, minY, size);
  59134. var stop = ear, prev, next;
  59135. // iterate through ears, slicing them one by one
  59136. while (ear.prev !== ear.next) {
  59137. prev = ear.prev;
  59138. next = ear.next;
  59139. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  59140. // cut off the triangle
  59141. triangles.push(prev.i / dim);
  59142. triangles.push(ear.i / dim);
  59143. triangles.push(next.i / dim);
  59144. removeNode(ear);
  59145. // skipping the next vertice leads to less sliver triangles
  59146. ear = next.next;
  59147. stop = next.next;
  59148. continue;
  59149. }
  59150. ear = next;
  59151. // if we looped through the whole remaining polygon and can't find any more ears
  59152. if (ear === stop) {
  59153. // try filtering points and slicing again
  59154. if (!pass) {
  59155. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  59156. // if this didn't work, try curing all small self-intersections locally
  59157. }
  59158. else if (pass === 1) {
  59159. ear = cureLocalIntersections(ear, triangles, dim);
  59160. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  59161. // as a last resort, try splitting the remaining polygon into two
  59162. }
  59163. else if (pass === 2) {
  59164. splitEarcut(ear, triangles, dim, minX, minY, size);
  59165. }
  59166. break;
  59167. }
  59168. }
  59169. }
  59170. // check whether a polygon node forms a valid ear with adjacent nodes
  59171. function isEar(ear) {
  59172. var a = ear.prev, b = ear, c = ear.next;
  59173. if (area(a, b, c) >= 0)
  59174. return false; // reflex, can't be an ear
  59175. // now make sure we don't have other points inside the potential ear
  59176. var p = ear.next.next;
  59177. while (p !== ear.prev) {
  59178. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  59179. area(p.prev, p, p.next) >= 0)
  59180. return false;
  59181. p = p.next;
  59182. }
  59183. return true;
  59184. }
  59185. function isEarHashed(ear, minX, minY, size) {
  59186. var a = ear.prev, b = ear, c = ear.next;
  59187. if (area(a, b, c) >= 0)
  59188. return false; // reflex, can't be an ear
  59189. // triangle bbox; min & max are calculated like this for speed
  59190. 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);
  59191. // z-order range for the current triangle bbox;
  59192. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  59193. // first look for points inside the triangle in increasing z-order
  59194. var p = ear.nextZ;
  59195. while (p && p.z <= maxZ) {
  59196. if (p !== ear.prev &&
  59197. p !== ear.next &&
  59198. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  59199. area(p.prev, p, p.next) >= 0)
  59200. return false;
  59201. p = p.nextZ;
  59202. }
  59203. // then look for points in decreasing z-order
  59204. p = ear.prevZ;
  59205. while (p && p.z >= minZ) {
  59206. if (p !== ear.prev &&
  59207. p !== ear.next &&
  59208. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  59209. area(p.prev, p, p.next) >= 0)
  59210. return false;
  59211. p = p.prevZ;
  59212. }
  59213. return true;
  59214. }
  59215. // go through all polygon nodes and cure small local self-intersections
  59216. function cureLocalIntersections(start, triangles, dim) {
  59217. var p = start;
  59218. do {
  59219. var a = p.prev, b = p.next.next;
  59220. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  59221. triangles.push(a.i / dim);
  59222. triangles.push(p.i / dim);
  59223. triangles.push(b.i / dim);
  59224. // remove two nodes involved
  59225. removeNode(p);
  59226. removeNode(p.next);
  59227. p = start = b;
  59228. }
  59229. p = p.next;
  59230. } while (p !== start);
  59231. return p;
  59232. }
  59233. // try splitting polygon into two and triangulate them independently
  59234. function splitEarcut(start, triangles, dim, minX, minY, size) {
  59235. // look for a valid diagonal that divides the polygon into two
  59236. var a = start;
  59237. do {
  59238. var b = a.next.next;
  59239. while (b !== a.prev) {
  59240. if (a.i !== b.i && isValidDiagonal(a, b)) {
  59241. // split the polygon in two by the diagonal
  59242. var c = splitPolygon(a, b);
  59243. // filter colinear points around the cuts
  59244. a = filterPoints(a, a.next);
  59245. c = filterPoints(c, c.next);
  59246. // run earcut on each half
  59247. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  59248. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  59249. return;
  59250. }
  59251. b = b.next;
  59252. }
  59253. a = a.next;
  59254. } while (a !== start);
  59255. }
  59256. // link every hole into the outer loop, producing a single-ring polygon without holes
  59257. function eliminateHoles(data, holeIndices, outerNode, dim) {
  59258. var queue = [], i, len, start, end, list;
  59259. for (i = 0, len = holeIndices.length; i < len; i++) {
  59260. start = holeIndices[i] * dim;
  59261. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  59262. list = linkedList(data, start, end, dim, false);
  59263. if (list === list.next)
  59264. list.steiner = true;
  59265. queue.push(getLeftmost(list));
  59266. }
  59267. queue.sort(compareX);
  59268. // process holes from left to right
  59269. for (i = 0; i < queue.length; i++) {
  59270. eliminateHole(queue[i], outerNode);
  59271. outerNode = filterPoints(outerNode, outerNode.next);
  59272. }
  59273. return outerNode;
  59274. }
  59275. function compareX(a, b) {
  59276. return a.x - b.x;
  59277. }
  59278. // find a bridge between vertices that connects hole with an outer ring and and link it
  59279. function eliminateHole(hole, outerNode) {
  59280. outerNode = findHoleBridge(hole, outerNode);
  59281. if (outerNode) {
  59282. var b = splitPolygon(outerNode, hole);
  59283. filterPoints(b, b.next);
  59284. }
  59285. }
  59286. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  59287. function findHoleBridge(hole, outerNode) {
  59288. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  59289. // find a segment intersected by a ray from the hole's leftmost point to the left;
  59290. // segment's endpoint with lesser x will be potential connection point
  59291. do {
  59292. if (hy <= p.y && hy >= p.next.y) {
  59293. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  59294. if (x <= hx && x > qx) {
  59295. qx = x;
  59296. if (x === hx) {
  59297. if (hy === p.y)
  59298. return p;
  59299. if (hy === p.next.y)
  59300. return p.next;
  59301. }
  59302. m = p.x < p.next.x ? p : p.next;
  59303. }
  59304. }
  59305. p = p.next;
  59306. } while (p !== outerNode);
  59307. if (!m)
  59308. return null;
  59309. if (hx === qx)
  59310. return m.prev; // hole touches outer segment; pick lower endpoint
  59311. // look for points inside the triangle of hole point, segment intersection and endpoint;
  59312. // if there are no points found, we have a valid connection;
  59313. // otherwise choose the point of the minimum angle with the ray as connection point
  59314. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  59315. p = m.next;
  59316. while (p !== stop) {
  59317. if (hx >= p.x &&
  59318. p.x >= mx &&
  59319. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  59320. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  59321. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  59322. m = p;
  59323. tanMin = tan;
  59324. }
  59325. }
  59326. p = p.next;
  59327. }
  59328. return m;
  59329. }
  59330. // interlink polygon nodes in z-order
  59331. function indexCurve(start, minX, minY, size) {
  59332. var p = start;
  59333. do {
  59334. if (p.z === null)
  59335. p.z = zOrder(p.x, p.y, minX, minY, size);
  59336. p.prevZ = p.prev;
  59337. p.nextZ = p.next;
  59338. p = p.next;
  59339. } while (p !== start);
  59340. p.prevZ.nextZ = null;
  59341. p.prevZ = null;
  59342. sortLinked(p);
  59343. }
  59344. // Simon Tatham's linked list merge sort algorithm
  59345. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  59346. function sortLinked(list) {
  59347. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  59348. do {
  59349. p = list;
  59350. list = null;
  59351. tail = null;
  59352. numMerges = 0;
  59353. while (p) {
  59354. numMerges++;
  59355. q = p;
  59356. pSize = 0;
  59357. for (i = 0; i < inSize; i++) {
  59358. pSize++;
  59359. q = q.nextZ;
  59360. if (!q)
  59361. break;
  59362. }
  59363. qSize = inSize;
  59364. while (pSize > 0 || (qSize > 0 && q)) {
  59365. if (pSize === 0) {
  59366. e = q;
  59367. q = q.nextZ;
  59368. qSize--;
  59369. }
  59370. else if (qSize === 0 || !q) {
  59371. e = p;
  59372. p = p.nextZ;
  59373. pSize--;
  59374. }
  59375. else if (p.z <= q.z) {
  59376. e = p;
  59377. p = p.nextZ;
  59378. pSize--;
  59379. }
  59380. else {
  59381. e = q;
  59382. q = q.nextZ;
  59383. qSize--;
  59384. }
  59385. if (tail)
  59386. tail.nextZ = e;
  59387. else
  59388. list = e;
  59389. e.prevZ = tail;
  59390. tail = e;
  59391. }
  59392. p = q;
  59393. }
  59394. tail.nextZ = null;
  59395. inSize *= 2;
  59396. } while (numMerges > 1);
  59397. return list;
  59398. }
  59399. // z-order of a point given coords and size of the data bounding box
  59400. function zOrder(x, y, minX, minY, size) {
  59401. // coords are transformed into non-negative 15-bit integer range
  59402. x = 32767 * (x - minX) / size;
  59403. y = 32767 * (y - minY) / size;
  59404. x = (x | (x << 8)) & 0x00FF00FF;
  59405. x = (x | (x << 4)) & 0x0F0F0F0F;
  59406. x = (x | (x << 2)) & 0x33333333;
  59407. x = (x | (x << 1)) & 0x55555555;
  59408. y = (y | (y << 8)) & 0x00FF00FF;
  59409. y = (y | (y << 4)) & 0x0F0F0F0F;
  59410. y = (y | (y << 2)) & 0x33333333;
  59411. y = (y | (y << 1)) & 0x55555555;
  59412. return x | (y << 1);
  59413. }
  59414. // find the leftmost node of a polygon ring
  59415. function getLeftmost(start) {
  59416. var p = start, leftmost = start;
  59417. do {
  59418. if (p.x < leftmost.x)
  59419. leftmost = p;
  59420. p = p.next;
  59421. } while (p !== start);
  59422. return leftmost;
  59423. }
  59424. // check if a point lies within a convex triangle
  59425. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  59426. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  59427. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  59428. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  59429. }
  59430. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  59431. function isValidDiagonal(a, b) {
  59432. return a.next.i !== b.i &&
  59433. a.prev.i !== b.i &&
  59434. !intersectsPolygon(a, b) &&
  59435. locallyInside(a, b) &&
  59436. locallyInside(b, a) &&
  59437. middleInside(a, b);
  59438. }
  59439. // signed area of a triangle
  59440. function area(p, q, r) {
  59441. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  59442. }
  59443. // check if two points are equal
  59444. function equals(p1, p2) {
  59445. return p1.x === p2.x && p1.y === p2.y;
  59446. }
  59447. // check if two segments intersect
  59448. function intersects(p1, q1, p2, q2) {
  59449. if ((equals(p1, q1) && equals(p2, q2)) ||
  59450. (equals(p1, q2) && equals(p2, q1)))
  59451. return true;
  59452. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  59453. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  59454. }
  59455. // check if a polygon diagonal intersects any polygon segments
  59456. function intersectsPolygon(a, b) {
  59457. var p = a;
  59458. do {
  59459. if (p.i !== a.i &&
  59460. p.next.i !== a.i &&
  59461. p.i !== b.i &&
  59462. p.next.i !== b.i &&
  59463. intersects(p, p.next, a, b))
  59464. return true;
  59465. p = p.next;
  59466. } while (p !== a);
  59467. return false;
  59468. }
  59469. // check if a polygon diagonal is locally inside the polygon
  59470. function locallyInside(a, b) {
  59471. return area(a.prev, a, a.next) < 0
  59472. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  59473. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  59474. }
  59475. // check if the middle point of a polygon diagonal is inside the polygon
  59476. function middleInside(a, b) {
  59477. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  59478. do {
  59479. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  59480. inside = !inside;
  59481. p = p.next;
  59482. } while (p !== a);
  59483. return inside;
  59484. }
  59485. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  59486. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  59487. function splitPolygon(a, b) {
  59488. 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;
  59489. a.next = b;
  59490. b.prev = a;
  59491. a2.next = an;
  59492. an.prev = a2;
  59493. b2.next = a2;
  59494. a2.prev = b2;
  59495. bp.next = b2;
  59496. b2.prev = bp;
  59497. return b2;
  59498. }
  59499. // create a node and optionally link it with previous one (in a circular doubly linked list)
  59500. function insertNode(i, x, y, last) {
  59501. var p = new Node(i, x, y);
  59502. if (!last) {
  59503. p.prev = p;
  59504. p.next = p;
  59505. }
  59506. else {
  59507. p.next = last.next;
  59508. p.prev = last;
  59509. last.next.prev = p;
  59510. last.next = p;
  59511. }
  59512. return p;
  59513. }
  59514. function removeNode(p) {
  59515. p.next.prev = p.prev;
  59516. p.prev.next = p.next;
  59517. if (p.prevZ)
  59518. p.prevZ.nextZ = p.nextZ;
  59519. if (p.nextZ)
  59520. p.nextZ.prevZ = p.prevZ;
  59521. }
  59522. function Node(i, x, y) {
  59523. // vertice index in coordinates array
  59524. this.i = i;
  59525. // vertex coordinates
  59526. this.x = x;
  59527. this.y = y;
  59528. // previous and next vertice nodes in a polygon ring
  59529. this.prev = null;
  59530. this.next = null;
  59531. // z-order curve value
  59532. this.z = null;
  59533. // previous and next nodes in z-order
  59534. this.prevZ = null;
  59535. this.nextZ = null;
  59536. // indicates whether this is a steiner point
  59537. this.steiner = false;
  59538. }
  59539. /**
  59540. * return a percentage difference between the polygon area and its triangulation area;
  59541. * used to verify correctness of triangulation
  59542. */
  59543. function deviation(data, holeIndices, dim, triangles) {
  59544. var hasHoles = holeIndices && holeIndices.length;
  59545. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  59546. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  59547. if (hasHoles) {
  59548. for (var i = 0, len = holeIndices.length; i < len; i++) {
  59549. var start = holeIndices[i] * dim;
  59550. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  59551. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  59552. }
  59553. }
  59554. var trianglesArea = 0;
  59555. for (i = 0; i < triangles.length; i += 3) {
  59556. var a = triangles[i] * dim;
  59557. var b = triangles[i + 1] * dim;
  59558. var c = triangles[i + 2] * dim;
  59559. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  59560. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  59561. }
  59562. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  59563. }
  59564. Earcut.deviation = deviation;
  59565. ;
  59566. function signedArea(data, start, end, dim) {
  59567. var sum = 0;
  59568. for (var i = start, j = end - dim; i < end; i += dim) {
  59569. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  59570. j = i;
  59571. }
  59572. return sum;
  59573. }
  59574. /**
  59575. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  59576. */
  59577. function flatten(data) {
  59578. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  59579. for (var i = 0; i < data.length; i++) {
  59580. for (var j = 0; j < data[i].length; j++) {
  59581. for (var d = 0; d < dim; d++)
  59582. result.vertices.push(data[i][j][d]);
  59583. }
  59584. if (i > 0) {
  59585. holeIndex += data[i - 1].length;
  59586. result.holes.push(holeIndex);
  59587. }
  59588. }
  59589. return result;
  59590. }
  59591. Earcut.flatten = flatten;
  59592. ;
  59593. })(Earcut || (Earcut = {}));
  59594. //# sourceMappingURL=babylon.earcut.js.map
  59595. /// <reference path="..\Math\babylon.math.ts" />
  59596. var BABYLON;
  59597. (function (BABYLON) {
  59598. var IndexedVector2 = (function (_super) {
  59599. __extends(IndexedVector2, _super);
  59600. function IndexedVector2(original, index) {
  59601. var _this = _super.call(this, original.x, original.y) || this;
  59602. _this.index = index;
  59603. return _this;
  59604. }
  59605. return IndexedVector2;
  59606. }(BABYLON.Vector2));
  59607. var PolygonPoints = (function () {
  59608. function PolygonPoints() {
  59609. this.elements = new Array();
  59610. }
  59611. PolygonPoints.prototype.add = function (originalPoints) {
  59612. var _this = this;
  59613. var result = new Array();
  59614. originalPoints.forEach(function (point) {
  59615. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  59616. var newPoint = new IndexedVector2(point, _this.elements.length);
  59617. result.push(newPoint);
  59618. _this.elements.push(newPoint);
  59619. }
  59620. });
  59621. return result;
  59622. };
  59623. PolygonPoints.prototype.computeBounds = function () {
  59624. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  59625. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  59626. this.elements.forEach(function (point) {
  59627. // x
  59628. if (point.x < lmin.x) {
  59629. lmin.x = point.x;
  59630. }
  59631. else if (point.x > lmax.x) {
  59632. lmax.x = point.x;
  59633. }
  59634. // y
  59635. if (point.y < lmin.y) {
  59636. lmin.y = point.y;
  59637. }
  59638. else if (point.y > lmax.y) {
  59639. lmax.y = point.y;
  59640. }
  59641. });
  59642. return {
  59643. min: lmin,
  59644. max: lmax,
  59645. width: lmax.x - lmin.x,
  59646. height: lmax.y - lmin.y
  59647. };
  59648. };
  59649. return PolygonPoints;
  59650. }());
  59651. var Polygon = (function () {
  59652. function Polygon() {
  59653. }
  59654. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  59655. return [
  59656. new BABYLON.Vector2(xmin, ymin),
  59657. new BABYLON.Vector2(xmax, ymin),
  59658. new BABYLON.Vector2(xmax, ymax),
  59659. new BABYLON.Vector2(xmin, ymax)
  59660. ];
  59661. };
  59662. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  59663. if (cx === void 0) { cx = 0; }
  59664. if (cy === void 0) { cy = 0; }
  59665. if (numberOfSides === void 0) { numberOfSides = 32; }
  59666. var result = new Array();
  59667. var angle = 0;
  59668. var increment = (Math.PI * 2) / numberOfSides;
  59669. for (var i = 0; i < numberOfSides; i++) {
  59670. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  59671. angle -= increment;
  59672. }
  59673. return result;
  59674. };
  59675. Polygon.Parse = function (input) {
  59676. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  59677. var i, result = [];
  59678. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  59679. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  59680. }
  59681. return result;
  59682. };
  59683. Polygon.StartingAt = function (x, y) {
  59684. return BABYLON.Path2.StartingAt(x, y);
  59685. };
  59686. return Polygon;
  59687. }());
  59688. BABYLON.Polygon = Polygon;
  59689. var PolygonMeshBuilder = (function () {
  59690. function PolygonMeshBuilder(name, contours, scene) {
  59691. this._points = new PolygonPoints();
  59692. this._outlinepoints = new PolygonPoints();
  59693. this._holes = [];
  59694. this._epoints = new Array();
  59695. this._eholes = new Array();
  59696. this._name = name;
  59697. this._scene = scene;
  59698. var points;
  59699. if (contours instanceof BABYLON.Path2) {
  59700. points = contours.getPoints();
  59701. }
  59702. else {
  59703. points = contours;
  59704. }
  59705. this._addToepoint(points);
  59706. this._points.add(points);
  59707. this._outlinepoints.add(points);
  59708. }
  59709. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  59710. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  59711. var p = points_1[_i];
  59712. this._epoints.push(p.x, p.y);
  59713. }
  59714. };
  59715. PolygonMeshBuilder.prototype.addHole = function (hole) {
  59716. this._points.add(hole);
  59717. var holepoints = new PolygonPoints();
  59718. holepoints.add(hole);
  59719. this._holes.push(holepoints);
  59720. this._eholes.push(this._epoints.length / 2);
  59721. this._addToepoint(hole);
  59722. return this;
  59723. };
  59724. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  59725. var _this = this;
  59726. if (updatable === void 0) { updatable = false; }
  59727. var result = new BABYLON.Mesh(this._name, this._scene);
  59728. var normals = [];
  59729. var positions = [];
  59730. var uvs = [];
  59731. var bounds = this._points.computeBounds();
  59732. this._points.elements.forEach(function (p) {
  59733. normals.push(0, 1.0, 0);
  59734. positions.push(p.x, 0, p.y);
  59735. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  59736. });
  59737. var indices = [];
  59738. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  59739. for (var i = 0; i < res.length; i++) {
  59740. indices.push(res[i]);
  59741. }
  59742. if (depth > 0) {
  59743. var positionscount = (positions.length / 3); //get the current pointcount
  59744. this._points.elements.forEach(function (p) {
  59745. normals.push(0, -1.0, 0);
  59746. positions.push(p.x, -depth, p.y);
  59747. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  59748. });
  59749. var totalCount = indices.length;
  59750. for (var i = 0; i < totalCount; i += 3) {
  59751. var i0 = indices[i + 0];
  59752. var i1 = indices[i + 1];
  59753. var i2 = indices[i + 2];
  59754. indices.push(i2 + positionscount);
  59755. indices.push(i1 + positionscount);
  59756. indices.push(i0 + positionscount);
  59757. }
  59758. //Add the sides
  59759. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  59760. this._holes.forEach(function (hole) {
  59761. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  59762. });
  59763. }
  59764. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  59765. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  59766. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  59767. result.setIndices(indices);
  59768. return result;
  59769. };
  59770. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  59771. var StartIndex = positions.length / 3;
  59772. var ulength = 0;
  59773. for (var i = 0; i < points.elements.length; i++) {
  59774. var p = points.elements[i];
  59775. var p1;
  59776. if ((i + 1) > points.elements.length - 1) {
  59777. p1 = points.elements[0];
  59778. }
  59779. else {
  59780. p1 = points.elements[i + 1];
  59781. }
  59782. positions.push(p.x, 0, p.y);
  59783. positions.push(p.x, -depth, p.y);
  59784. positions.push(p1.x, 0, p1.y);
  59785. positions.push(p1.x, -depth, p1.y);
  59786. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  59787. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  59788. var v3 = v2.subtract(v1);
  59789. var v4 = new BABYLON.Vector3(0, 1, 0);
  59790. var vn = BABYLON.Vector3.Cross(v3, v4);
  59791. vn = vn.normalize();
  59792. uvs.push(ulength / bounds.width, 0);
  59793. uvs.push(ulength / bounds.width, 1);
  59794. ulength += v3.length();
  59795. uvs.push((ulength / bounds.width), 0);
  59796. uvs.push((ulength / bounds.width), 1);
  59797. if (!flip) {
  59798. normals.push(-vn.x, -vn.y, -vn.z);
  59799. normals.push(-vn.x, -vn.y, -vn.z);
  59800. normals.push(-vn.x, -vn.y, -vn.z);
  59801. normals.push(-vn.x, -vn.y, -vn.z);
  59802. indices.push(StartIndex);
  59803. indices.push(StartIndex + 1);
  59804. indices.push(StartIndex + 2);
  59805. indices.push(StartIndex + 1);
  59806. indices.push(StartIndex + 3);
  59807. indices.push(StartIndex + 2);
  59808. }
  59809. else {
  59810. normals.push(vn.x, vn.y, vn.z);
  59811. normals.push(vn.x, vn.y, vn.z);
  59812. normals.push(vn.x, vn.y, vn.z);
  59813. normals.push(vn.x, vn.y, vn.z);
  59814. indices.push(StartIndex);
  59815. indices.push(StartIndex + 2);
  59816. indices.push(StartIndex + 1);
  59817. indices.push(StartIndex + 1);
  59818. indices.push(StartIndex + 2);
  59819. indices.push(StartIndex + 3);
  59820. }
  59821. StartIndex += 4;
  59822. }
  59823. ;
  59824. };
  59825. return PolygonMeshBuilder;
  59826. }());
  59827. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  59828. })(BABYLON || (BABYLON = {}));
  59829. //# sourceMappingURL=babylon.polygonMesh.js.map
  59830. var BABYLON;
  59831. (function (BABYLON) {
  59832. // Unique ID when we import meshes from Babylon to CSG
  59833. var currentCSGMeshId = 0;
  59834. // # class Vertex
  59835. // Represents a vertex of a polygon. Use your own vertex class instead of this
  59836. // one to provide additional features like texture coordinates and vertex
  59837. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  59838. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  59839. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  59840. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  59841. // is not used anywhere else.
  59842. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  59843. var Vertex = (function () {
  59844. function Vertex(pos, normal, uv) {
  59845. this.pos = pos;
  59846. this.normal = normal;
  59847. this.uv = uv;
  59848. }
  59849. Vertex.prototype.clone = function () {
  59850. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  59851. };
  59852. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  59853. // orientation of a polygon is flipped.
  59854. Vertex.prototype.flip = function () {
  59855. this.normal = this.normal.scale(-1);
  59856. };
  59857. // Create a new vertex between this vertex and `other` by linearly
  59858. // interpolating all properties using a parameter of `t`. Subclasses should
  59859. // override this to interpolate additional properties.
  59860. Vertex.prototype.interpolate = function (other, t) {
  59861. 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));
  59862. };
  59863. return Vertex;
  59864. }());
  59865. // # class Plane
  59866. // Represents a plane in 3D space.
  59867. var Plane = (function () {
  59868. function Plane(normal, w) {
  59869. this.normal = normal;
  59870. this.w = w;
  59871. }
  59872. Plane.FromPoints = function (a, b, c) {
  59873. var v0 = c.subtract(a);
  59874. var v1 = b.subtract(a);
  59875. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  59876. return null;
  59877. }
  59878. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  59879. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  59880. };
  59881. Plane.prototype.clone = function () {
  59882. return new Plane(this.normal.clone(), this.w);
  59883. };
  59884. Plane.prototype.flip = function () {
  59885. this.normal.scaleInPlace(-1);
  59886. this.w = -this.w;
  59887. };
  59888. // Split `polygon` by this plane if needed, then put the polygon or polygon
  59889. // fragments in the appropriate lists. Coplanar polygons go into either
  59890. // `coplanarFront` or `coplanarBack` depending on their orientation with
  59891. // respect to this plane. Polygons in front or in back of this plane go into
  59892. // either `front` or `back`.
  59893. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  59894. var COPLANAR = 0;
  59895. var FRONT = 1;
  59896. var BACK = 2;
  59897. var SPANNING = 3;
  59898. // Classify each point as well as the entire polygon into one of the above
  59899. // four classes.
  59900. var polygonType = 0;
  59901. var types = [];
  59902. var i;
  59903. var t;
  59904. for (i = 0; i < polygon.vertices.length; i++) {
  59905. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  59906. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  59907. polygonType |= type;
  59908. types.push(type);
  59909. }
  59910. // Put the polygon in the correct list, splitting it when necessary.
  59911. switch (polygonType) {
  59912. case COPLANAR:
  59913. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  59914. break;
  59915. case FRONT:
  59916. front.push(polygon);
  59917. break;
  59918. case BACK:
  59919. back.push(polygon);
  59920. break;
  59921. case SPANNING:
  59922. var f = [], b = [];
  59923. for (i = 0; i < polygon.vertices.length; i++) {
  59924. var j = (i + 1) % polygon.vertices.length;
  59925. var ti = types[i], tj = types[j];
  59926. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  59927. if (ti !== BACK)
  59928. f.push(vi);
  59929. if (ti !== FRONT)
  59930. b.push(ti !== BACK ? vi.clone() : vi);
  59931. if ((ti | tj) === SPANNING) {
  59932. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  59933. var v = vi.interpolate(vj, t);
  59934. f.push(v);
  59935. b.push(v.clone());
  59936. }
  59937. }
  59938. var poly;
  59939. if (f.length >= 3) {
  59940. poly = new Polygon(f, polygon.shared);
  59941. if (poly.plane)
  59942. front.push(poly);
  59943. }
  59944. if (b.length >= 3) {
  59945. poly = new Polygon(b, polygon.shared);
  59946. if (poly.plane)
  59947. back.push(poly);
  59948. }
  59949. break;
  59950. }
  59951. };
  59952. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  59953. // point is on the plane.
  59954. Plane.EPSILON = 1e-5;
  59955. return Plane;
  59956. }());
  59957. // # class Polygon
  59958. // Represents a convex polygon. The vertices used to initialize a polygon must
  59959. // be coplanar and form a convex loop.
  59960. //
  59961. // Each convex polygon has a `shared` property, which is shared between all
  59962. // polygons that are clones of each other or were split from the same polygon.
  59963. // This can be used to define per-polygon properties (such as surface color).
  59964. var Polygon = (function () {
  59965. function Polygon(vertices, shared) {
  59966. this.vertices = vertices;
  59967. this.shared = shared;
  59968. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  59969. }
  59970. Polygon.prototype.clone = function () {
  59971. var vertices = this.vertices.map(function (v) { return v.clone(); });
  59972. return new Polygon(vertices, this.shared);
  59973. };
  59974. Polygon.prototype.flip = function () {
  59975. this.vertices.reverse().map(function (v) { v.flip(); });
  59976. this.plane.flip();
  59977. };
  59978. return Polygon;
  59979. }());
  59980. // # class Node
  59981. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  59982. // by picking a polygon to split along. That polygon (and all other coplanar
  59983. // polygons) are added directly to that node and the other polygons are added to
  59984. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  59985. // no distinction between internal and leaf nodes.
  59986. var Node = (function () {
  59987. function Node(polygons) {
  59988. this.plane = null;
  59989. this.front = null;
  59990. this.back = null;
  59991. this.polygons = [];
  59992. if (polygons) {
  59993. this.build(polygons);
  59994. }
  59995. }
  59996. Node.prototype.clone = function () {
  59997. var node = new Node();
  59998. node.plane = this.plane && this.plane.clone();
  59999. node.front = this.front && this.front.clone();
  60000. node.back = this.back && this.back.clone();
  60001. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  60002. return node;
  60003. };
  60004. // Convert solid space to empty space and empty space to solid space.
  60005. Node.prototype.invert = function () {
  60006. for (var i = 0; i < this.polygons.length; i++) {
  60007. this.polygons[i].flip();
  60008. }
  60009. if (this.plane) {
  60010. this.plane.flip();
  60011. }
  60012. if (this.front) {
  60013. this.front.invert();
  60014. }
  60015. if (this.back) {
  60016. this.back.invert();
  60017. }
  60018. var temp = this.front;
  60019. this.front = this.back;
  60020. this.back = temp;
  60021. };
  60022. // Recursively remove all polygons in `polygons` that are inside this BSP
  60023. // tree.
  60024. Node.prototype.clipPolygons = function (polygons) {
  60025. if (!this.plane)
  60026. return polygons.slice();
  60027. var front = [], back = [];
  60028. for (var i = 0; i < polygons.length; i++) {
  60029. this.plane.splitPolygon(polygons[i], front, back, front, back);
  60030. }
  60031. if (this.front) {
  60032. front = this.front.clipPolygons(front);
  60033. }
  60034. if (this.back) {
  60035. back = this.back.clipPolygons(back);
  60036. }
  60037. else {
  60038. back = [];
  60039. }
  60040. return front.concat(back);
  60041. };
  60042. // Remove all polygons in this BSP tree that are inside the other BSP tree
  60043. // `bsp`.
  60044. Node.prototype.clipTo = function (bsp) {
  60045. this.polygons = bsp.clipPolygons(this.polygons);
  60046. if (this.front)
  60047. this.front.clipTo(bsp);
  60048. if (this.back)
  60049. this.back.clipTo(bsp);
  60050. };
  60051. // Return a list of all polygons in this BSP tree.
  60052. Node.prototype.allPolygons = function () {
  60053. var polygons = this.polygons.slice();
  60054. if (this.front)
  60055. polygons = polygons.concat(this.front.allPolygons());
  60056. if (this.back)
  60057. polygons = polygons.concat(this.back.allPolygons());
  60058. return polygons;
  60059. };
  60060. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  60061. // new polygons are filtered down to the bottom of the tree and become new
  60062. // nodes there. Each set of polygons is partitioned using the first polygon
  60063. // (no heuristic is used to pick a good split).
  60064. Node.prototype.build = function (polygons) {
  60065. if (!polygons.length)
  60066. return;
  60067. if (!this.plane)
  60068. this.plane = polygons[0].plane.clone();
  60069. var front = [], back = [];
  60070. for (var i = 0; i < polygons.length; i++) {
  60071. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  60072. }
  60073. if (front.length) {
  60074. if (!this.front)
  60075. this.front = new Node();
  60076. this.front.build(front);
  60077. }
  60078. if (back.length) {
  60079. if (!this.back)
  60080. this.back = new Node();
  60081. this.back.build(back);
  60082. }
  60083. };
  60084. return Node;
  60085. }());
  60086. var CSG = (function () {
  60087. function CSG() {
  60088. this.polygons = new Array();
  60089. }
  60090. // Convert BABYLON.Mesh to BABYLON.CSG
  60091. CSG.FromMesh = function (mesh) {
  60092. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  60093. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  60094. if (mesh instanceof BABYLON.Mesh) {
  60095. mesh.computeWorldMatrix(true);
  60096. matrix = mesh.getWorldMatrix();
  60097. meshPosition = mesh.position.clone();
  60098. meshRotation = mesh.rotation.clone();
  60099. if (mesh.rotationQuaternion) {
  60100. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  60101. }
  60102. meshScaling = mesh.scaling.clone();
  60103. }
  60104. else {
  60105. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  60106. }
  60107. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60108. var subMeshes = mesh.subMeshes;
  60109. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  60110. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  60111. vertices = [];
  60112. for (var j = 0; j < 3; j++) {
  60113. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  60114. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  60115. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  60116. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  60117. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  60118. vertex = new Vertex(position, normal, uv);
  60119. vertices.push(vertex);
  60120. }
  60121. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  60122. // To handle the case of degenerated triangle
  60123. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  60124. if (polygon.plane)
  60125. polygons.push(polygon);
  60126. }
  60127. }
  60128. var csg = CSG.FromPolygons(polygons);
  60129. csg.matrix = matrix;
  60130. csg.position = meshPosition;
  60131. csg.rotation = meshRotation;
  60132. csg.scaling = meshScaling;
  60133. csg.rotationQuaternion = meshRotationQuaternion;
  60134. currentCSGMeshId++;
  60135. return csg;
  60136. };
  60137. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  60138. CSG.FromPolygons = function (polygons) {
  60139. var csg = new CSG();
  60140. csg.polygons = polygons;
  60141. return csg;
  60142. };
  60143. CSG.prototype.clone = function () {
  60144. var csg = new CSG();
  60145. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  60146. csg.copyTransformAttributes(this);
  60147. return csg;
  60148. };
  60149. CSG.prototype.toPolygons = function () {
  60150. return this.polygons;
  60151. };
  60152. CSG.prototype.union = function (csg) {
  60153. var a = new Node(this.clone().polygons);
  60154. var b = new Node(csg.clone().polygons);
  60155. a.clipTo(b);
  60156. b.clipTo(a);
  60157. b.invert();
  60158. b.clipTo(a);
  60159. b.invert();
  60160. a.build(b.allPolygons());
  60161. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  60162. };
  60163. CSG.prototype.unionInPlace = function (csg) {
  60164. var a = new Node(this.polygons);
  60165. var b = new Node(csg.polygons);
  60166. a.clipTo(b);
  60167. b.clipTo(a);
  60168. b.invert();
  60169. b.clipTo(a);
  60170. b.invert();
  60171. a.build(b.allPolygons());
  60172. this.polygons = a.allPolygons();
  60173. };
  60174. CSG.prototype.subtract = function (csg) {
  60175. var a = new Node(this.clone().polygons);
  60176. var b = new Node(csg.clone().polygons);
  60177. a.invert();
  60178. a.clipTo(b);
  60179. b.clipTo(a);
  60180. b.invert();
  60181. b.clipTo(a);
  60182. b.invert();
  60183. a.build(b.allPolygons());
  60184. a.invert();
  60185. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  60186. };
  60187. CSG.prototype.subtractInPlace = function (csg) {
  60188. var a = new Node(this.polygons);
  60189. var b = new Node(csg.polygons);
  60190. a.invert();
  60191. a.clipTo(b);
  60192. b.clipTo(a);
  60193. b.invert();
  60194. b.clipTo(a);
  60195. b.invert();
  60196. a.build(b.allPolygons());
  60197. a.invert();
  60198. this.polygons = a.allPolygons();
  60199. };
  60200. CSG.prototype.intersect = function (csg) {
  60201. var a = new Node(this.clone().polygons);
  60202. var b = new Node(csg.clone().polygons);
  60203. a.invert();
  60204. b.clipTo(a);
  60205. b.invert();
  60206. a.clipTo(b);
  60207. b.clipTo(a);
  60208. a.build(b.allPolygons());
  60209. a.invert();
  60210. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  60211. };
  60212. CSG.prototype.intersectInPlace = function (csg) {
  60213. var a = new Node(this.polygons);
  60214. var b = new Node(csg.polygons);
  60215. a.invert();
  60216. b.clipTo(a);
  60217. b.invert();
  60218. a.clipTo(b);
  60219. b.clipTo(a);
  60220. a.build(b.allPolygons());
  60221. a.invert();
  60222. this.polygons = a.allPolygons();
  60223. };
  60224. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  60225. // not modified.
  60226. CSG.prototype.inverse = function () {
  60227. var csg = this.clone();
  60228. csg.inverseInPlace();
  60229. return csg;
  60230. };
  60231. CSG.prototype.inverseInPlace = function () {
  60232. this.polygons.map(function (p) { p.flip(); });
  60233. };
  60234. // This is used to keep meshes transformations so they can be restored
  60235. // when we build back a Babylon Mesh
  60236. // NB : All CSG operations are performed in world coordinates
  60237. CSG.prototype.copyTransformAttributes = function (csg) {
  60238. this.matrix = csg.matrix;
  60239. this.position = csg.position;
  60240. this.rotation = csg.rotation;
  60241. this.scaling = csg.scaling;
  60242. this.rotationQuaternion = csg.rotationQuaternion;
  60243. return this;
  60244. };
  60245. // Build Raw mesh from CSG
  60246. // Coordinates here are in world space
  60247. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  60248. var matrix = this.matrix.clone();
  60249. matrix.invert();
  60250. 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;
  60251. if (keepSubMeshes) {
  60252. // Sort Polygons, since subMeshes are indices range
  60253. polygons.sort(function (a, b) {
  60254. if (a.shared.meshId === b.shared.meshId) {
  60255. return a.shared.subMeshId - b.shared.subMeshId;
  60256. }
  60257. else {
  60258. return a.shared.meshId - b.shared.meshId;
  60259. }
  60260. });
  60261. }
  60262. for (var i = 0, il = polygons.length; i < il; i++) {
  60263. polygon = polygons[i];
  60264. // Building SubMeshes
  60265. if (!subMesh_dict[polygon.shared.meshId]) {
  60266. subMesh_dict[polygon.shared.meshId] = {};
  60267. }
  60268. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  60269. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  60270. indexStart: +Infinity,
  60271. indexEnd: -Infinity,
  60272. materialIndex: polygon.shared.materialIndex
  60273. };
  60274. }
  60275. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  60276. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  60277. polygonIndices[0] = 0;
  60278. polygonIndices[1] = j - 1;
  60279. polygonIndices[2] = j;
  60280. for (var k = 0; k < 3; k++) {
  60281. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  60282. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  60283. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  60284. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  60285. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  60286. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  60287. // Check if 2 points can be merged
  60288. if (!(typeof vertex_idx !== 'undefined' &&
  60289. normals[vertex_idx * 3] === localNormal.x &&
  60290. normals[vertex_idx * 3 + 1] === localNormal.y &&
  60291. normals[vertex_idx * 3 + 2] === localNormal.z &&
  60292. uvs[vertex_idx * 2] === uv.x &&
  60293. uvs[vertex_idx * 2 + 1] === uv.y)) {
  60294. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  60295. uvs.push(uv.x, uv.y);
  60296. normals.push(normal.x, normal.y, normal.z);
  60297. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  60298. }
  60299. indices.push(vertex_idx);
  60300. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  60301. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  60302. currentIndex++;
  60303. }
  60304. }
  60305. }
  60306. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  60307. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  60308. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  60309. mesh.setIndices(indices);
  60310. if (keepSubMeshes) {
  60311. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  60312. var materialIndexOffset = 0, materialMaxIndex;
  60313. mesh.subMeshes = new Array();
  60314. for (var m in subMesh_dict) {
  60315. materialMaxIndex = -1;
  60316. for (var sm in subMesh_dict[m]) {
  60317. subMesh_obj = subMesh_dict[m][sm];
  60318. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  60319. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  60320. }
  60321. materialIndexOffset += ++materialMaxIndex;
  60322. }
  60323. }
  60324. return mesh;
  60325. };
  60326. // Build Mesh from CSG taking material and transforms into account
  60327. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  60328. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  60329. mesh.material = material;
  60330. mesh.position.copyFrom(this.position);
  60331. mesh.rotation.copyFrom(this.rotation);
  60332. if (this.rotationQuaternion) {
  60333. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  60334. }
  60335. mesh.scaling.copyFrom(this.scaling);
  60336. mesh.computeWorldMatrix(true);
  60337. return mesh;
  60338. };
  60339. return CSG;
  60340. }());
  60341. BABYLON.CSG = CSG;
  60342. })(BABYLON || (BABYLON = {}));
  60343. //# sourceMappingURL=babylon.csg.js.map
  60344. var BABYLON;
  60345. (function (BABYLON) {
  60346. var LensFlare = (function () {
  60347. function LensFlare(size, position, color, imgUrl, system) {
  60348. this.size = size;
  60349. this.position = position;
  60350. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  60351. this.dispose = function () {
  60352. if (this.texture) {
  60353. this.texture.dispose();
  60354. }
  60355. // Remove from scene
  60356. var index = this._system.lensFlares.indexOf(this);
  60357. this._system.lensFlares.splice(index, 1);
  60358. };
  60359. this.color = color || new BABYLON.Color3(1, 1, 1);
  60360. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  60361. this._system = system;
  60362. system.lensFlares.push(this);
  60363. }
  60364. return LensFlare;
  60365. }());
  60366. BABYLON.LensFlare = LensFlare;
  60367. })(BABYLON || (BABYLON = {}));
  60368. //# sourceMappingURL=babylon.lensFlare.js.map
  60369. var BABYLON;
  60370. (function (BABYLON) {
  60371. var LensFlareSystem = (function () {
  60372. function LensFlareSystem(name, emitter, scene) {
  60373. this.name = name;
  60374. this.lensFlares = new Array();
  60375. this.borderLimit = 300;
  60376. this.viewportBorder = 0;
  60377. this.layerMask = 0x0FFFFFFF;
  60378. this._vertexBuffers = {};
  60379. this._isEnabled = true;
  60380. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60381. this._emitter = emitter;
  60382. this.id = name;
  60383. scene.lensFlareSystems.push(this);
  60384. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  60385. var engine = scene.getEngine();
  60386. // VBO
  60387. var vertices = [];
  60388. vertices.push(1, 1);
  60389. vertices.push(-1, 1);
  60390. vertices.push(-1, -1);
  60391. vertices.push(1, -1);
  60392. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  60393. // Indices
  60394. var indices = [];
  60395. indices.push(0);
  60396. indices.push(1);
  60397. indices.push(2);
  60398. indices.push(0);
  60399. indices.push(2);
  60400. indices.push(3);
  60401. this._indexBuffer = engine.createIndexBuffer(indices);
  60402. // Effects
  60403. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  60404. }
  60405. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  60406. get: function () {
  60407. return this._isEnabled;
  60408. },
  60409. set: function (value) {
  60410. this._isEnabled = value;
  60411. },
  60412. enumerable: true,
  60413. configurable: true
  60414. });
  60415. LensFlareSystem.prototype.getScene = function () {
  60416. return this._scene;
  60417. };
  60418. LensFlareSystem.prototype.getEmitter = function () {
  60419. return this._emitter;
  60420. };
  60421. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  60422. this._emitter = newEmitter;
  60423. };
  60424. LensFlareSystem.prototype.getEmitterPosition = function () {
  60425. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  60426. };
  60427. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  60428. var position = this.getEmitterPosition();
  60429. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  60430. this._positionX = position.x;
  60431. this._positionY = position.y;
  60432. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  60433. if (this.viewportBorder > 0) {
  60434. globalViewport.x -= this.viewportBorder;
  60435. globalViewport.y -= this.viewportBorder;
  60436. globalViewport.width += this.viewportBorder * 2;
  60437. globalViewport.height += this.viewportBorder * 2;
  60438. position.x += this.viewportBorder;
  60439. position.y += this.viewportBorder;
  60440. this._positionX += this.viewportBorder;
  60441. this._positionY += this.viewportBorder;
  60442. }
  60443. if (position.z > 0) {
  60444. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  60445. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  60446. return true;
  60447. }
  60448. return true;
  60449. }
  60450. return false;
  60451. };
  60452. LensFlareSystem.prototype._isVisible = function () {
  60453. if (!this._isEnabled) {
  60454. return false;
  60455. }
  60456. var emitterPosition = this.getEmitterPosition();
  60457. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  60458. var distance = direction.length();
  60459. direction.normalize();
  60460. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  60461. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  60462. return !pickInfo.hit || pickInfo.distance > distance;
  60463. };
  60464. LensFlareSystem.prototype.render = function () {
  60465. if (!this._effect.isReady())
  60466. return false;
  60467. var engine = this._scene.getEngine();
  60468. var viewport = this._scene.activeCamera.viewport;
  60469. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  60470. // Position
  60471. if (!this.computeEffectivePosition(globalViewport)) {
  60472. return false;
  60473. }
  60474. // Visibility
  60475. if (!this._isVisible()) {
  60476. return false;
  60477. }
  60478. // Intensity
  60479. var awayX;
  60480. var awayY;
  60481. if (this._positionX < this.borderLimit + globalViewport.x) {
  60482. awayX = this.borderLimit + globalViewport.x - this._positionX;
  60483. }
  60484. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  60485. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  60486. }
  60487. else {
  60488. awayX = 0;
  60489. }
  60490. if (this._positionY < this.borderLimit + globalViewport.y) {
  60491. awayY = this.borderLimit + globalViewport.y - this._positionY;
  60492. }
  60493. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  60494. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  60495. }
  60496. else {
  60497. awayY = 0;
  60498. }
  60499. var away = (awayX > awayY) ? awayX : awayY;
  60500. away -= this.viewportBorder;
  60501. if (away > this.borderLimit) {
  60502. away = this.borderLimit;
  60503. }
  60504. var intensity = 1.0 - (away / this.borderLimit);
  60505. if (intensity < 0) {
  60506. return false;
  60507. }
  60508. if (intensity > 1.0) {
  60509. intensity = 1.0;
  60510. }
  60511. if (this.viewportBorder > 0) {
  60512. globalViewport.x += this.viewportBorder;
  60513. globalViewport.y += this.viewportBorder;
  60514. globalViewport.width -= this.viewportBorder * 2;
  60515. globalViewport.height -= this.viewportBorder * 2;
  60516. this._positionX -= this.viewportBorder;
  60517. this._positionY -= this.viewportBorder;
  60518. }
  60519. // Position
  60520. var centerX = globalViewport.x + globalViewport.width / 2;
  60521. var centerY = globalViewport.y + globalViewport.height / 2;
  60522. var distX = centerX - this._positionX;
  60523. var distY = centerY - this._positionY;
  60524. // Effects
  60525. engine.enableEffect(this._effect);
  60526. engine.setState(false);
  60527. engine.setDepthBuffer(false);
  60528. // VBOs
  60529. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  60530. // Flares
  60531. for (var index = 0; index < this.lensFlares.length; index++) {
  60532. var flare = this.lensFlares[index];
  60533. engine.setAlphaMode(flare.alphaMode);
  60534. var x = centerX - (distX * flare.position);
  60535. var y = centerY - (distY * flare.position);
  60536. var cw = flare.size;
  60537. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  60538. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  60539. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  60540. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  60541. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  60542. // Texture
  60543. this._effect.setTexture("textureSampler", flare.texture);
  60544. // Color
  60545. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  60546. // Draw order
  60547. engine.draw(true, 0, 6);
  60548. }
  60549. engine.setDepthBuffer(true);
  60550. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  60551. return true;
  60552. };
  60553. LensFlareSystem.prototype.dispose = function () {
  60554. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60555. if (vertexBuffer) {
  60556. vertexBuffer.dispose();
  60557. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  60558. }
  60559. if (this._indexBuffer) {
  60560. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  60561. this._indexBuffer = null;
  60562. }
  60563. while (this.lensFlares.length) {
  60564. this.lensFlares[0].dispose();
  60565. }
  60566. // Remove from scene
  60567. var index = this._scene.lensFlareSystems.indexOf(this);
  60568. this._scene.lensFlareSystems.splice(index, 1);
  60569. };
  60570. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  60571. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  60572. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  60573. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  60574. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  60575. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  60576. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  60577. var parsedFlare = parsedLensFlareSystem.flares[index];
  60578. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  60579. }
  60580. return lensFlareSystem;
  60581. };
  60582. LensFlareSystem.prototype.serialize = function () {
  60583. var serializationObject = {};
  60584. serializationObject.id = this.id;
  60585. serializationObject.name = this.name;
  60586. serializationObject.emitterId = this.getEmitter().id;
  60587. serializationObject.borderLimit = this.borderLimit;
  60588. serializationObject.flares = [];
  60589. for (var index = 0; index < this.lensFlares.length; index++) {
  60590. var flare = this.lensFlares[index];
  60591. serializationObject.flares.push({
  60592. size: flare.size,
  60593. position: flare.position,
  60594. color: flare.color.asArray(),
  60595. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  60596. });
  60597. }
  60598. return serializationObject;
  60599. };
  60600. return LensFlareSystem;
  60601. }());
  60602. BABYLON.LensFlareSystem = LensFlareSystem;
  60603. })(BABYLON || (BABYLON = {}));
  60604. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  60605. var BABYLON;
  60606. (function (BABYLON) {
  60607. /**
  60608. * This is a holder class for the physics joint created by the physics plugin.
  60609. * It holds a set of functions to control the underlying joint.
  60610. */
  60611. var PhysicsJoint = (function () {
  60612. function PhysicsJoint(type, jointData) {
  60613. this.type = type;
  60614. this.jointData = jointData;
  60615. jointData.nativeParams = jointData.nativeParams || {};
  60616. }
  60617. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  60618. get: function () {
  60619. return this._physicsJoint;
  60620. },
  60621. set: function (newJoint) {
  60622. if (this._physicsJoint) {
  60623. //remove from the wolrd
  60624. }
  60625. this._physicsJoint = newJoint;
  60626. },
  60627. enumerable: true,
  60628. configurable: true
  60629. });
  60630. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  60631. set: function (physicsPlugin) {
  60632. this._physicsPlugin = physicsPlugin;
  60633. },
  60634. enumerable: true,
  60635. configurable: true
  60636. });
  60637. /**
  60638. * Execute a function that is physics-plugin specific.
  60639. * @param {Function} func the function that will be executed.
  60640. * It accepts two parameters: the physics world and the physics joint.
  60641. */
  60642. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  60643. func(this._physicsPlugin.world, this._physicsJoint);
  60644. };
  60645. //TODO check if the native joints are the same
  60646. //Joint Types
  60647. PhysicsJoint.DistanceJoint = 0;
  60648. PhysicsJoint.HingeJoint = 1;
  60649. PhysicsJoint.BallAndSocketJoint = 2;
  60650. PhysicsJoint.WheelJoint = 3;
  60651. PhysicsJoint.SliderJoint = 4;
  60652. //OIMO
  60653. PhysicsJoint.PrismaticJoint = 5;
  60654. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  60655. PhysicsJoint.UniversalJoint = 6;
  60656. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  60657. //Cannon
  60658. //Similar to a Ball-Joint. Different in params
  60659. PhysicsJoint.PointToPointJoint = 8;
  60660. //Cannon only at the moment
  60661. PhysicsJoint.SpringJoint = 9;
  60662. PhysicsJoint.LockJoint = 10;
  60663. return PhysicsJoint;
  60664. }());
  60665. BABYLON.PhysicsJoint = PhysicsJoint;
  60666. /**
  60667. * A class representing a physics distance joint.
  60668. */
  60669. var DistanceJoint = (function (_super) {
  60670. __extends(DistanceJoint, _super);
  60671. function DistanceJoint(jointData) {
  60672. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  60673. }
  60674. /**
  60675. * Update the predefined distance.
  60676. */
  60677. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  60678. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  60679. };
  60680. return DistanceJoint;
  60681. }(PhysicsJoint));
  60682. BABYLON.DistanceJoint = DistanceJoint;
  60683. var MotorEnabledJoint = (function (_super) {
  60684. __extends(MotorEnabledJoint, _super);
  60685. function MotorEnabledJoint(type, jointData) {
  60686. return _super.call(this, type, jointData) || this;
  60687. }
  60688. /**
  60689. * Set the motor values.
  60690. * Attention, this function is plugin specific. Engines won't react 100% the same.
  60691. * @param {number} force the force to apply
  60692. * @param {number} maxForce max force for this motor.
  60693. */
  60694. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  60695. this._physicsPlugin.setMotor(this, force, maxForce);
  60696. };
  60697. /**
  60698. * Set the motor's limits.
  60699. * Attention, this function is plugin specific. Engines won't react 100% the same.
  60700. */
  60701. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  60702. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  60703. };
  60704. return MotorEnabledJoint;
  60705. }(PhysicsJoint));
  60706. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  60707. /**
  60708. * This class represents a single hinge physics joint
  60709. */
  60710. var HingeJoint = (function (_super) {
  60711. __extends(HingeJoint, _super);
  60712. function HingeJoint(jointData) {
  60713. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  60714. }
  60715. /**
  60716. * Set the motor values.
  60717. * Attention, this function is plugin specific. Engines won't react 100% the same.
  60718. * @param {number} force the force to apply
  60719. * @param {number} maxForce max force for this motor.
  60720. */
  60721. HingeJoint.prototype.setMotor = function (force, maxForce) {
  60722. this._physicsPlugin.setMotor(this, force, maxForce);
  60723. };
  60724. /**
  60725. * Set the motor's limits.
  60726. * Attention, this function is plugin specific. Engines won't react 100% the same.
  60727. */
  60728. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  60729. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  60730. };
  60731. return HingeJoint;
  60732. }(MotorEnabledJoint));
  60733. BABYLON.HingeJoint = HingeJoint;
  60734. /**
  60735. * This class represents a dual hinge physics joint (same as wheel joint)
  60736. */
  60737. var Hinge2Joint = (function (_super) {
  60738. __extends(Hinge2Joint, _super);
  60739. function Hinge2Joint(jointData) {
  60740. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  60741. }
  60742. /**
  60743. * Set the motor values.
  60744. * Attention, this function is plugin specific. Engines won't react 100% the same.
  60745. * @param {number} force the force to apply
  60746. * @param {number} maxForce max force for this motor.
  60747. * @param {motorIndex} the motor's index, 0 or 1.
  60748. */
  60749. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  60750. if (motorIndex === void 0) { motorIndex = 0; }
  60751. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  60752. };
  60753. /**
  60754. * Set the motor limits.
  60755. * Attention, this function is plugin specific. Engines won't react 100% the same.
  60756. * @param {number} upperLimit the upper limit
  60757. * @param {number} lowerLimit lower limit
  60758. * @param {motorIndex} the motor's index, 0 or 1.
  60759. */
  60760. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  60761. if (motorIndex === void 0) { motorIndex = 0; }
  60762. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  60763. };
  60764. return Hinge2Joint;
  60765. }(MotorEnabledJoint));
  60766. BABYLON.Hinge2Joint = Hinge2Joint;
  60767. })(BABYLON || (BABYLON = {}));
  60768. //# sourceMappingURL=babylon.physicsJoint.js.map
  60769. var BABYLON;
  60770. (function (BABYLON) {
  60771. var PhysicsImpostor = (function () {
  60772. function PhysicsImpostor(object, type, _options, _scene) {
  60773. if (_options === void 0) { _options = { mass: 0 }; }
  60774. var _this = this;
  60775. this.object = object;
  60776. this.type = type;
  60777. this._options = _options;
  60778. this._scene = _scene;
  60779. this._bodyUpdateRequired = false;
  60780. this._onBeforePhysicsStepCallbacks = new Array();
  60781. this._onAfterPhysicsStepCallbacks = new Array();
  60782. this._onPhysicsCollideCallbacks = [];
  60783. this._deltaPosition = BABYLON.Vector3.Zero();
  60784. this._isDisposed = false;
  60785. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  60786. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  60787. /**
  60788. * this function is executed by the physics engine.
  60789. */
  60790. this.beforeStep = function () {
  60791. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  60792. //conjugate deltaRotation
  60793. if (_this._deltaRotationConjugated) {
  60794. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  60795. }
  60796. else {
  60797. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  60798. }
  60799. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  60800. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  60801. func(_this);
  60802. });
  60803. };
  60804. /**
  60805. * this function is executed by the physics engine.
  60806. */
  60807. this.afterStep = function () {
  60808. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  60809. func(_this);
  60810. });
  60811. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  60812. _this.object.position.addInPlace(_this._deltaPosition);
  60813. if (_this._deltaRotation) {
  60814. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  60815. }
  60816. };
  60817. /**
  60818. * Legacy collision detection event support
  60819. */
  60820. this.onCollideEvent = null;
  60821. //event and body object due to cannon's event-based architecture.
  60822. this.onCollide = function (e) {
  60823. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  60824. return;
  60825. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  60826. if (otherImpostor) {
  60827. // Legacy collision detection event support
  60828. if (_this.onCollideEvent) {
  60829. _this.onCollideEvent(_this, otherImpostor);
  60830. }
  60831. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  60832. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  60833. }).forEach(function (obj) {
  60834. obj.callback(_this, otherImpostor);
  60835. });
  60836. }
  60837. };
  60838. //sanity check!
  60839. if (!this.object) {
  60840. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  60841. return;
  60842. }
  60843. //legacy support for old syntax.
  60844. if (!this._scene && object.getScene) {
  60845. this._scene = object.getScene();
  60846. }
  60847. this._physicsEngine = this._scene.getPhysicsEngine();
  60848. if (!this._physicsEngine) {
  60849. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  60850. }
  60851. else {
  60852. //set the object's quaternion, if not set
  60853. if (!this.object.rotationQuaternion) {
  60854. if (this.object.rotation) {
  60855. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  60856. }
  60857. else {
  60858. this.object.rotationQuaternion = new BABYLON.Quaternion();
  60859. }
  60860. }
  60861. //default options params
  60862. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  60863. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  60864. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  60865. this._joints = [];
  60866. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  60867. if (!this.object.parent) {
  60868. this._init();
  60869. }
  60870. else if (this.object.parent.physicsImpostor) {
  60871. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  60872. }
  60873. }
  60874. }
  60875. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  60876. get: function () {
  60877. return this._isDisposed;
  60878. },
  60879. enumerable: true,
  60880. configurable: true
  60881. });
  60882. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  60883. get: function () {
  60884. return this._physicsEngine.getPhysicsPlugin().getBodyMass(this);
  60885. },
  60886. set: function (value) {
  60887. this.setMass(value);
  60888. },
  60889. enumerable: true,
  60890. configurable: true
  60891. });
  60892. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  60893. get: function () {
  60894. return this._physicsEngine.getPhysicsPlugin().getBodyFriction(this);
  60895. },
  60896. set: function (value) {
  60897. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  60898. },
  60899. enumerable: true,
  60900. configurable: true
  60901. });
  60902. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  60903. get: function () {
  60904. return this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this);
  60905. },
  60906. set: function (value) {
  60907. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  60908. },
  60909. enumerable: true,
  60910. configurable: true
  60911. });
  60912. /**
  60913. * This function will completly initialize this impostor.
  60914. * It will create a new body - but only if this mesh has no parent.
  60915. * If it has, this impostor will not be used other than to define the impostor
  60916. * of the child mesh.
  60917. */
  60918. PhysicsImpostor.prototype._init = function () {
  60919. this._physicsEngine.removeImpostor(this);
  60920. this.physicsBody = null;
  60921. this._parent = this._parent || this._getPhysicsParent();
  60922. if (!this.parent) {
  60923. this._physicsEngine.addImpostor(this);
  60924. }
  60925. };
  60926. PhysicsImpostor.prototype._getPhysicsParent = function () {
  60927. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  60928. var parentMesh = this.object.parent;
  60929. return parentMesh.physicsImpostor;
  60930. }
  60931. return;
  60932. };
  60933. /**
  60934. * Should a new body be generated.
  60935. */
  60936. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  60937. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  60938. };
  60939. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  60940. this.forceUpdate();
  60941. };
  60942. /**
  60943. * Force a regeneration of this or the parent's impostor's body.
  60944. * Use under cautious - This will remove all joints already implemented.
  60945. */
  60946. PhysicsImpostor.prototype.forceUpdate = function () {
  60947. this._init();
  60948. if (this.parent) {
  60949. this.parent.forceUpdate();
  60950. }
  60951. };
  60952. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  60953. /*public get mesh(): AbstractMesh {
  60954. return this._mesh;
  60955. }*/
  60956. /**
  60957. * Gets the body that holds this impostor. Either its own, or its parent.
  60958. */
  60959. get: function () {
  60960. return this._parent ? this._parent.physicsBody : this._physicsBody;
  60961. },
  60962. /**
  60963. * Set the physics body. Used mainly by the physics engine/plugin
  60964. */
  60965. set: function (physicsBody) {
  60966. if (this._physicsBody) {
  60967. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  60968. }
  60969. this._physicsBody = physicsBody;
  60970. this.resetUpdateFlags();
  60971. },
  60972. enumerable: true,
  60973. configurable: true
  60974. });
  60975. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  60976. get: function () {
  60977. return this._parent;
  60978. },
  60979. set: function (value) {
  60980. this._parent = value;
  60981. },
  60982. enumerable: true,
  60983. configurable: true
  60984. });
  60985. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  60986. this._bodyUpdateRequired = false;
  60987. };
  60988. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  60989. if (this.object.getBoundingInfo) {
  60990. var q = this.object.rotationQuaternion;
  60991. //reset rotation
  60992. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  60993. //calculate the world matrix with no rotation
  60994. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  60995. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  60996. //bring back the rotation
  60997. this.object.rotationQuaternion = q;
  60998. //calculate the world matrix with the new rotation
  60999. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  61000. return size;
  61001. }
  61002. else {
  61003. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  61004. }
  61005. };
  61006. PhysicsImpostor.prototype.getObjectCenter = function () {
  61007. if (this.object.getBoundingInfo) {
  61008. return this.object.getBoundingInfo().boundingBox.centerWorld;
  61009. }
  61010. else {
  61011. return this.object.position;
  61012. }
  61013. };
  61014. /**
  61015. * Get a specific parametes from the options parameter.
  61016. */
  61017. PhysicsImpostor.prototype.getParam = function (paramName) {
  61018. return this._options[paramName];
  61019. };
  61020. /**
  61021. * Sets a specific parameter in the options given to the physics plugin
  61022. */
  61023. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  61024. this._options[paramName] = value;
  61025. this._bodyUpdateRequired = true;
  61026. };
  61027. /**
  61028. * Specifically change the body's mass option. Won't recreate the physics body object
  61029. */
  61030. PhysicsImpostor.prototype.setMass = function (mass) {
  61031. if (this.getParam("mass") !== mass) {
  61032. this.setParam("mass", mass);
  61033. }
  61034. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  61035. };
  61036. PhysicsImpostor.prototype.getLinearVelocity = function () {
  61037. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  61038. };
  61039. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  61040. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  61041. };
  61042. PhysicsImpostor.prototype.getAngularVelocity = function () {
  61043. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  61044. };
  61045. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  61046. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  61047. };
  61048. /**
  61049. * Execute a function with the physics plugin native code.
  61050. * Provide a function the will have two variables - the world object and the physics body object.
  61051. */
  61052. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  61053. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  61054. };
  61055. /**
  61056. * Register a function that will be executed before the physics world is stepping forward.
  61057. */
  61058. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  61059. this._onBeforePhysicsStepCallbacks.push(func);
  61060. };
  61061. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  61062. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  61063. if (index > -1) {
  61064. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  61065. }
  61066. else {
  61067. BABYLON.Tools.Warn("Function to remove was not found");
  61068. }
  61069. };
  61070. /**
  61071. * Register a function that will be executed after the physics step
  61072. */
  61073. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  61074. this._onAfterPhysicsStepCallbacks.push(func);
  61075. };
  61076. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  61077. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  61078. if (index > -1) {
  61079. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  61080. }
  61081. else {
  61082. BABYLON.Tools.Warn("Function to remove was not found");
  61083. }
  61084. };
  61085. /**
  61086. * register a function that will be executed when this impostor collides against a different body.
  61087. */
  61088. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  61089. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  61090. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  61091. };
  61092. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  61093. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  61094. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  61095. if (index > -1) {
  61096. this._onPhysicsCollideCallbacks.splice(index, 1);
  61097. }
  61098. else {
  61099. BABYLON.Tools.Warn("Function to remove was not found");
  61100. }
  61101. };
  61102. /**
  61103. * Apply a force
  61104. */
  61105. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  61106. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  61107. };
  61108. /**
  61109. * Apply an impulse
  61110. */
  61111. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  61112. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  61113. };
  61114. /**
  61115. * A help function to create a joint.
  61116. */
  61117. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  61118. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  61119. this.addJoint(otherImpostor, joint);
  61120. };
  61121. /**
  61122. * Add a joint to this impostor with a different impostor.
  61123. */
  61124. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  61125. this._joints.push({
  61126. otherImpostor: otherImpostor,
  61127. joint: joint
  61128. });
  61129. this._physicsEngine.addJoint(this, otherImpostor, joint);
  61130. };
  61131. /**
  61132. * Will keep this body still, in a sleep mode.
  61133. */
  61134. PhysicsImpostor.prototype.sleep = function () {
  61135. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  61136. };
  61137. /**
  61138. * Wake the body up.
  61139. */
  61140. PhysicsImpostor.prototype.wakeUp = function () {
  61141. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  61142. };
  61143. PhysicsImpostor.prototype.clone = function (newObject) {
  61144. if (!newObject)
  61145. return null;
  61146. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  61147. };
  61148. PhysicsImpostor.prototype.dispose = function () {
  61149. var _this = this;
  61150. //no dispose if no physics engine is available.
  61151. if (!this._physicsEngine) {
  61152. return;
  61153. }
  61154. this._joints.forEach(function (j) {
  61155. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  61156. });
  61157. //dispose the physics body
  61158. this._physicsEngine.removeImpostor(this);
  61159. if (this.parent) {
  61160. this.parent.forceUpdate();
  61161. }
  61162. else {
  61163. /*this._object.getChildMeshes().forEach(function(mesh) {
  61164. if (mesh.physicsImpostor) {
  61165. if (disposeChildren) {
  61166. mesh.physicsImpostor.dispose();
  61167. mesh.physicsImpostor = null;
  61168. }
  61169. }
  61170. })*/
  61171. }
  61172. this._isDisposed = true;
  61173. };
  61174. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  61175. this._deltaPosition.copyFrom(position);
  61176. };
  61177. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  61178. if (!this._deltaRotation) {
  61179. this._deltaRotation = new BABYLON.Quaternion();
  61180. }
  61181. this._deltaRotation.copyFrom(rotation);
  61182. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  61183. };
  61184. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  61185. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  61186. };
  61187. PhysicsImpostor.prototype.getRadius = function () {
  61188. return this._physicsEngine.getPhysicsPlugin().getRadius(this);
  61189. };
  61190. /**
  61191. * Sync a bone with this impostor
  61192. * @param bone The bone to sync to the impostor.
  61193. * @param boneMesh The mesh that the bone is influencing.
  61194. * @param jointPivot The pivot of the joint / bone in local space.
  61195. * @param distToJoint Optional distance from the impostor to the joint.
  61196. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  61197. */
  61198. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  61199. var tempVec = PhysicsImpostor._tmpVecs[0];
  61200. var mesh = this.object;
  61201. if (adjustRotation) {
  61202. var tempQuat = PhysicsImpostor._tmpQuat;
  61203. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  61204. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  61205. }
  61206. else {
  61207. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  61208. }
  61209. tempVec.x = 0;
  61210. tempVec.y = 0;
  61211. tempVec.z = 0;
  61212. if (jointPivot) {
  61213. tempVec.x = jointPivot.x;
  61214. tempVec.y = jointPivot.y;
  61215. tempVec.z = jointPivot.z;
  61216. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  61217. if (distToJoint === undefined || distToJoint === null) {
  61218. distToJoint = jointPivot.length();
  61219. }
  61220. tempVec.x *= distToJoint;
  61221. tempVec.y *= distToJoint;
  61222. tempVec.z *= distToJoint;
  61223. }
  61224. if (bone.getParent()) {
  61225. tempVec.addInPlace(mesh.getAbsolutePosition());
  61226. bone.setAbsolutePosition(tempVec, boneMesh);
  61227. }
  61228. else {
  61229. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  61230. boneMesh.position.x -= tempVec.x;
  61231. boneMesh.position.y -= tempVec.y;
  61232. boneMesh.position.z -= tempVec.z;
  61233. }
  61234. };
  61235. /**
  61236. * Sync impostor to a bone
  61237. * @param bone The bone that the impostor will be synced to.
  61238. * @param boneMesh The mesh that the bone is influencing.
  61239. * @param jointPivot The pivot of the joint / bone in local space.
  61240. * @param distToJoint Optional distance from the impostor to the joint.
  61241. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  61242. * @param boneAxis Optional vector3 axis the bone is aligned with
  61243. */
  61244. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  61245. var mesh = this.object;
  61246. if (adjustRotation) {
  61247. var tempQuat = PhysicsImpostor._tmpQuat;
  61248. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  61249. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  61250. }
  61251. else {
  61252. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  61253. }
  61254. var pos = PhysicsImpostor._tmpVecs[0];
  61255. var boneDir = PhysicsImpostor._tmpVecs[1];
  61256. if (!boneAxis) {
  61257. boneAxis = PhysicsImpostor._tmpVecs[2];
  61258. boneAxis.x = 0;
  61259. boneAxis.y = 1;
  61260. boneAxis.z = 0;
  61261. }
  61262. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  61263. bone.getAbsolutePositionToRef(boneMesh, pos);
  61264. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  61265. distToJoint = jointPivot.length();
  61266. }
  61267. if (distToJoint !== undefined && distToJoint !== null) {
  61268. pos.x += boneDir.x * distToJoint;
  61269. pos.y += boneDir.y * distToJoint;
  61270. pos.z += boneDir.z * distToJoint;
  61271. }
  61272. mesh.setAbsolutePosition(pos);
  61273. };
  61274. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  61275. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  61276. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61277. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  61278. //Impostor types
  61279. PhysicsImpostor.NoImpostor = 0;
  61280. PhysicsImpostor.SphereImpostor = 1;
  61281. PhysicsImpostor.BoxImpostor = 2;
  61282. PhysicsImpostor.PlaneImpostor = 3;
  61283. PhysicsImpostor.MeshImpostor = 4;
  61284. PhysicsImpostor.CylinderImpostor = 7;
  61285. PhysicsImpostor.ParticleImpostor = 8;
  61286. PhysicsImpostor.HeightmapImpostor = 9;
  61287. return PhysicsImpostor;
  61288. }());
  61289. BABYLON.PhysicsImpostor = PhysicsImpostor;
  61290. })(BABYLON || (BABYLON = {}));
  61291. //# sourceMappingURL=babylon.physicsImpostor.js.map
  61292. var BABYLON;
  61293. (function (BABYLON) {
  61294. var PhysicsEngine = (function () {
  61295. function PhysicsEngine(gravity, _physicsPlugin) {
  61296. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  61297. this._physicsPlugin = _physicsPlugin;
  61298. //new methods and parameters
  61299. this._impostors = [];
  61300. this._joints = [];
  61301. if (!this._physicsPlugin.isSupported()) {
  61302. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  61303. + "Please make sure it is included.");
  61304. }
  61305. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  61306. this.setGravity(gravity);
  61307. this.setTimeStep();
  61308. }
  61309. PhysicsEngine.prototype.setGravity = function (gravity) {
  61310. this.gravity = gravity;
  61311. this._physicsPlugin.setGravity(this.gravity);
  61312. };
  61313. /**
  61314. * Set the time step of the physics engine.
  61315. * default is 1/60.
  61316. * To slow it down, enter 1/600 for example.
  61317. * To speed it up, 1/30
  61318. * @param {number} newTimeStep the new timestep to apply to this world.
  61319. */
  61320. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  61321. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  61322. this._physicsPlugin.setTimeStep(newTimeStep);
  61323. };
  61324. /**
  61325. * Get the time step of the physics engine.
  61326. */
  61327. PhysicsEngine.prototype.getTimeStep = function () {
  61328. return this._physicsPlugin.getTimeStep();
  61329. };
  61330. PhysicsEngine.prototype.dispose = function () {
  61331. this._impostors.forEach(function (impostor) {
  61332. impostor.dispose();
  61333. });
  61334. this._physicsPlugin.dispose();
  61335. };
  61336. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  61337. return this._physicsPlugin.name;
  61338. };
  61339. /**
  61340. * Adding a new impostor for the impostor tracking.
  61341. * This will be done by the impostor itself.
  61342. * @param {PhysicsImpostor} impostor the impostor to add
  61343. */
  61344. PhysicsEngine.prototype.addImpostor = function (impostor) {
  61345. impostor.uniqueId = this._impostors.push(impostor);
  61346. //if no parent, generate the body
  61347. if (!impostor.parent) {
  61348. this._physicsPlugin.generatePhysicsBody(impostor);
  61349. }
  61350. };
  61351. /**
  61352. * Remove an impostor from the engine.
  61353. * This impostor and its mesh will not longer be updated by the physics engine.
  61354. * @param {PhysicsImpostor} impostor the impostor to remove
  61355. */
  61356. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  61357. var index = this._impostors.indexOf(impostor);
  61358. if (index > -1) {
  61359. var removed = this._impostors.splice(index, 1);
  61360. //Is it needed?
  61361. if (removed.length) {
  61362. //this will also remove it from the world.
  61363. removed[0].physicsBody = null;
  61364. }
  61365. }
  61366. };
  61367. /**
  61368. * Add a joint to the physics engine
  61369. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  61370. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  61371. * @param {PhysicsJoint} the joint that will connect both impostors.
  61372. */
  61373. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  61374. var impostorJoint = {
  61375. mainImpostor: mainImpostor,
  61376. connectedImpostor: connectedImpostor,
  61377. joint: joint
  61378. };
  61379. joint.physicsPlugin = this._physicsPlugin;
  61380. this._joints.push(impostorJoint);
  61381. this._physicsPlugin.generateJoint(impostorJoint);
  61382. };
  61383. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  61384. var matchingJoints = this._joints.filter(function (impostorJoint) {
  61385. return (impostorJoint.connectedImpostor === connectedImpostor
  61386. && impostorJoint.joint === joint
  61387. && impostorJoint.mainImpostor === mainImpostor);
  61388. });
  61389. if (matchingJoints.length) {
  61390. this._physicsPlugin.removeJoint(matchingJoints[0]);
  61391. //TODO remove it from the list as well
  61392. }
  61393. };
  61394. /**
  61395. * Called by the scene. no need to call it.
  61396. */
  61397. PhysicsEngine.prototype._step = function (delta) {
  61398. var _this = this;
  61399. //check if any mesh has no body / requires an update
  61400. this._impostors.forEach(function (impostor) {
  61401. if (impostor.isBodyInitRequired()) {
  61402. _this._physicsPlugin.generatePhysicsBody(impostor);
  61403. }
  61404. });
  61405. if (delta > 0.1) {
  61406. delta = 0.1;
  61407. }
  61408. else if (delta <= 0) {
  61409. delta = 1.0 / 60.0;
  61410. }
  61411. this._physicsPlugin.executeStep(delta, this._impostors);
  61412. };
  61413. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  61414. return this._physicsPlugin;
  61415. };
  61416. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  61417. for (var i = 0; i < this._impostors.length; ++i) {
  61418. if (this._impostors[i].object === object) {
  61419. return this._impostors[i];
  61420. }
  61421. }
  61422. };
  61423. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  61424. for (var i = 0; i < this._impostors.length; ++i) {
  61425. if (this._impostors[i].physicsBody === body) {
  61426. return this._impostors[i];
  61427. }
  61428. }
  61429. };
  61430. // Statics
  61431. PhysicsEngine.Epsilon = 0.001;
  61432. return PhysicsEngine;
  61433. }());
  61434. BABYLON.PhysicsEngine = PhysicsEngine;
  61435. })(BABYLON || (BABYLON = {}));
  61436. //# sourceMappingURL=babylon.physicsEngine.js.map
  61437. var BABYLON;
  61438. (function (BABYLON) {
  61439. var CannonJSPlugin = (function () {
  61440. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  61441. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  61442. if (iterations === void 0) { iterations = 10; }
  61443. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  61444. this.name = "CannonJSPlugin";
  61445. this._physicsMaterials = [];
  61446. this._fixedTimeStep = 1 / 60;
  61447. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  61448. this._currentCollisionGroup = 2;
  61449. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  61450. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  61451. this._tmpPosition = BABYLON.Vector3.Zero();
  61452. this._tmpQuaternion = new BABYLON.Quaternion();
  61453. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  61454. this._tmpDeltaRotation = new BABYLON.Quaternion();
  61455. this._tmpUnityRotation = new BABYLON.Quaternion();
  61456. if (!this.isSupported()) {
  61457. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  61458. return;
  61459. }
  61460. this.world = new CANNON.World();
  61461. this.world.broadphase = new CANNON.NaiveBroadphase();
  61462. this.world.solver.iterations = iterations;
  61463. }
  61464. CannonJSPlugin.prototype.setGravity = function (gravity) {
  61465. this.world.gravity.copy(gravity);
  61466. };
  61467. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  61468. this._fixedTimeStep = timeStep;
  61469. };
  61470. CannonJSPlugin.prototype.getTimeStep = function () {
  61471. return this._fixedTimeStep;
  61472. };
  61473. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  61474. // Delta is in seconds, should be provided in milliseconds
  61475. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  61476. };
  61477. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  61478. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  61479. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  61480. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  61481. };
  61482. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  61483. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  61484. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  61485. impostor.physicsBody.applyForce(impulse, worldPoint);
  61486. };
  61487. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  61488. //parent-child relationship. Does this impostor has a parent impostor?
  61489. if (impostor.parent) {
  61490. if (impostor.physicsBody) {
  61491. this.removePhysicsBody(impostor);
  61492. //TODO is that needed?
  61493. impostor.forceUpdate();
  61494. }
  61495. return;
  61496. }
  61497. //should a new body be created for this impostor?
  61498. if (impostor.isBodyInitRequired()) {
  61499. var shape = this._createShape(impostor);
  61500. //unregister events, if body is being changed
  61501. var oldBody = impostor.physicsBody;
  61502. if (oldBody) {
  61503. this.removePhysicsBody(impostor);
  61504. }
  61505. //create the body and material
  61506. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  61507. var bodyCreationObject = {
  61508. mass: impostor.getParam("mass"),
  61509. material: material
  61510. };
  61511. // A simple extend, in case native options were used.
  61512. var nativeOptions = impostor.getParam("nativeOptions");
  61513. for (var key in nativeOptions) {
  61514. if (nativeOptions.hasOwnProperty(key)) {
  61515. bodyCreationObject[key] = nativeOptions[key];
  61516. }
  61517. }
  61518. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  61519. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  61520. this.world.addEventListener("preStep", impostor.beforeStep);
  61521. this.world.addEventListener("postStep", impostor.afterStep);
  61522. impostor.physicsBody.addShape(shape);
  61523. this.world.add(impostor.physicsBody);
  61524. //try to keep the body moving in the right direction by taking old properties.
  61525. //Should be tested!
  61526. if (oldBody) {
  61527. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  61528. impostor.physicsBody[param].copy(oldBody[param]);
  61529. });
  61530. }
  61531. this._processChildMeshes(impostor);
  61532. }
  61533. //now update the body's transformation
  61534. this._updatePhysicsBodyTransformation(impostor);
  61535. };
  61536. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  61537. var _this = this;
  61538. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  61539. if (meshChildren.length) {
  61540. var processMesh = function (localPosition, mesh) {
  61541. var childImpostor = mesh.getPhysicsImpostor();
  61542. if (childImpostor) {
  61543. var parent = childImpostor.parent;
  61544. if (parent !== mainImpostor) {
  61545. var localPosition = mesh.position;
  61546. if (childImpostor.physicsBody) {
  61547. _this.removePhysicsBody(childImpostor);
  61548. childImpostor.physicsBody = null;
  61549. }
  61550. childImpostor.parent = mainImpostor;
  61551. childImpostor.resetUpdateFlags();
  61552. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  61553. //Add the mass of the children.
  61554. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  61555. }
  61556. }
  61557. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  61558. };
  61559. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  61560. }
  61561. };
  61562. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  61563. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  61564. this.world.removeEventListener("preStep", impostor.beforeStep);
  61565. this.world.removeEventListener("postStep", impostor.afterStep);
  61566. this.world.remove(impostor.physicsBody);
  61567. };
  61568. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  61569. var mainBody = impostorJoint.mainImpostor.physicsBody;
  61570. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  61571. if (!mainBody || !connectedBody) {
  61572. return;
  61573. }
  61574. var constraint;
  61575. var jointData = impostorJoint.joint.jointData;
  61576. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  61577. var constraintData = {
  61578. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  61579. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  61580. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  61581. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  61582. maxForce: jointData.nativeParams.maxForce,
  61583. collideConnected: !!jointData.collision
  61584. };
  61585. switch (impostorJoint.joint.type) {
  61586. case BABYLON.PhysicsJoint.HingeJoint:
  61587. case BABYLON.PhysicsJoint.Hinge2Joint:
  61588. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  61589. break;
  61590. case BABYLON.PhysicsJoint.DistanceJoint:
  61591. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  61592. break;
  61593. case BABYLON.PhysicsJoint.SpringJoint:
  61594. var springData = jointData;
  61595. constraint = new CANNON.Spring(mainBody, connectedBody, {
  61596. restLength: springData.length,
  61597. stiffness: springData.stiffness,
  61598. damping: springData.damping,
  61599. localAnchorA: constraintData.pivotA,
  61600. localAnchorB: constraintData.pivotB
  61601. });
  61602. break;
  61603. case BABYLON.PhysicsJoint.LockJoint:
  61604. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  61605. break;
  61606. case BABYLON.PhysicsJoint.PointToPointJoint:
  61607. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  61608. default:
  61609. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  61610. break;
  61611. }
  61612. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  61613. constraint.collideConnected = !!jointData.collision;
  61614. impostorJoint.joint.physicsJoint = constraint;
  61615. //don't add spring as constraint, as it is not one.
  61616. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  61617. this.world.addConstraint(constraint);
  61618. }
  61619. else {
  61620. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  61621. constraint.applyForce();
  61622. });
  61623. }
  61624. };
  61625. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  61626. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  61627. };
  61628. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  61629. var index;
  61630. var mat;
  61631. for (index = 0; index < this._physicsMaterials.length; index++) {
  61632. mat = this._physicsMaterials[index];
  61633. if (mat.friction === friction && mat.restitution === restitution) {
  61634. return mat;
  61635. }
  61636. }
  61637. var currentMat = new CANNON.Material(name);
  61638. currentMat.friction = friction;
  61639. currentMat.restitution = restitution;
  61640. this._physicsMaterials.push(currentMat);
  61641. return currentMat;
  61642. };
  61643. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  61644. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  61645. };
  61646. CannonJSPlugin.prototype._createShape = function (impostor) {
  61647. var object = impostor.object;
  61648. var returnValue;
  61649. var extendSize = impostor.getObjectExtendSize();
  61650. switch (impostor.type) {
  61651. case BABYLON.PhysicsImpostor.SphereImpostor:
  61652. var radiusX = extendSize.x;
  61653. var radiusY = extendSize.y;
  61654. var radiusZ = extendSize.z;
  61655. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  61656. break;
  61657. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  61658. case BABYLON.PhysicsImpostor.CylinderImpostor:
  61659. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  61660. break;
  61661. case BABYLON.PhysicsImpostor.BoxImpostor:
  61662. var box = extendSize.scale(0.5);
  61663. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  61664. break;
  61665. case BABYLON.PhysicsImpostor.PlaneImpostor:
  61666. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  61667. returnValue = new CANNON.Plane();
  61668. break;
  61669. case BABYLON.PhysicsImpostor.MeshImpostor:
  61670. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  61671. var rawFaces = object.getIndices ? object.getIndices() : [];
  61672. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  61673. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  61674. break;
  61675. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  61676. returnValue = this._createHeightmap(object);
  61677. break;
  61678. case BABYLON.PhysicsImpostor.ParticleImpostor:
  61679. returnValue = new CANNON.Particle();
  61680. break;
  61681. }
  61682. return returnValue;
  61683. };
  61684. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  61685. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61686. var matrix = [];
  61687. //For now pointDepth will not be used and will be automatically calculated.
  61688. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  61689. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  61690. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSizeWorld.x, object.getBoundingInfo().boundingBox.extendSizeWorld.z);
  61691. var elementSize = dim * 2 / arraySize;
  61692. var minY = object.getBoundingInfo().boundingBox.extendSizeWorld.y;
  61693. for (var i = 0; i < pos.length; i = i + 3) {
  61694. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  61695. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  61696. var y = pos[i + 1] + minY;
  61697. if (!matrix[x]) {
  61698. matrix[x] = [];
  61699. }
  61700. if (!matrix[x][z]) {
  61701. matrix[x][z] = y;
  61702. }
  61703. matrix[x][z] = Math.max(y, matrix[x][z]);
  61704. }
  61705. for (var x = 0; x <= arraySize; ++x) {
  61706. if (!matrix[x]) {
  61707. var loc = 1;
  61708. while (!matrix[(x + loc) % arraySize]) {
  61709. loc++;
  61710. }
  61711. matrix[x] = matrix[(x + loc) % arraySize].slice();
  61712. //console.log("missing x", x);
  61713. }
  61714. for (var z = 0; z <= arraySize; ++z) {
  61715. if (!matrix[x][z]) {
  61716. var loc = 1;
  61717. var newValue;
  61718. while (newValue === undefined) {
  61719. newValue = matrix[x][(z + loc++) % arraySize];
  61720. }
  61721. matrix[x][z] = newValue;
  61722. }
  61723. }
  61724. }
  61725. var shape = new CANNON.Heightfield(matrix, {
  61726. elementSize: elementSize
  61727. });
  61728. //For future reference, needed for body transformation
  61729. shape.minY = minY;
  61730. return shape;
  61731. };
  61732. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  61733. var object = impostor.object;
  61734. //make sure it is updated...
  61735. object.computeWorldMatrix && object.computeWorldMatrix(true);
  61736. // The delta between the mesh position and the mesh bounding box center
  61737. var center = impostor.getObjectCenter();
  61738. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  61739. this._tmpPosition.copyFrom(center);
  61740. var quaternion = object.rotationQuaternion;
  61741. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  61742. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  61743. //-90 DEG in X, precalculated
  61744. quaternion = quaternion.multiply(this._minus90X);
  61745. //Invert! (Precalculated, 90 deg in X)
  61746. //No need to clone. this will never change.
  61747. impostor.setDeltaRotation(this._plus90X);
  61748. }
  61749. //If it is a heightfield, if should be centered.
  61750. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  61751. var mesh = object;
  61752. //calculate the correct body position:
  61753. var rotationQuaternion = mesh.rotationQuaternion;
  61754. mesh.rotationQuaternion = this._tmpUnityRotation;
  61755. mesh.computeWorldMatrix(true);
  61756. //get original center with no rotation
  61757. var c = center.clone();
  61758. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  61759. //rotation is back
  61760. mesh.rotationQuaternion = rotationQuaternion;
  61761. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  61762. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSizeWorld.x, 0, -mesh.getBoundingInfo().boundingBox.extendSizeWorld.z);
  61763. mesh.setPivotMatrix(p);
  61764. mesh.computeWorldMatrix(true);
  61765. //calculate the translation
  61766. var translation = mesh.getBoundingInfo().boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  61767. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSizeWorld.y, translation.z);
  61768. //add it inverted to the delta
  61769. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.centerWorld.subtract(c));
  61770. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSizeWorld.y;
  61771. mesh.setPivotMatrix(oldPivot);
  61772. mesh.computeWorldMatrix(true);
  61773. }
  61774. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  61775. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  61776. this._tmpPosition.copyFrom(object.position);
  61777. }
  61778. impostor.setDeltaPosition(this._tmpDeltaPosition);
  61779. //Now update the impostor object
  61780. impostor.physicsBody.position.copy(this._tmpPosition);
  61781. impostor.physicsBody.quaternion.copy(quaternion);
  61782. };
  61783. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  61784. impostor.object.position.copyFrom(impostor.physicsBody.position);
  61785. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  61786. };
  61787. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  61788. impostor.physicsBody.position.copy(newPosition);
  61789. impostor.physicsBody.quaternion.copy(newRotation);
  61790. };
  61791. CannonJSPlugin.prototype.isSupported = function () {
  61792. return window.CANNON !== undefined;
  61793. };
  61794. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  61795. impostor.physicsBody.velocity.copy(velocity);
  61796. };
  61797. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  61798. impostor.physicsBody.angularVelocity.copy(velocity);
  61799. };
  61800. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  61801. var v = impostor.physicsBody.velocity;
  61802. if (!v)
  61803. return null;
  61804. return new BABYLON.Vector3(v.x, v.y, v.z);
  61805. };
  61806. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  61807. var v = impostor.physicsBody.angularVelocity;
  61808. if (!v)
  61809. return null;
  61810. return new BABYLON.Vector3(v.x, v.y, v.z);
  61811. };
  61812. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  61813. impostor.physicsBody.mass = mass;
  61814. impostor.physicsBody.updateMassProperties();
  61815. };
  61816. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  61817. return impostor.physicsBody.mass;
  61818. };
  61819. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  61820. return impostor.physicsBody.material.friction;
  61821. };
  61822. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  61823. impostor.physicsBody.material.friction = friction;
  61824. };
  61825. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  61826. return impostor.physicsBody.material.restitution;
  61827. };
  61828. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  61829. impostor.physicsBody.material.restitution = restitution;
  61830. };
  61831. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  61832. impostor.physicsBody.sleep();
  61833. };
  61834. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  61835. impostor.physicsBody.wakeUp();
  61836. };
  61837. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  61838. joint.physicsJoint.distance = maxDistance;
  61839. };
  61840. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  61841. if (!motorIndex) {
  61842. joint.physicsJoint.enableMotor();
  61843. }
  61844. };
  61845. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  61846. if (!motorIndex) {
  61847. joint.physicsJoint.disableMotor();
  61848. }
  61849. };
  61850. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  61851. if (!motorIndex) {
  61852. joint.physicsJoint.enableMotor();
  61853. joint.physicsJoint.setMotorSpeed(speed);
  61854. if (maxForce) {
  61855. this.setLimit(joint, maxForce);
  61856. }
  61857. }
  61858. };
  61859. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  61860. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  61861. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  61862. };
  61863. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  61864. var body = impostor.physicsBody;
  61865. mesh.position.x = body.position.x;
  61866. mesh.position.y = body.position.y;
  61867. mesh.position.z = body.position.z;
  61868. mesh.rotationQuaternion.x = body.quaternion.x;
  61869. mesh.rotationQuaternion.y = body.quaternion.y;
  61870. mesh.rotationQuaternion.z = body.quaternion.z;
  61871. mesh.rotationQuaternion.w = body.quaternion.w;
  61872. };
  61873. CannonJSPlugin.prototype.getRadius = function (impostor) {
  61874. var shape = impostor.physicsBody.shapes[0];
  61875. return shape.boundingSphereRadius;
  61876. };
  61877. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  61878. var shape = impostor.physicsBody.shapes[0];
  61879. result.x = shape.halfExtents.x * 2;
  61880. result.y = shape.halfExtents.y * 2;
  61881. result.z = shape.halfExtents.z * 2;
  61882. };
  61883. CannonJSPlugin.prototype.dispose = function () {
  61884. };
  61885. return CannonJSPlugin;
  61886. }());
  61887. BABYLON.CannonJSPlugin = CannonJSPlugin;
  61888. })(BABYLON || (BABYLON = {}));
  61889. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  61890. var BABYLON;
  61891. (function (BABYLON) {
  61892. var OimoJSPlugin = (function () {
  61893. function OimoJSPlugin(iterations) {
  61894. this.name = "OimoJSPlugin";
  61895. this._tmpImpostorsArray = [];
  61896. this._tmpPositionVector = BABYLON.Vector3.Zero();
  61897. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  61898. this.world.worldscale(1);
  61899. this.world.clear();
  61900. //making sure no stats are calculated
  61901. this.world.isNoStat = true;
  61902. }
  61903. OimoJSPlugin.prototype.setGravity = function (gravity) {
  61904. this.world.gravity.copy(gravity);
  61905. };
  61906. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  61907. this.world.timeStep = timeStep;
  61908. };
  61909. OimoJSPlugin.prototype.getTimeStep = function () {
  61910. return this.world.timeStep;
  61911. };
  61912. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  61913. var _this = this;
  61914. impostors.forEach(function (impostor) {
  61915. impostor.beforeStep();
  61916. });
  61917. this.world.step();
  61918. impostors.forEach(function (impostor) {
  61919. impostor.afterStep();
  61920. //update the ordered impostors array
  61921. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  61922. });
  61923. //check for collisions
  61924. var contact = this.world.contacts;
  61925. while (contact !== null) {
  61926. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  61927. contact = contact.next;
  61928. continue;
  61929. }
  61930. //is this body colliding with any other? get the impostor
  61931. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  61932. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  61933. if (!mainImpostor || !collidingImpostor) {
  61934. contact = contact.next;
  61935. continue;
  61936. }
  61937. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  61938. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  61939. contact = contact.next;
  61940. }
  61941. };
  61942. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  61943. var mass = impostor.physicsBody.massInfo.mass;
  61944. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  61945. };
  61946. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  61947. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  61948. this.applyImpulse(impostor, force, contactPoint);
  61949. };
  61950. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  61951. var _this = this;
  61952. //parent-child relationship. Does this impostor has a parent impostor?
  61953. if (impostor.parent) {
  61954. if (impostor.physicsBody) {
  61955. this.removePhysicsBody(impostor);
  61956. //TODO is that needed?
  61957. impostor.forceUpdate();
  61958. }
  61959. return;
  61960. }
  61961. if (impostor.isBodyInitRequired()) {
  61962. var bodyConfig = {
  61963. name: impostor.uniqueId,
  61964. //Oimo must have mass, also for static objects.
  61965. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  61966. size: [],
  61967. type: [],
  61968. pos: [],
  61969. rot: [],
  61970. move: impostor.getParam("mass") !== 0,
  61971. //Supporting older versions of Oimo
  61972. world: this.world
  61973. };
  61974. var impostors = [impostor];
  61975. var addToArray = function (parent) {
  61976. if (!parent.getChildMeshes)
  61977. return;
  61978. parent.getChildMeshes().forEach(function (m) {
  61979. if (m.physicsImpostor) {
  61980. impostors.push(m.physicsImpostor);
  61981. m.physicsImpostor._init();
  61982. }
  61983. });
  61984. };
  61985. addToArray(impostor.object);
  61986. var checkWithEpsilon_1 = function (value) {
  61987. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  61988. };
  61989. impostors.forEach(function (i) {
  61990. //get the correct bounding box
  61991. var oldQuaternion = i.object.rotationQuaternion;
  61992. var rot = new OIMO.Euler().setFromQuaternion({
  61993. x: impostor.object.rotationQuaternion.x,
  61994. y: impostor.object.rotationQuaternion.y,
  61995. z: impostor.object.rotationQuaternion.z,
  61996. s: impostor.object.rotationQuaternion.w
  61997. });
  61998. var extendSize = i.getObjectExtendSize();
  61999. if (i === impostor) {
  62000. var center = impostor.getObjectCenter();
  62001. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  62002. //Can also use Array.prototype.push.apply
  62003. bodyConfig.pos.push(center.x);
  62004. bodyConfig.pos.push(center.y);
  62005. bodyConfig.pos.push(center.z);
  62006. //tmp solution
  62007. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  62008. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  62009. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  62010. }
  62011. else {
  62012. bodyConfig.pos.push(i.object.position.x);
  62013. bodyConfig.pos.push(i.object.position.y);
  62014. bodyConfig.pos.push(i.object.position.z);
  62015. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  62016. bodyConfig.rot.push(0);
  62017. bodyConfig.rot.push(0);
  62018. bodyConfig.rot.push(0);
  62019. }
  62020. // register mesh
  62021. switch (i.type) {
  62022. case BABYLON.PhysicsImpostor.ParticleImpostor:
  62023. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  62024. case BABYLON.PhysicsImpostor.SphereImpostor:
  62025. var radiusX = extendSize.x;
  62026. var radiusY = extendSize.y;
  62027. var radiusZ = extendSize.z;
  62028. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  62029. bodyConfig.type.push('sphere');
  62030. //due to the way oimo works with compounds, add 3 times
  62031. bodyConfig.size.push(size);
  62032. bodyConfig.size.push(size);
  62033. bodyConfig.size.push(size);
  62034. break;
  62035. case BABYLON.PhysicsImpostor.CylinderImpostor:
  62036. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  62037. var sizeY = checkWithEpsilon_1(extendSize.y);
  62038. bodyConfig.type.push('cylinder');
  62039. bodyConfig.size.push(sizeX);
  62040. bodyConfig.size.push(sizeY);
  62041. //due to the way oimo works with compounds, add one more value.
  62042. bodyConfig.size.push(sizeY);
  62043. break;
  62044. case BABYLON.PhysicsImpostor.PlaneImpostor:
  62045. case BABYLON.PhysicsImpostor.BoxImpostor:
  62046. default:
  62047. var sizeX = checkWithEpsilon_1(extendSize.x);
  62048. var sizeY = checkWithEpsilon_1(extendSize.y);
  62049. var sizeZ = checkWithEpsilon_1(extendSize.z);
  62050. bodyConfig.type.push('box');
  62051. bodyConfig.size.push(sizeX);
  62052. bodyConfig.size.push(sizeY);
  62053. bodyConfig.size.push(sizeZ);
  62054. break;
  62055. }
  62056. //actually not needed, but hey...
  62057. i.object.rotationQuaternion = oldQuaternion;
  62058. });
  62059. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  62060. }
  62061. else {
  62062. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  62063. }
  62064. impostor.setDeltaPosition(this._tmpPositionVector);
  62065. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  62066. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  62067. };
  62068. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  62069. //impostor.physicsBody.dispose();
  62070. //Same as : (older oimo versions)
  62071. this.world.removeRigidBody(impostor.physicsBody);
  62072. };
  62073. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  62074. var mainBody = impostorJoint.mainImpostor.physicsBody;
  62075. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  62076. if (!mainBody || !connectedBody) {
  62077. return;
  62078. }
  62079. var jointData = impostorJoint.joint.jointData;
  62080. var options = jointData.nativeParams || {};
  62081. var type;
  62082. var nativeJointData = {
  62083. body1: mainBody,
  62084. body2: connectedBody,
  62085. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  62086. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  62087. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  62088. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  62089. min: options.min,
  62090. max: options.max,
  62091. collision: options.collision || jointData.collision,
  62092. spring: options.spring,
  62093. //supporting older version of Oimo
  62094. world: this.world
  62095. };
  62096. switch (impostorJoint.joint.type) {
  62097. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  62098. type = "jointBall";
  62099. break;
  62100. case BABYLON.PhysicsJoint.SpringJoint:
  62101. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  62102. var springData = jointData;
  62103. nativeJointData.min = springData.length || nativeJointData.min;
  62104. //Max should also be set, just make sure it is at least min
  62105. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  62106. case BABYLON.PhysicsJoint.DistanceJoint:
  62107. type = "jointDistance";
  62108. nativeJointData.max = jointData.maxDistance;
  62109. break;
  62110. case BABYLON.PhysicsJoint.PrismaticJoint:
  62111. type = "jointPrisme";
  62112. break;
  62113. case BABYLON.PhysicsJoint.SliderJoint:
  62114. type = "jointSlide";
  62115. break;
  62116. case BABYLON.PhysicsJoint.WheelJoint:
  62117. type = "jointWheel";
  62118. break;
  62119. case BABYLON.PhysicsJoint.HingeJoint:
  62120. default:
  62121. type = "jointHinge";
  62122. break;
  62123. }
  62124. nativeJointData.type = type;
  62125. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  62126. };
  62127. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  62128. //Bug in Oimo prevents us from disposing a joint in the playground
  62129. //joint.joint.physicsJoint.dispose();
  62130. //So we will bruteforce it!
  62131. try {
  62132. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  62133. }
  62134. catch (e) {
  62135. BABYLON.Tools.Warn(e);
  62136. }
  62137. };
  62138. OimoJSPlugin.prototype.isSupported = function () {
  62139. return OIMO !== undefined;
  62140. };
  62141. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  62142. if (!impostor.physicsBody.sleeping) {
  62143. //TODO check that
  62144. if (impostor.physicsBody.shapes.next) {
  62145. var parentShape = this._getLastShape(impostor.physicsBody);
  62146. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  62147. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  62148. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  62149. }
  62150. else {
  62151. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  62152. }
  62153. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  62154. impostor.object.rotationQuaternion.normalize();
  62155. }
  62156. };
  62157. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  62158. var body = impostor.physicsBody;
  62159. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  62160. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  62161. body.syncShapes();
  62162. body.awake();
  62163. };
  62164. OimoJSPlugin.prototype._getLastShape = function (body) {
  62165. var lastShape = body.shapes;
  62166. while (lastShape.next) {
  62167. lastShape = lastShape.next;
  62168. }
  62169. return lastShape;
  62170. };
  62171. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  62172. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  62173. };
  62174. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  62175. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  62176. };
  62177. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  62178. var v = impostor.physicsBody.linearVelocity;
  62179. if (!v)
  62180. return null;
  62181. return new BABYLON.Vector3(v.x, v.y, v.z);
  62182. };
  62183. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  62184. var v = impostor.physicsBody.angularVelocity;
  62185. if (!v)
  62186. return null;
  62187. return new BABYLON.Vector3(v.x, v.y, v.z);
  62188. };
  62189. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  62190. var staticBody = mass === 0;
  62191. //this will actually set the body's density and not its mass.
  62192. //But this is how oimo treats the mass variable.
  62193. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  62194. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  62195. };
  62196. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  62197. return impostor.physicsBody.shapes.density;
  62198. };
  62199. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  62200. return impostor.physicsBody.shapes.friction;
  62201. };
  62202. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  62203. impostor.physicsBody.shapes.friction = friction;
  62204. };
  62205. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  62206. return impostor.physicsBody.shapes.restitution;
  62207. };
  62208. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  62209. impostor.physicsBody.shapes.restitution = restitution;
  62210. };
  62211. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  62212. impostor.physicsBody.sleep();
  62213. };
  62214. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  62215. impostor.physicsBody.awake();
  62216. };
  62217. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  62218. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  62219. if (minDistance !== void 0) {
  62220. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  62221. }
  62222. };
  62223. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  62224. //TODO separate rotational and transational motors.
  62225. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  62226. if (motor) {
  62227. motor.setMotor(speed, maxForce);
  62228. }
  62229. };
  62230. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  62231. //TODO separate rotational and transational motors.
  62232. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  62233. if (motor) {
  62234. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  62235. }
  62236. };
  62237. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  62238. var body = impostor.physicsBody;
  62239. mesh.position.x = body.position.x;
  62240. mesh.position.y = body.position.y;
  62241. mesh.position.z = body.position.z;
  62242. mesh.rotationQuaternion.x = body.orientation.x;
  62243. mesh.rotationQuaternion.y = body.orientation.y;
  62244. mesh.rotationQuaternion.z = body.orientation.z;
  62245. mesh.rotationQuaternion.w = body.orientation.s;
  62246. };
  62247. OimoJSPlugin.prototype.getRadius = function (impostor) {
  62248. return impostor.physicsBody.shapes.radius;
  62249. };
  62250. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  62251. var shape = impostor.physicsBody.shapes;
  62252. result.x = shape.halfWidth * 2;
  62253. result.y = shape.halfHeight * 2;
  62254. result.z = shape.halfDepth * 2;
  62255. };
  62256. OimoJSPlugin.prototype.dispose = function () {
  62257. this.world.clear();
  62258. };
  62259. return OimoJSPlugin;
  62260. }());
  62261. BABYLON.OimoJSPlugin = OimoJSPlugin;
  62262. })(BABYLON || (BABYLON = {}));
  62263. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  62264. var BABYLON;
  62265. (function (BABYLON) {
  62266. var Internals;
  62267. (function (Internals) {
  62268. /*
  62269. * Based on jsTGALoader - Javascript loader for TGA file
  62270. * By Vincent Thibault
  62271. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  62272. */
  62273. var TGATools = (function () {
  62274. function TGATools() {
  62275. }
  62276. TGATools.GetTGAHeader = function (data) {
  62277. var offset = 0;
  62278. var header = {
  62279. id_length: data[offset++],
  62280. colormap_type: data[offset++],
  62281. image_type: data[offset++],
  62282. colormap_index: data[offset++] | data[offset++] << 8,
  62283. colormap_length: data[offset++] | data[offset++] << 8,
  62284. colormap_size: data[offset++],
  62285. origin: [
  62286. data[offset++] | data[offset++] << 8,
  62287. data[offset++] | data[offset++] << 8
  62288. ],
  62289. width: data[offset++] | data[offset++] << 8,
  62290. height: data[offset++] | data[offset++] << 8,
  62291. pixel_size: data[offset++],
  62292. flags: data[offset++]
  62293. };
  62294. return header;
  62295. };
  62296. TGATools.UploadContent = function (gl, data) {
  62297. // Not enough data to contain header ?
  62298. if (data.length < 19) {
  62299. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  62300. return;
  62301. }
  62302. // Read Header
  62303. var offset = 18;
  62304. var header = TGATools.GetTGAHeader(data);
  62305. // Assume it's a valid Targa file.
  62306. if (header.id_length + offset > data.length) {
  62307. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  62308. return;
  62309. }
  62310. // Skip not needed data
  62311. offset += header.id_length;
  62312. var use_rle = false;
  62313. var use_pal = false;
  62314. var use_rgb = false;
  62315. var use_grey = false;
  62316. // Get some informations.
  62317. switch (header.image_type) {
  62318. case TGATools._TYPE_RLE_INDEXED:
  62319. use_rle = true;
  62320. case TGATools._TYPE_INDEXED:
  62321. use_pal = true;
  62322. break;
  62323. case TGATools._TYPE_RLE_RGB:
  62324. use_rle = true;
  62325. case TGATools._TYPE_RGB:
  62326. use_rgb = true;
  62327. break;
  62328. case TGATools._TYPE_RLE_GREY:
  62329. use_rle = true;
  62330. case TGATools._TYPE_GREY:
  62331. use_grey = true;
  62332. break;
  62333. }
  62334. var pixel_data;
  62335. var numAlphaBits = header.flags & 0xf;
  62336. var pixel_size = header.pixel_size >> 3;
  62337. var pixel_total = header.width * header.height * pixel_size;
  62338. // Read palettes
  62339. var palettes;
  62340. if (use_pal) {
  62341. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  62342. }
  62343. // Read LRE
  62344. if (use_rle) {
  62345. pixel_data = new Uint8Array(pixel_total);
  62346. var c, count, i;
  62347. var localOffset = 0;
  62348. var pixels = new Uint8Array(pixel_size);
  62349. while (offset < pixel_total && localOffset < pixel_total) {
  62350. c = data[offset++];
  62351. count = (c & 0x7f) + 1;
  62352. // RLE pixels
  62353. if (c & 0x80) {
  62354. // Bind pixel tmp array
  62355. for (i = 0; i < pixel_size; ++i) {
  62356. pixels[i] = data[offset++];
  62357. }
  62358. // Copy pixel array
  62359. for (i = 0; i < count; ++i) {
  62360. pixel_data.set(pixels, localOffset + i * pixel_size);
  62361. }
  62362. localOffset += pixel_size * count;
  62363. }
  62364. else {
  62365. count *= pixel_size;
  62366. for (i = 0; i < count; ++i) {
  62367. pixel_data[localOffset + i] = data[offset++];
  62368. }
  62369. localOffset += count;
  62370. }
  62371. }
  62372. }
  62373. else {
  62374. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  62375. }
  62376. // Load to texture
  62377. var x_start, y_start, x_step, y_step, y_end, x_end;
  62378. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  62379. default:
  62380. case TGATools._ORIGIN_UL:
  62381. x_start = 0;
  62382. x_step = 1;
  62383. x_end = header.width;
  62384. y_start = 0;
  62385. y_step = 1;
  62386. y_end = header.height;
  62387. break;
  62388. case TGATools._ORIGIN_BL:
  62389. x_start = 0;
  62390. x_step = 1;
  62391. x_end = header.width;
  62392. y_start = header.height - 1;
  62393. y_step = -1;
  62394. y_end = -1;
  62395. break;
  62396. case TGATools._ORIGIN_UR:
  62397. x_start = header.width - 1;
  62398. x_step = -1;
  62399. x_end = -1;
  62400. y_start = 0;
  62401. y_step = 1;
  62402. y_end = header.height;
  62403. break;
  62404. case TGATools._ORIGIN_BR:
  62405. x_start = header.width - 1;
  62406. x_step = -1;
  62407. x_end = -1;
  62408. y_start = header.height - 1;
  62409. y_step = -1;
  62410. y_end = -1;
  62411. break;
  62412. }
  62413. // Load the specify method
  62414. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  62415. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  62416. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  62417. };
  62418. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  62419. var image = pixel_data, colormap = palettes;
  62420. var width = header.width, height = header.height;
  62421. var color, i = 0, x, y;
  62422. var imageData = new Uint8Array(width * height * 4);
  62423. for (y = y_start; y !== y_end; y += y_step) {
  62424. for (x = x_start; x !== x_end; x += x_step, i++) {
  62425. color = image[i];
  62426. imageData[(x + width * y) * 4 + 3] = 255;
  62427. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  62428. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  62429. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  62430. }
  62431. }
  62432. return imageData;
  62433. };
  62434. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  62435. var image = pixel_data;
  62436. var width = header.width, height = header.height;
  62437. var color, i = 0, x, y;
  62438. var imageData = new Uint8Array(width * height * 4);
  62439. for (y = y_start; y !== y_end; y += y_step) {
  62440. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  62441. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  62442. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  62443. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  62444. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  62445. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  62446. }
  62447. }
  62448. return imageData;
  62449. };
  62450. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  62451. var image = pixel_data;
  62452. var width = header.width, height = header.height;
  62453. var i = 0, x, y;
  62454. var imageData = new Uint8Array(width * height * 4);
  62455. for (y = y_start; y !== y_end; y += y_step) {
  62456. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  62457. imageData[(x + width * y) * 4 + 3] = 255;
  62458. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  62459. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  62460. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  62461. }
  62462. }
  62463. return imageData;
  62464. };
  62465. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  62466. var image = pixel_data;
  62467. var width = header.width, height = header.height;
  62468. var i = 0, x, y;
  62469. var imageData = new Uint8Array(width * height * 4);
  62470. for (y = y_start; y !== y_end; y += y_step) {
  62471. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  62472. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  62473. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  62474. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  62475. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  62476. }
  62477. }
  62478. return imageData;
  62479. };
  62480. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  62481. var image = pixel_data;
  62482. var width = header.width, height = header.height;
  62483. var color, i = 0, x, y;
  62484. var imageData = new Uint8Array(width * height * 4);
  62485. for (y = y_start; y !== y_end; y += y_step) {
  62486. for (x = x_start; x !== x_end; x += x_step, i++) {
  62487. color = image[i];
  62488. imageData[(x + width * y) * 4 + 0] = color;
  62489. imageData[(x + width * y) * 4 + 1] = color;
  62490. imageData[(x + width * y) * 4 + 2] = color;
  62491. imageData[(x + width * y) * 4 + 3] = 255;
  62492. }
  62493. }
  62494. return imageData;
  62495. };
  62496. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  62497. var image = pixel_data;
  62498. var width = header.width, height = header.height;
  62499. var i = 0, x, y;
  62500. var imageData = new Uint8Array(width * height * 4);
  62501. for (y = y_start; y !== y_end; y += y_step) {
  62502. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  62503. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  62504. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  62505. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  62506. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  62507. }
  62508. }
  62509. return imageData;
  62510. };
  62511. TGATools._TYPE_NO_DATA = 0;
  62512. TGATools._TYPE_INDEXED = 1;
  62513. TGATools._TYPE_RGB = 2;
  62514. TGATools._TYPE_GREY = 3;
  62515. TGATools._TYPE_RLE_INDEXED = 9;
  62516. TGATools._TYPE_RLE_RGB = 10;
  62517. TGATools._TYPE_RLE_GREY = 11;
  62518. TGATools._ORIGIN_MASK = 0x30;
  62519. TGATools._ORIGIN_SHIFT = 0x04;
  62520. TGATools._ORIGIN_BL = 0x00;
  62521. TGATools._ORIGIN_BR = 0x01;
  62522. TGATools._ORIGIN_UL = 0x02;
  62523. TGATools._ORIGIN_UR = 0x03;
  62524. return TGATools;
  62525. }());
  62526. Internals.TGATools = TGATools;
  62527. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62528. })(BABYLON || (BABYLON = {}));
  62529. //# sourceMappingURL=babylon.tga.js.map
  62530. var BABYLON;
  62531. (function (BABYLON) {
  62532. var Internals;
  62533. (function (Internals) {
  62534. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  62535. // All values and structures referenced from:
  62536. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  62537. var DDS_MAGIC = 0x20534444;
  62538. 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;
  62539. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  62540. 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;
  62541. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  62542. function FourCCToInt32(value) {
  62543. return value.charCodeAt(0) +
  62544. (value.charCodeAt(1) << 8) +
  62545. (value.charCodeAt(2) << 16) +
  62546. (value.charCodeAt(3) << 24);
  62547. }
  62548. function Int32ToFourCC(value) {
  62549. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  62550. }
  62551. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  62552. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  62553. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  62554. var FOURCC_DX10 = FourCCToInt32("DX10");
  62555. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  62556. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  62557. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  62558. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  62559. var headerLengthInt = 31; // The header length in 32 bit ints
  62560. // Offsets into the header array
  62561. var off_magic = 0;
  62562. var off_size = 1;
  62563. var off_flags = 2;
  62564. var off_height = 3;
  62565. var off_width = 4;
  62566. var off_mipmapCount = 7;
  62567. var off_pfFlags = 20;
  62568. var off_pfFourCC = 21;
  62569. var off_RGBbpp = 22;
  62570. var off_RMask = 23;
  62571. var off_GMask = 24;
  62572. var off_BMask = 25;
  62573. var off_AMask = 26;
  62574. var off_caps1 = 27;
  62575. var off_caps2 = 28;
  62576. var off_caps3 = 29;
  62577. var off_caps4 = 30;
  62578. var off_dxgiFormat = 32;
  62579. ;
  62580. var DDSTools = (function () {
  62581. function DDSTools() {
  62582. }
  62583. DDSTools.GetDDSInfo = function (arrayBuffer) {
  62584. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  62585. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  62586. var mipmapCount = 1;
  62587. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  62588. mipmapCount = Math.max(1, header[off_mipmapCount]);
  62589. }
  62590. var fourCC = header[off_pfFourCC];
  62591. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  62592. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  62593. switch (fourCC) {
  62594. case FOURCC_D3DFMT_R16G16B16A16F:
  62595. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  62596. break;
  62597. case FOURCC_D3DFMT_R32G32B32A32F:
  62598. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  62599. break;
  62600. case FOURCC_DX10:
  62601. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  62602. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  62603. break;
  62604. }
  62605. }
  62606. return {
  62607. width: header[off_width],
  62608. height: header[off_height],
  62609. mipmapCount: mipmapCount,
  62610. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  62611. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  62612. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  62613. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  62614. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  62615. dxgiFormat: dxgiFormat,
  62616. textureType: textureType
  62617. };
  62618. };
  62619. DDSTools._ToHalfFloat = function (value) {
  62620. if (!DDSTools._FloatView) {
  62621. DDSTools._FloatView = new Float32Array(1);
  62622. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  62623. }
  62624. DDSTools._FloatView[0] = value;
  62625. var x = DDSTools._Int32View[0];
  62626. var bits = (x >> 16) & 0x8000; /* Get the sign */
  62627. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  62628. var e = (x >> 23) & 0xff; /* Using int is faster here */
  62629. /* If zero, or denormal, or exponent underflows too much for a denormal
  62630. * half, return signed zero. */
  62631. if (e < 103) {
  62632. return bits;
  62633. }
  62634. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  62635. if (e > 142) {
  62636. bits |= 0x7c00;
  62637. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  62638. * not Inf, so make sure we set one mantissa bit too. */
  62639. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  62640. return bits;
  62641. }
  62642. /* If exponent underflows but not too much, return a denormal */
  62643. if (e < 113) {
  62644. m |= 0x0800;
  62645. /* Extra rounding may overflow and set mantissa to 0 and exponent
  62646. * to 1, which is OK. */
  62647. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  62648. return bits;
  62649. }
  62650. bits |= ((e - 112) << 10) | (m >> 1);
  62651. bits += m & 1;
  62652. return bits;
  62653. };
  62654. DDSTools._FromHalfFloat = function (value) {
  62655. var s = (value & 0x8000) >> 15;
  62656. var e = (value & 0x7C00) >> 10;
  62657. var f = value & 0x03FF;
  62658. if (e === 0) {
  62659. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  62660. }
  62661. else if (e == 0x1F) {
  62662. return f ? NaN : ((s ? -1 : 1) * Infinity);
  62663. }
  62664. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  62665. };
  62666. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  62667. var destArray = new Float32Array(dataLength);
  62668. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  62669. var index = 0;
  62670. for (var y = 0; y < height; y++) {
  62671. for (var x = 0; x < width; x++) {
  62672. var srcPos = (x + y * width) * 4;
  62673. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  62674. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  62675. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  62676. if (DDSTools.StoreLODInAlphaChannel) {
  62677. destArray[index + 3] = lod;
  62678. }
  62679. else {
  62680. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  62681. }
  62682. index += 4;
  62683. }
  62684. }
  62685. return destArray;
  62686. };
  62687. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  62688. if (DDSTools.StoreLODInAlphaChannel) {
  62689. var destArray = new Uint16Array(dataLength);
  62690. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  62691. var index = 0;
  62692. for (var y = 0; y < height; y++) {
  62693. for (var x = 0; x < width; x++) {
  62694. var srcPos = (x + y * width) * 4;
  62695. destArray[index] = srcData[srcPos];
  62696. destArray[index + 1] = srcData[srcPos + 1];
  62697. destArray[index + 2] = srcData[srcPos + 2];
  62698. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  62699. index += 4;
  62700. }
  62701. }
  62702. return destArray;
  62703. }
  62704. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  62705. };
  62706. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  62707. if (DDSTools.StoreLODInAlphaChannel) {
  62708. var destArray = new Float32Array(dataLength);
  62709. var srcData = new Float32Array(arrayBuffer, dataOffset);
  62710. var index = 0;
  62711. for (var y = 0; y < height; y++) {
  62712. for (var x = 0; x < width; x++) {
  62713. var srcPos = (x + y * width) * 4;
  62714. destArray[index] = srcData[srcPos];
  62715. destArray[index + 1] = srcData[srcPos + 1];
  62716. destArray[index + 2] = srcData[srcPos + 2];
  62717. destArray[index + 3] = lod;
  62718. index += 4;
  62719. }
  62720. }
  62721. return destArray;
  62722. }
  62723. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  62724. };
  62725. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  62726. var destArray = new Uint8Array(dataLength);
  62727. var srcData = new Float32Array(arrayBuffer, dataOffset);
  62728. var index = 0;
  62729. for (var y = 0; y < height; y++) {
  62730. for (var x = 0; x < width; x++) {
  62731. var srcPos = (x + y * width) * 4;
  62732. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  62733. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  62734. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  62735. if (DDSTools.StoreLODInAlphaChannel) {
  62736. destArray[index + 3] = lod;
  62737. }
  62738. else {
  62739. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  62740. }
  62741. index += 4;
  62742. }
  62743. }
  62744. return destArray;
  62745. };
  62746. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  62747. var destArray = new Uint8Array(dataLength);
  62748. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  62749. var index = 0;
  62750. for (var y = 0; y < height; y++) {
  62751. for (var x = 0; x < width; x++) {
  62752. var srcPos = (x + y * width) * 4;
  62753. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  62754. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  62755. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  62756. if (DDSTools.StoreLODInAlphaChannel) {
  62757. destArray[index + 3] = lod;
  62758. }
  62759. else {
  62760. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  62761. }
  62762. index += 4;
  62763. }
  62764. }
  62765. return destArray;
  62766. };
  62767. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  62768. var byteArray = new Uint8Array(dataLength);
  62769. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  62770. var index = 0;
  62771. for (var y = 0; y < height; y++) {
  62772. for (var x = 0; x < width; x++) {
  62773. var srcPos = (x + y * width) * 4;
  62774. byteArray[index] = srcData[srcPos + 2];
  62775. byteArray[index + 1] = srcData[srcPos + 1];
  62776. byteArray[index + 2] = srcData[srcPos];
  62777. byteArray[index + 3] = srcData[srcPos + 3];
  62778. index += 4;
  62779. }
  62780. }
  62781. return byteArray;
  62782. };
  62783. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  62784. var byteArray = new Uint8Array(dataLength);
  62785. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  62786. var index = 0;
  62787. for (var y = 0; y < height; y++) {
  62788. for (var x = 0; x < width; x++) {
  62789. var srcPos = (x + y * width) * 3;
  62790. byteArray[index] = srcData[srcPos + 2];
  62791. byteArray[index + 1] = srcData[srcPos + 1];
  62792. byteArray[index + 2] = srcData[srcPos];
  62793. index += 3;
  62794. }
  62795. }
  62796. return byteArray;
  62797. };
  62798. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  62799. var byteArray = new Uint8Array(dataLength);
  62800. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  62801. var index = 0;
  62802. for (var y = 0; y < height; y++) {
  62803. for (var x = 0; x < width; x++) {
  62804. var srcPos = (x + y * width);
  62805. byteArray[index] = srcData[srcPos];
  62806. index++;
  62807. }
  62808. }
  62809. return byteArray;
  62810. };
  62811. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  62812. if (lodIndex === void 0) { lodIndex = -1; }
  62813. var ext = engine.getCaps().s3tc;
  62814. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  62815. if (header[off_magic] != DDS_MAGIC) {
  62816. BABYLON.Tools.Error("Invalid magic number in DDS header");
  62817. return;
  62818. }
  62819. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  62820. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  62821. return;
  62822. }
  62823. if (info.isCompressed && !ext) {
  62824. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  62825. return;
  62826. }
  62827. var bpp = header[off_RGBbpp];
  62828. dataOffset = header[off_size] + 4;
  62829. var computeFormats = false;
  62830. if (info.isFourCC) {
  62831. fourCC = header[off_pfFourCC];
  62832. switch (fourCC) {
  62833. case FOURCC_DXT1:
  62834. blockBytes = 8;
  62835. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  62836. break;
  62837. case FOURCC_DXT3:
  62838. blockBytes = 16;
  62839. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  62840. break;
  62841. case FOURCC_DXT5:
  62842. blockBytes = 16;
  62843. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  62844. break;
  62845. case FOURCC_D3DFMT_R16G16B16A16F:
  62846. computeFormats = true;
  62847. break;
  62848. case FOURCC_D3DFMT_R32G32B32A32F:
  62849. computeFormats = true;
  62850. break;
  62851. case FOURCC_DX10:
  62852. // There is an additionnal header so dataOffset need to be changed
  62853. dataOffset += 5 * 4; // 5 uints
  62854. var supported = false;
  62855. switch (info.dxgiFormat) {
  62856. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  62857. computeFormats = true;
  62858. supported = true;
  62859. break;
  62860. case DXGI_FORMAT_B8G8R8X8_UNORM:
  62861. info.isRGB = true;
  62862. info.isFourCC = false;
  62863. bpp = 32;
  62864. supported = true;
  62865. break;
  62866. }
  62867. if (supported) {
  62868. break;
  62869. }
  62870. default:
  62871. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  62872. return;
  62873. }
  62874. }
  62875. if (computeFormats) {
  62876. format = engine._getWebGLTextureType(info.textureType);
  62877. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  62878. }
  62879. mipmapCount = 1;
  62880. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  62881. mipmapCount = Math.max(1, header[off_mipmapCount]);
  62882. }
  62883. for (var face = 0; face < faces; face++) {
  62884. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  62885. width = header[off_width];
  62886. height = header[off_height];
  62887. for (mip = 0; mip < mipmapCount; ++mip) {
  62888. if (lodIndex === -1 || lodIndex === mip) {
  62889. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  62890. var i = (lodIndex === -1) ? mip : 0;
  62891. if (!info.isCompressed && info.isFourCC) {
  62892. dataLength = width * height * 4;
  62893. var floatArray;
  62894. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  62895. if (bpp === 128) {
  62896. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  62897. }
  62898. else if (bpp === 64) {
  62899. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  62900. }
  62901. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  62902. format = engine._getWebGLTextureType(info.textureType);
  62903. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  62904. }
  62905. else {
  62906. if (bpp === 128) {
  62907. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  62908. }
  62909. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  62910. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  62911. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  62912. format = engine._getWebGLTextureType(info.textureType);
  62913. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  62914. }
  62915. else {
  62916. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  62917. }
  62918. }
  62919. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  62920. }
  62921. else if (info.isRGB) {
  62922. if (bpp === 24) {
  62923. dataLength = width * height * 3;
  62924. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  62925. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  62926. }
  62927. else {
  62928. dataLength = width * height * 4;
  62929. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  62930. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  62931. }
  62932. }
  62933. else if (info.isLuminance) {
  62934. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  62935. var unpaddedRowSize = width;
  62936. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  62937. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  62938. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  62939. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  62940. }
  62941. else {
  62942. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  62943. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  62944. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  62945. }
  62946. }
  62947. dataOffset += width * height * (bpp / 8);
  62948. width *= 0.5;
  62949. height *= 0.5;
  62950. width = Math.max(1.0, width);
  62951. height = Math.max(1.0, height);
  62952. }
  62953. }
  62954. };
  62955. DDSTools.StoreLODInAlphaChannel = false;
  62956. return DDSTools;
  62957. }());
  62958. Internals.DDSTools = DDSTools;
  62959. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62960. })(BABYLON || (BABYLON = {}));
  62961. //# sourceMappingURL=babylon.dds.js.map
  62962. var BABYLON;
  62963. (function (BABYLON) {
  62964. var Internals;
  62965. (function (Internals) {
  62966. /**
  62967. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  62968. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  62969. */
  62970. var KhronosTextureContainer = (function () {
  62971. /**
  62972. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  62973. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  62974. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  62975. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  62976. */
  62977. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  62978. this.arrayBuffer = arrayBuffer;
  62979. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  62980. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  62981. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  62982. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  62983. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  62984. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  62985. BABYLON.Tools.Error("texture missing KTX identifier");
  62986. return;
  62987. }
  62988. // load the reset of the header in native 32 bit int
  62989. var header = new Int32Array(this.arrayBuffer, 12, 13);
  62990. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  62991. var oppositeEndianess = header[0] === 0x01020304;
  62992. // read all the header elements in order they exist in the file, without modification (sans endainness)
  62993. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  62994. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  62995. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  62996. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  62997. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  62998. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  62999. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  63000. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  63001. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  63002. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  63003. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  63004. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  63005. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  63006. if (this.glType !== 0) {
  63007. BABYLON.Tools.Error("only compressed formats currently supported");
  63008. return;
  63009. }
  63010. else {
  63011. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  63012. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  63013. }
  63014. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  63015. BABYLON.Tools.Error("only 2D textures currently supported");
  63016. return;
  63017. }
  63018. if (this.numberOfArrayElements !== 0) {
  63019. BABYLON.Tools.Error("texture arrays not currently supported");
  63020. return;
  63021. }
  63022. if (this.numberOfFaces !== facesExpected) {
  63023. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  63024. return;
  63025. }
  63026. // we now have a completely validated file, so could use existence of loadType as success
  63027. // would need to make this more elaborate & adjust checks above to support more than one load type
  63028. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  63029. }
  63030. // not as fast hardware based, but will probably never need to use
  63031. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  63032. return ((val & 0xFF) << 24)
  63033. | ((val & 0xFF00) << 8)
  63034. | ((val >> 8) & 0xFF00)
  63035. | ((val >> 24) & 0xFF);
  63036. };
  63037. /**
  63038. * It is assumed that the texture has already been created & is currently bound
  63039. */
  63040. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  63041. switch (this.loadType) {
  63042. case KhronosTextureContainer.COMPRESSED_2D:
  63043. this._upload2DCompressedLevels(gl, loadMipmaps);
  63044. break;
  63045. case KhronosTextureContainer.TEX_2D:
  63046. case KhronosTextureContainer.COMPRESSED_3D:
  63047. case KhronosTextureContainer.TEX_3D:
  63048. }
  63049. };
  63050. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  63051. // initialize width & height for level 1
  63052. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  63053. var width = this.pixelWidth;
  63054. var height = this.pixelHeight;
  63055. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  63056. for (var level = 0; level < mipmapCount; level++) {
  63057. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  63058. for (var face = 0; face < this.numberOfFaces; face++) {
  63059. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  63060. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  63061. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  63062. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  63063. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  63064. }
  63065. width = Math.max(1.0, width * 0.5);
  63066. height = Math.max(1.0, height * 0.5);
  63067. }
  63068. };
  63069. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  63070. // load types
  63071. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  63072. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  63073. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  63074. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  63075. return KhronosTextureContainer;
  63076. }());
  63077. Internals.KhronosTextureContainer = KhronosTextureContainer;
  63078. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63079. })(BABYLON || (BABYLON = {}));
  63080. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  63081. var BABYLON;
  63082. (function (BABYLON) {
  63083. var DynamicFloatArrayElementInfo = (function () {
  63084. function DynamicFloatArrayElementInfo() {
  63085. }
  63086. return DynamicFloatArrayElementInfo;
  63087. }());
  63088. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  63089. /**
  63090. * 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.
  63091. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  63092. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  63093. * 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.
  63094. * 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.
  63095. * 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".
  63096. */
  63097. var DynamicFloatArray = (function () {
  63098. /**
  63099. * Construct an instance of the dynamic float array
  63100. * @param stride size of one element in float (i.e. not bytes!)
  63101. * @param initialElementCount the number of available entries at construction
  63102. */
  63103. function DynamicFloatArray(stride, initialElementCount) {
  63104. this.compareValueOffset = null;
  63105. this.sortingAscending = true;
  63106. this._stride = stride;
  63107. this.buffer = new Float32Array(stride * initialElementCount);
  63108. this._lastUsed = 0;
  63109. this._firstFree = 0;
  63110. this._allEntries = new Array(initialElementCount);
  63111. this._freeEntries = new Array(initialElementCount);
  63112. for (var i = 0; i < initialElementCount; i++) {
  63113. var element = new DynamicFloatArrayElementInfo();
  63114. element.offset = i * stride;
  63115. this._allEntries[i] = element;
  63116. this._freeEntries[initialElementCount - i - 1] = element;
  63117. }
  63118. }
  63119. /**
  63120. * Allocate an element in the array.
  63121. * @return the element info instance that contains the offset into the main buffer of the element's location.
  63122. * Beware, this offset may change when you call pack()
  63123. */
  63124. DynamicFloatArray.prototype.allocElement = function () {
  63125. if (this._freeEntries.length === 0) {
  63126. this._growBuffer();
  63127. }
  63128. var el = this._freeEntries.pop();
  63129. this._lastUsed = Math.max(el.offset, this._lastUsed);
  63130. if (el.offset === this._firstFree) {
  63131. if (this._freeEntries.length > 0) {
  63132. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  63133. }
  63134. else {
  63135. this._firstFree += this._stride;
  63136. }
  63137. }
  63138. return el;
  63139. };
  63140. /**
  63141. * Free the element corresponding to the given element info
  63142. * @param elInfo the element that describe the allocated element
  63143. */
  63144. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  63145. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  63146. this._freeEntries.push(elInfo);
  63147. };
  63148. /**
  63149. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  63150. * 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().
  63151. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  63152. */
  63153. DynamicFloatArray.prototype.pack = function () {
  63154. // no free slot? no need to pack
  63155. if (this._freeEntries.length === 0) {
  63156. return this.buffer;
  63157. }
  63158. // If the buffer is already packed the last used will always be lower than the first free
  63159. // 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.
  63160. if (this._lastUsed < this._firstFree) {
  63161. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  63162. return elementsBuffer_1;
  63163. }
  63164. var s = this._stride;
  63165. // 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
  63166. var lastFree = new DynamicFloatArrayElementInfo();
  63167. lastFree.offset = this.totalElementCount * s;
  63168. this._freeEntries.push(lastFree);
  63169. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  63170. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  63171. var firstFreeSlotOffset = sortedFree[0].offset;
  63172. var freeZoneSize = 1;
  63173. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  63174. var prevOffset = sortedFree[0].offset;
  63175. for (var i = 1; i < sortedFree.length; i++) {
  63176. // 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
  63177. if (firstFreeSlotOffset >= occupiedZoneSize) {
  63178. break;
  63179. }
  63180. var curFree = sortedFree[i];
  63181. var curOffset = curFree.offset;
  63182. // Compute the distance between this offset and the previous
  63183. var distance = curOffset - prevOffset;
  63184. // If the distance is the stride size, they are adjacent, it good, move to the next
  63185. if (distance === s) {
  63186. // Free zone is one element bigger
  63187. ++freeZoneSize;
  63188. // as we're about to iterate to the next, the cur becomes the previous...
  63189. prevOffset = curOffset;
  63190. continue;
  63191. }
  63192. // Distance is bigger, which means there's x element between the previous free and this one
  63193. var usedRange = (distance / s) - 1;
  63194. // Two cases the free zone is smaller than the data to move or bigger
  63195. // Copy what can fit in the free zone
  63196. var curMoveOffset = curOffset - s;
  63197. var copyCount = Math.min(freeZoneSize, usedRange);
  63198. for (var j = 0; j < copyCount; j++) {
  63199. var freeI = firstFreeSlotOffset / s;
  63200. var curI = curMoveOffset / s;
  63201. var moveEl = sortedAll[curI];
  63202. this._moveElement(moveEl, firstFreeSlotOffset);
  63203. var replacedEl = sortedAll[freeI];
  63204. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  63205. replacedEl.offset = curMoveOffset;
  63206. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  63207. sortedAll[freeI] = moveEl;
  63208. sortedAll[curI] = replacedEl;
  63209. curMoveOffset -= s;
  63210. firstFreeSlotOffset += s;
  63211. }
  63212. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  63213. if (freeZoneSize <= usedRange) {
  63214. firstFreeSlotOffset = curMoveOffset + s;
  63215. freeZoneSize = 1 + copyCount;
  63216. }
  63217. else {
  63218. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  63219. }
  63220. // as we're about to iterate to the next, the cur becomes the previous...
  63221. prevOffset = curOffset;
  63222. }
  63223. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  63224. this._lastUsed = firstFreeSlotOffset - s;
  63225. this._firstFree = firstFreeSlotOffset;
  63226. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  63227. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  63228. this._allEntries = sortedAll;
  63229. return elementsBuffer;
  63230. };
  63231. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  63232. for (var i = 0; i < this._stride; i++) {
  63233. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  63234. }
  63235. element.offset = destOffset;
  63236. };
  63237. DynamicFloatArray.prototype._growBuffer = function () {
  63238. // Allocate the new buffer with 50% more entries, copy the content of the current one
  63239. var newElCount = Math.floor(this.totalElementCount * 1.5);
  63240. var newBuffer = new Float32Array(newElCount * this._stride);
  63241. newBuffer.set(this.buffer);
  63242. var curCount = this.totalElementCount;
  63243. var addedCount = newElCount - this.totalElementCount;
  63244. for (var i = 0; i < addedCount; i++) {
  63245. var element = new DynamicFloatArrayElementInfo();
  63246. element.offset = (curCount + i) * this.stride;
  63247. this._allEntries.push(element);
  63248. this._freeEntries[addedCount - i - 1] = element;
  63249. }
  63250. this._firstFree = curCount * this.stride;
  63251. this.buffer = newBuffer;
  63252. };
  63253. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  63254. /**
  63255. * Get the total count of entries that can fit in the current buffer
  63256. * @returns the elements count
  63257. */
  63258. get: function () {
  63259. return this._allEntries.length;
  63260. },
  63261. enumerable: true,
  63262. configurable: true
  63263. });
  63264. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  63265. /**
  63266. * Get the count of free entries that can still be allocated without resizing the buffer
  63267. * @returns the free elements count
  63268. */
  63269. get: function () {
  63270. return this._freeEntries.length;
  63271. },
  63272. enumerable: true,
  63273. configurable: true
  63274. });
  63275. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  63276. /**
  63277. * Get the count of allocated elements
  63278. * @returns the allocated elements count
  63279. */
  63280. get: function () {
  63281. return this._allEntries.length - this._freeEntries.length;
  63282. },
  63283. enumerable: true,
  63284. configurable: true
  63285. });
  63286. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  63287. /**
  63288. * Return the size of one element in float
  63289. * @returns the size in float
  63290. */
  63291. get: function () {
  63292. return this._stride;
  63293. },
  63294. enumerable: true,
  63295. configurable: true
  63296. });
  63297. DynamicFloatArray.prototype.sort = function () {
  63298. var _this = this;
  63299. if (!this.compareValueOffset) {
  63300. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  63301. }
  63302. var count = this.usedElementCount;
  63303. // Do we have to (re)create the sort table?
  63304. if (!this._sortTable || this._sortTable.length < count) {
  63305. // 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...
  63306. var newCount = Math.min(this.totalElementCount, count * 2);
  63307. this._sortTable = new Array(newCount);
  63308. }
  63309. if (!this._sortedTable || this._sortedTable.length !== count) {
  63310. this._sortedTable = new Array(count);
  63311. }
  63312. // Because, you know...
  63313. this.pack();
  63314. //let stride = this.stride;
  63315. //for (let i = 0; i < count; i++) {
  63316. // let si = this._sortTable[i];
  63317. // if (!si) {
  63318. // si = new SortInfo();
  63319. // this._sortTable[i] = si;
  63320. // }
  63321. // si.entry = this._allEntries[i];
  63322. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  63323. // si.swapedOffset = null;
  63324. // this._sortedTable[i] = si;
  63325. //}
  63326. var curOffset = 0;
  63327. var stride = this.stride;
  63328. for (var i = 0; i < count; i++, curOffset += stride) {
  63329. var si = this._sortTable[i];
  63330. if (!si) {
  63331. si = new SortInfo();
  63332. this._sortTable[i] = si;
  63333. }
  63334. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  63335. si.offset = curOffset;
  63336. si.swapedOffset = null;
  63337. this._sortedTable[i] = si;
  63338. }
  63339. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  63340. if (this.sortingAscending) {
  63341. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  63342. }
  63343. else {
  63344. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  63345. }
  63346. var swapElements = function (src, dst) {
  63347. for (var i = 0; i < stride; i++) {
  63348. var tps = _this.buffer[dst + i];
  63349. _this.buffer[dst + i] = _this.buffer[src + i];
  63350. _this.buffer[src + i] = tps;
  63351. }
  63352. };
  63353. // 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:
  63354. // 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),
  63355. // and I still want something with a good algorithm complexity.
  63356. // 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,
  63357. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  63358. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  63359. // 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
  63360. // until we find a SortInfo object without a swapedOffset which means we got the right location
  63361. // 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
  63362. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  63363. for (var i = 0; i < count; i++) {
  63364. // Get the element to move
  63365. var sourceSI = this._sortedTable[i];
  63366. var destSI = this._sortTable[i];
  63367. var sourceOff = sourceSI.offset;
  63368. // If the source changed location, find the new one
  63369. if (sourceSI.swapedOffset) {
  63370. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  63371. var curSI = sourceSI;
  63372. while (curSI.swapedOffset) {
  63373. curSI = this._sortTable[curSI.swapedOffset / stride];
  63374. }
  63375. // Finally get the right location
  63376. sourceOff = curSI.offset;
  63377. }
  63378. // Tag the element being replaced with its new location
  63379. destSI.swapedOffset = sourceOff;
  63380. // Swap elements (only if needed)
  63381. if (sourceOff !== destSI.offset) {
  63382. swapElements(sourceOff, destSI.offset);
  63383. }
  63384. // Update the offset in the corresponding DFAE
  63385. //sourceSI.entry.offset = destSI.entry.offset;
  63386. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  63387. }
  63388. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  63389. return true;
  63390. };
  63391. return DynamicFloatArray;
  63392. }());
  63393. BABYLON.DynamicFloatArray = DynamicFloatArray;
  63394. var SortInfo = (function () {
  63395. function SortInfo() {
  63396. this.compareData = this.offset = this.swapedOffset = null;
  63397. }
  63398. return SortInfo;
  63399. }());
  63400. })(BABYLON || (BABYLON = {}));
  63401. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  63402. var BABYLON;
  63403. (function (BABYLON) {
  63404. var Debug;
  63405. (function (Debug) {
  63406. /**
  63407. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  63408. */
  63409. var SkeletonViewer = (function () {
  63410. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  63411. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  63412. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  63413. this.skeleton = skeleton;
  63414. this.mesh = mesh;
  63415. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  63416. this.renderingGroupId = renderingGroupId;
  63417. this.color = BABYLON.Color3.White();
  63418. this._debugLines = [];
  63419. this._isEnabled = false;
  63420. this._scene = scene;
  63421. this.update();
  63422. this._renderFunction = this.update.bind(this);
  63423. }
  63424. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  63425. get: function () {
  63426. return this._isEnabled;
  63427. },
  63428. set: function (value) {
  63429. if (this._isEnabled === value) {
  63430. return;
  63431. }
  63432. this._isEnabled = value;
  63433. if (value) {
  63434. this._scene.registerBeforeRender(this._renderFunction);
  63435. }
  63436. else {
  63437. this._scene.unregisterBeforeRender(this._renderFunction);
  63438. }
  63439. },
  63440. enumerable: true,
  63441. configurable: true
  63442. });
  63443. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  63444. if (x === void 0) { x = 0; }
  63445. if (y === void 0) { y = 0; }
  63446. if (z === void 0) { z = 0; }
  63447. var tmat = BABYLON.Tmp.Matrix[0];
  63448. var parentBone = bone.getParent();
  63449. tmat.copyFrom(bone.getLocalMatrix());
  63450. if (x !== 0 || y !== 0 || z !== 0) {
  63451. var tmat2 = BABYLON.Tmp.Matrix[1];
  63452. BABYLON.Matrix.IdentityToRef(tmat2);
  63453. tmat2.m[12] = x;
  63454. tmat2.m[13] = y;
  63455. tmat2.m[14] = z;
  63456. tmat2.multiplyToRef(tmat, tmat);
  63457. }
  63458. if (parentBone) {
  63459. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  63460. }
  63461. tmat.multiplyToRef(meshMat, tmat);
  63462. position.x = tmat.m[12];
  63463. position.y = tmat.m[13];
  63464. position.z = tmat.m[14];
  63465. };
  63466. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  63467. var len = bones.length;
  63468. var meshPos = this.mesh.position;
  63469. for (var i = 0; i < len; i++) {
  63470. var bone = bones[i];
  63471. var points = this._debugLines[i];
  63472. if (!points) {
  63473. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63474. this._debugLines[i] = points;
  63475. }
  63476. this._getBonePosition(points[0], bone, meshMat);
  63477. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  63478. points[0].subtractInPlace(meshPos);
  63479. points[1].subtractInPlace(meshPos);
  63480. }
  63481. };
  63482. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  63483. var len = bones.length;
  63484. var boneNum = 0;
  63485. var meshPos = this.mesh.position;
  63486. for (var i = len - 1; i >= 0; i--) {
  63487. var childBone = bones[i];
  63488. var parentBone = childBone.getParent();
  63489. if (!parentBone) {
  63490. continue;
  63491. }
  63492. var points = this._debugLines[boneNum];
  63493. if (!points) {
  63494. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63495. this._debugLines[boneNum] = points;
  63496. }
  63497. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  63498. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  63499. points[0].subtractInPlace(meshPos);
  63500. points[1].subtractInPlace(meshPos);
  63501. boneNum++;
  63502. }
  63503. };
  63504. SkeletonViewer.prototype.update = function () {
  63505. if (this.autoUpdateBonesMatrices) {
  63506. this.skeleton.computeAbsoluteTransforms();
  63507. }
  63508. if (this.skeleton.bones[0].length === undefined) {
  63509. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  63510. }
  63511. else {
  63512. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  63513. }
  63514. if (!this._debugMesh) {
  63515. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  63516. this._debugMesh.renderingGroupId = this.renderingGroupId;
  63517. }
  63518. else {
  63519. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  63520. }
  63521. this._debugMesh.position.copyFrom(this.mesh.position);
  63522. this._debugMesh.color = this.color;
  63523. };
  63524. SkeletonViewer.prototype.dispose = function () {
  63525. if (this._debugMesh) {
  63526. this.isEnabled = false;
  63527. this._debugMesh.dispose();
  63528. this._debugMesh = null;
  63529. }
  63530. };
  63531. return SkeletonViewer;
  63532. }());
  63533. Debug.SkeletonViewer = SkeletonViewer;
  63534. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63535. })(BABYLON || (BABYLON = {}));
  63536. //# sourceMappingURL=babylon.skeletonViewer.js.map
  63537. var BABYLON;
  63538. (function (BABYLON) {
  63539. var Debug;
  63540. (function (Debug) {
  63541. var AxesViewer = (function () {
  63542. function AxesViewer(scene, scaleLines) {
  63543. if (scaleLines === void 0) { scaleLines = 1; }
  63544. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63545. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63546. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63547. this.scaleLines = 1;
  63548. this.scaleLines = scaleLines;
  63549. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  63550. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  63551. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  63552. this._xmesh.renderingGroupId = 2;
  63553. this._ymesh.renderingGroupId = 2;
  63554. this._zmesh.renderingGroupId = 2;
  63555. this._xmesh.material.checkReadyOnlyOnce = true;
  63556. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  63557. this._ymesh.material.checkReadyOnlyOnce = true;
  63558. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  63559. this._zmesh.material.checkReadyOnlyOnce = true;
  63560. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  63561. this.scene = scene;
  63562. }
  63563. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  63564. var scaleLines = this.scaleLines;
  63565. this._xmesh.position.copyFrom(position);
  63566. this._ymesh.position.copyFrom(position);
  63567. this._zmesh.position.copyFrom(position);
  63568. var point2 = this._xline[1];
  63569. point2.x = xaxis.x * scaleLines;
  63570. point2.y = xaxis.y * scaleLines;
  63571. point2.z = xaxis.z * scaleLines;
  63572. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  63573. point2 = this._yline[1];
  63574. point2.x = yaxis.x * scaleLines;
  63575. point2.y = yaxis.y * scaleLines;
  63576. point2.z = yaxis.z * scaleLines;
  63577. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  63578. point2 = this._zline[1];
  63579. point2.x = zaxis.x * scaleLines;
  63580. point2.y = zaxis.y * scaleLines;
  63581. point2.z = zaxis.z * scaleLines;
  63582. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  63583. };
  63584. AxesViewer.prototype.dispose = function () {
  63585. if (this._xmesh) {
  63586. this._xmesh.dispose();
  63587. this._ymesh.dispose();
  63588. this._zmesh.dispose();
  63589. this._xmesh = null;
  63590. this._ymesh = null;
  63591. this._zmesh = null;
  63592. this._xline = null;
  63593. this._yline = null;
  63594. this._zline = null;
  63595. this.scene = null;
  63596. }
  63597. };
  63598. return AxesViewer;
  63599. }());
  63600. Debug.AxesViewer = AxesViewer;
  63601. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63602. })(BABYLON || (BABYLON = {}));
  63603. //# sourceMappingURL=babylon.axesViewer.js.map
  63604. var BABYLON;
  63605. (function (BABYLON) {
  63606. var Debug;
  63607. (function (Debug) {
  63608. var BoneAxesViewer = (function (_super) {
  63609. __extends(BoneAxesViewer, _super);
  63610. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  63611. if (scaleLines === void 0) { scaleLines = 1; }
  63612. var _this = _super.call(this, scene, scaleLines) || this;
  63613. _this.pos = BABYLON.Vector3.Zero();
  63614. _this.xaxis = BABYLON.Vector3.Zero();
  63615. _this.yaxis = BABYLON.Vector3.Zero();
  63616. _this.zaxis = BABYLON.Vector3.Zero();
  63617. _this.mesh = mesh;
  63618. _this.bone = bone;
  63619. return _this;
  63620. }
  63621. BoneAxesViewer.prototype.update = function () {
  63622. var bone = this.bone;
  63623. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  63624. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  63625. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  63626. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  63627. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  63628. };
  63629. BoneAxesViewer.prototype.dispose = function () {
  63630. if (this.pos) {
  63631. this.pos = null;
  63632. this.xaxis = null;
  63633. this.yaxis = null;
  63634. this.zaxis = null;
  63635. this.mesh = null;
  63636. this.bone = null;
  63637. _super.prototype.dispose.call(this);
  63638. }
  63639. };
  63640. return BoneAxesViewer;
  63641. }(Debug.AxesViewer));
  63642. Debug.BoneAxesViewer = BoneAxesViewer;
  63643. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63644. })(BABYLON || (BABYLON = {}));
  63645. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  63646. var BABYLON;
  63647. (function (BABYLON) {
  63648. var RayHelper = (function () {
  63649. function RayHelper(ray) {
  63650. this.ray = ray;
  63651. }
  63652. RayHelper.CreateAndShow = function (ray, scene, color) {
  63653. var helper = new RayHelper(ray);
  63654. helper.show(scene, color);
  63655. return helper;
  63656. };
  63657. RayHelper.prototype.show = function (scene, color) {
  63658. if (!this._renderFunction) {
  63659. var ray = this.ray;
  63660. this._renderFunction = this._render.bind(this);
  63661. this._scene = scene;
  63662. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  63663. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  63664. this._scene.registerBeforeRender(this._renderFunction);
  63665. }
  63666. if (color) {
  63667. this._renderLine.color.copyFrom(color);
  63668. }
  63669. };
  63670. RayHelper.prototype.hide = function () {
  63671. if (this._renderFunction) {
  63672. this._scene.unregisterBeforeRender(this._renderFunction);
  63673. this._scene = null;
  63674. this._renderFunction = null;
  63675. this._renderLine.dispose();
  63676. this._renderLine = null;
  63677. this._renderPoints = null;
  63678. }
  63679. };
  63680. RayHelper.prototype._render = function () {
  63681. var ray = this.ray;
  63682. var point = this._renderPoints[1];
  63683. var len = Math.min(ray.length, 1000000);
  63684. point.copyFrom(ray.direction);
  63685. point.scaleInPlace(len);
  63686. point.addInPlace(ray.origin);
  63687. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  63688. };
  63689. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  63690. this._attachedToMesh = mesh;
  63691. var ray = this.ray;
  63692. if (!ray.direction) {
  63693. ray.direction = BABYLON.Vector3.Zero();
  63694. }
  63695. if (!ray.origin) {
  63696. ray.origin = BABYLON.Vector3.Zero();
  63697. }
  63698. if (length) {
  63699. ray.length = length;
  63700. }
  63701. if (!meshSpaceOrigin) {
  63702. meshSpaceOrigin = BABYLON.Vector3.Zero();
  63703. }
  63704. if (!meshSpaceDirection) {
  63705. // -1 so that this will work with Mesh.lookAt
  63706. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  63707. }
  63708. if (!this._meshSpaceDirection) {
  63709. this._meshSpaceDirection = meshSpaceDirection.clone();
  63710. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  63711. }
  63712. else {
  63713. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  63714. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  63715. }
  63716. if (!this._updateToMeshFunction) {
  63717. this._updateToMeshFunction = this._updateToMesh.bind(this);
  63718. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  63719. }
  63720. this._updateToMesh();
  63721. };
  63722. RayHelper.prototype.detachFromMesh = function () {
  63723. if (this._attachedToMesh) {
  63724. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  63725. this._attachedToMesh = null;
  63726. this._updateToMeshFunction = null;
  63727. }
  63728. };
  63729. RayHelper.prototype._updateToMesh = function () {
  63730. var ray = this.ray;
  63731. if (this._attachedToMesh._isDisposed) {
  63732. this.detachFromMesh();
  63733. return;
  63734. }
  63735. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  63736. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  63737. };
  63738. RayHelper.prototype.dispose = function () {
  63739. this.hide();
  63740. this.detachFromMesh();
  63741. this.ray = null;
  63742. };
  63743. return RayHelper;
  63744. }());
  63745. BABYLON.RayHelper = RayHelper;
  63746. })(BABYLON || (BABYLON = {}));
  63747. //# sourceMappingURL=babylon.rayHelper.js.map
  63748. var BABYLON;
  63749. (function (BABYLON) {
  63750. var DebugLayer = (function () {
  63751. function DebugLayer(scene) {
  63752. this._scene = scene;
  63753. }
  63754. /** Creates the inspector window. */
  63755. DebugLayer.prototype._createInspector = function (config) {
  63756. if (config === void 0) { config = {}; }
  63757. var popup = config.popup || false;
  63758. var initialTab = config.initialTab || 0;
  63759. var parentElement = config.parentElement || null;
  63760. if (!this._inspector) {
  63761. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  63762. } // else nothing to do,; instance is already existing
  63763. };
  63764. DebugLayer.prototype.isVisible = function () {
  63765. if (!this._inspector) {
  63766. return false;
  63767. }
  63768. return true;
  63769. };
  63770. DebugLayer.prototype.hide = function () {
  63771. if (this._inspector) {
  63772. try {
  63773. this._inspector.dispose();
  63774. }
  63775. catch (e) {
  63776. // If the inspector has been removed directly from the inspector tool
  63777. }
  63778. this._inspector = null;
  63779. }
  63780. };
  63781. DebugLayer.prototype.show = function (config) {
  63782. if (config === void 0) { config = {}; }
  63783. if (typeof INSPECTOR == 'undefined') {
  63784. // Load inspector and add it to the DOM
  63785. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  63786. }
  63787. else {
  63788. // Otherwise creates the inspector
  63789. this._createInspector(config);
  63790. }
  63791. };
  63792. // Get protocol used - http or https
  63793. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  63794. return DebugLayer;
  63795. }());
  63796. BABYLON.DebugLayer = DebugLayer;
  63797. })(BABYLON || (BABYLON = {}));
  63798. //# sourceMappingURL=babylon.debugLayer.js.map
  63799. var BABYLON;
  63800. (function (BABYLON) {
  63801. var Debug;
  63802. (function (Debug) {
  63803. var PhysicsViewer = (function () {
  63804. function PhysicsViewer(scene) {
  63805. this._impostors = [];
  63806. this._meshes = [];
  63807. this._numMeshes = 0;
  63808. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63809. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  63810. }
  63811. PhysicsViewer.prototype._updateDebugMeshes = function () {
  63812. var plugin = this._physicsEnginePlugin;
  63813. for (var i = 0; i < this._numMeshes; i++) {
  63814. if (this._impostors[i].isDisposed) {
  63815. this.hideImpostor(this._impostors[i--]);
  63816. }
  63817. else {
  63818. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  63819. }
  63820. }
  63821. };
  63822. PhysicsViewer.prototype.showImpostor = function (impostor) {
  63823. for (var i = 0; i < this._numMeshes; i++) {
  63824. if (this._impostors[i] == impostor) {
  63825. return;
  63826. }
  63827. }
  63828. var debugMesh = this._getDebugMesh(impostor, this._scene);
  63829. if (debugMesh) {
  63830. this._impostors[this._numMeshes] = impostor;
  63831. this._meshes[this._numMeshes] = debugMesh;
  63832. if (this._numMeshes === 0) {
  63833. this._renderFunction = this._updateDebugMeshes.bind(this);
  63834. this._scene.registerBeforeRender(this._renderFunction);
  63835. }
  63836. this._numMeshes++;
  63837. }
  63838. };
  63839. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  63840. var removed = false;
  63841. for (var i = 0; i < this._numMeshes; i++) {
  63842. if (this._impostors[i] == impostor) {
  63843. this._scene.removeMesh(this._meshes[i]);
  63844. this._meshes[i].dispose();
  63845. this._numMeshes--;
  63846. if (this._numMeshes > 0) {
  63847. this._meshes[i] = this._meshes[this._numMeshes];
  63848. this._impostors[i] = this._impostors[this._numMeshes];
  63849. this._meshes[this._numMeshes] = null;
  63850. this._impostors[this._numMeshes] = null;
  63851. }
  63852. else {
  63853. this._meshes[0] = null;
  63854. this._impostors[0] = null;
  63855. }
  63856. removed = true;
  63857. break;
  63858. }
  63859. }
  63860. if (removed && this._numMeshes === 0) {
  63861. this._scene.unregisterBeforeRender(this._renderFunction);
  63862. }
  63863. };
  63864. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  63865. if (!this._debugMaterial) {
  63866. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  63867. this._debugMaterial.wireframe = true;
  63868. }
  63869. return this._debugMaterial;
  63870. };
  63871. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  63872. if (!this._debugBoxMesh) {
  63873. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  63874. this._debugBoxMesh.renderingGroupId = 1;
  63875. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  63876. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  63877. scene.removeMesh(this._debugBoxMesh);
  63878. }
  63879. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  63880. };
  63881. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  63882. if (!this._debugSphereMesh) {
  63883. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  63884. this._debugSphereMesh.renderingGroupId = 1;
  63885. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  63886. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  63887. scene.removeMesh(this._debugSphereMesh);
  63888. }
  63889. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  63890. };
  63891. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  63892. var body = impostor.physicsBody;
  63893. var shape = body.shapes[0];
  63894. var mesh;
  63895. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  63896. mesh = this._getDebugBoxMesh(scene);
  63897. impostor.getBoxSizeToRef(mesh.scaling);
  63898. }
  63899. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  63900. mesh = this._getDebugSphereMesh(scene);
  63901. var radius = impostor.getRadius();
  63902. mesh.scaling.x = radius * 2;
  63903. mesh.scaling.y = radius * 2;
  63904. mesh.scaling.z = radius * 2;
  63905. }
  63906. return mesh;
  63907. };
  63908. PhysicsViewer.prototype.dispose = function () {
  63909. for (var i = 0; i < this._numMeshes; i++) {
  63910. this.hideImpostor(this._impostors[i]);
  63911. }
  63912. if (this._debugBoxMesh) {
  63913. this._debugBoxMesh.dispose();
  63914. }
  63915. if (this._debugSphereMesh) {
  63916. this._debugSphereMesh.dispose();
  63917. }
  63918. if (this._debugMaterial) {
  63919. this._debugMaterial.dispose();
  63920. }
  63921. this._impostors.length = 0;
  63922. this._scene = null;
  63923. this._physicsEnginePlugin = null;
  63924. };
  63925. return PhysicsViewer;
  63926. }());
  63927. Debug.PhysicsViewer = PhysicsViewer;
  63928. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63929. })(BABYLON || (BABYLON = {}));
  63930. //# sourceMappingURL=babylon.physicsViewer.js.map
  63931. var BABYLON;
  63932. (function (BABYLON) {
  63933. var BoundingBoxRenderer = (function () {
  63934. function BoundingBoxRenderer(scene) {
  63935. this.frontColor = new BABYLON.Color3(1, 1, 1);
  63936. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  63937. this.showBackLines = true;
  63938. this.renderList = new BABYLON.SmartArray(32);
  63939. this._vertexBuffers = {};
  63940. this._scene = scene;
  63941. }
  63942. BoundingBoxRenderer.prototype._prepareRessources = function () {
  63943. if (this._colorShader) {
  63944. return;
  63945. }
  63946. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  63947. attributes: [BABYLON.VertexBuffer.PositionKind],
  63948. uniforms: ["world", "viewProjection", "color"]
  63949. });
  63950. var engine = this._scene.getEngine();
  63951. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  63952. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  63953. this._createIndexBuffer();
  63954. };
  63955. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  63956. var engine = this._scene.getEngine();
  63957. 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]);
  63958. };
  63959. BoundingBoxRenderer.prototype._rebuild = function () {
  63960. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  63961. this._createIndexBuffer();
  63962. };
  63963. BoundingBoxRenderer.prototype.reset = function () {
  63964. this.renderList.reset();
  63965. };
  63966. BoundingBoxRenderer.prototype.render = function () {
  63967. if (this.renderList.length === 0) {
  63968. return;
  63969. }
  63970. this._prepareRessources();
  63971. if (!this._colorShader.isReady()) {
  63972. return;
  63973. }
  63974. var engine = this._scene.getEngine();
  63975. engine.setDepthWrite(false);
  63976. this._colorShader._preBind();
  63977. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  63978. var boundingBox = this.renderList.data[boundingBoxIndex];
  63979. var min = boundingBox.minimum;
  63980. var max = boundingBox.maximum;
  63981. var diff = max.subtract(min);
  63982. var median = min.add(diff.scale(0.5));
  63983. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  63984. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  63985. .multiply(boundingBox.getWorldMatrix());
  63986. // VBOs
  63987. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  63988. if (this.showBackLines) {
  63989. // Back
  63990. engine.setDepthFunctionToGreaterOrEqual();
  63991. this._scene.resetCachedMaterial();
  63992. this._colorShader.setColor4("color", this.backColor.toColor4());
  63993. this._colorShader.bind(worldMatrix);
  63994. // Draw order
  63995. engine.draw(false, 0, 24);
  63996. }
  63997. // Front
  63998. engine.setDepthFunctionToLess();
  63999. this._scene.resetCachedMaterial();
  64000. this._colorShader.setColor4("color", this.frontColor.toColor4());
  64001. this._colorShader.bind(worldMatrix);
  64002. // Draw order
  64003. engine.draw(false, 0, 24);
  64004. }
  64005. this._colorShader.unbind();
  64006. engine.setDepthFunctionToLessOrEqual();
  64007. engine.setDepthWrite(true);
  64008. };
  64009. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  64010. this._prepareRessources();
  64011. if (!this._colorShader.isReady()) {
  64012. return;
  64013. }
  64014. var engine = this._scene.getEngine();
  64015. engine.setDepthWrite(false);
  64016. engine.setColorWrite(false);
  64017. this._colorShader._preBind();
  64018. var boundingBox = mesh._boundingInfo.boundingBox;
  64019. var min = boundingBox.minimum;
  64020. var max = boundingBox.maximum;
  64021. var diff = max.subtract(min);
  64022. var median = min.add(diff.scale(0.5));
  64023. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  64024. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  64025. .multiply(boundingBox.getWorldMatrix());
  64026. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  64027. engine.setDepthFunctionToLess();
  64028. this._scene.resetCachedMaterial();
  64029. this._colorShader.bind(worldMatrix);
  64030. engine.draw(false, 0, 24);
  64031. this._colorShader.unbind();
  64032. engine.setDepthFunctionToLessOrEqual();
  64033. engine.setDepthWrite(true);
  64034. engine.setColorWrite(true);
  64035. };
  64036. BoundingBoxRenderer.prototype.dispose = function () {
  64037. if (!this._colorShader) {
  64038. return;
  64039. }
  64040. this.renderList.dispose();
  64041. this._colorShader.dispose();
  64042. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64043. if (buffer) {
  64044. buffer.dispose();
  64045. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64046. }
  64047. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  64048. };
  64049. return BoundingBoxRenderer;
  64050. }());
  64051. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  64052. })(BABYLON || (BABYLON = {}));
  64053. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  64054. var BABYLON;
  64055. (function (BABYLON) {
  64056. var MorphTarget = (function () {
  64057. function MorphTarget(name, influence) {
  64058. if (influence === void 0) { influence = 0; }
  64059. this.name = name;
  64060. this.animations = new Array();
  64061. this.onInfluenceChanged = new BABYLON.Observable();
  64062. this.influence = influence;
  64063. }
  64064. Object.defineProperty(MorphTarget.prototype, "influence", {
  64065. get: function () {
  64066. return this._influence;
  64067. },
  64068. set: function (influence) {
  64069. if (this._influence === influence) {
  64070. return;
  64071. }
  64072. var previous = this._influence;
  64073. this._influence = influence;
  64074. if (this.onInfluenceChanged.hasObservers) {
  64075. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  64076. }
  64077. },
  64078. enumerable: true,
  64079. configurable: true
  64080. });
  64081. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  64082. get: function () {
  64083. return this._normals !== undefined;
  64084. },
  64085. enumerable: true,
  64086. configurable: true
  64087. });
  64088. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  64089. get: function () {
  64090. return this._tangents !== undefined;
  64091. },
  64092. enumerable: true,
  64093. configurable: true
  64094. });
  64095. MorphTarget.prototype.setPositions = function (data) {
  64096. this._positions = new Float32Array(data);
  64097. };
  64098. MorphTarget.prototype.getPositions = function () {
  64099. return this._positions;
  64100. };
  64101. MorphTarget.prototype.setNormals = function (data) {
  64102. this._normals = new Float32Array(data);
  64103. };
  64104. MorphTarget.prototype.getNormals = function () {
  64105. return this._normals;
  64106. };
  64107. MorphTarget.prototype.setTangents = function (data) {
  64108. this._tangents = new Float32Array(data);
  64109. };
  64110. MorphTarget.prototype.getTangents = function () {
  64111. return this._tangents;
  64112. };
  64113. /**
  64114. * Serializes the current target into a Serialization object.
  64115. * Returns the serialized object.
  64116. */
  64117. MorphTarget.prototype.serialize = function () {
  64118. var serializationObject = {};
  64119. serializationObject.name = this.name;
  64120. serializationObject.influence = this.influence;
  64121. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  64122. if (this.hasNormals) {
  64123. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  64124. }
  64125. if (this.hasTangents) {
  64126. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  64127. }
  64128. return serializationObject;
  64129. };
  64130. // Statics
  64131. MorphTarget.Parse = function (serializationObject) {
  64132. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  64133. result.setPositions(serializationObject.positions);
  64134. if (serializationObject.normals) {
  64135. result.setNormals(serializationObject.normals);
  64136. }
  64137. if (serializationObject.tangents) {
  64138. result.setTangents(serializationObject.tangents);
  64139. }
  64140. return result;
  64141. };
  64142. MorphTarget.FromMesh = function (mesh, name, influence) {
  64143. if (!name) {
  64144. name = mesh.name;
  64145. }
  64146. var result = new MorphTarget(name, influence);
  64147. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  64148. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  64149. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  64150. }
  64151. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  64152. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  64153. }
  64154. return result;
  64155. };
  64156. return MorphTarget;
  64157. }());
  64158. BABYLON.MorphTarget = MorphTarget;
  64159. })(BABYLON || (BABYLON = {}));
  64160. //# sourceMappingURL=babylon.morphTarget.js.map
  64161. var BABYLON;
  64162. (function (BABYLON) {
  64163. var MorphTargetManager = (function () {
  64164. function MorphTargetManager(scene) {
  64165. this._targets = new Array();
  64166. this._targetObservable = new Array();
  64167. this._activeTargets = new BABYLON.SmartArray(16);
  64168. this._supportsNormals = false;
  64169. this._supportsTangents = false;
  64170. this._vertexCount = 0;
  64171. this._uniqueId = 0;
  64172. this._tempInfluences = new Array();
  64173. if (!scene) {
  64174. scene = BABYLON.Engine.LastCreatedScene;
  64175. }
  64176. this._scene = scene;
  64177. this._scene.morphTargetManagers.push(this);
  64178. this._uniqueId = scene.getUniqueId();
  64179. }
  64180. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  64181. get: function () {
  64182. return this._uniqueId;
  64183. },
  64184. enumerable: true,
  64185. configurable: true
  64186. });
  64187. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  64188. get: function () {
  64189. return this._vertexCount;
  64190. },
  64191. enumerable: true,
  64192. configurable: true
  64193. });
  64194. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  64195. get: function () {
  64196. return this._supportsNormals;
  64197. },
  64198. enumerable: true,
  64199. configurable: true
  64200. });
  64201. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  64202. get: function () {
  64203. return this._supportsTangents;
  64204. },
  64205. enumerable: true,
  64206. configurable: true
  64207. });
  64208. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  64209. get: function () {
  64210. return this._targets.length;
  64211. },
  64212. enumerable: true,
  64213. configurable: true
  64214. });
  64215. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  64216. get: function () {
  64217. return this._activeTargets.length;
  64218. },
  64219. enumerable: true,
  64220. configurable: true
  64221. });
  64222. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  64223. get: function () {
  64224. return this._influences;
  64225. },
  64226. enumerable: true,
  64227. configurable: true
  64228. });
  64229. MorphTargetManager.prototype.getActiveTarget = function (index) {
  64230. return this._activeTargets.data[index];
  64231. };
  64232. MorphTargetManager.prototype.getTarget = function (index) {
  64233. return this._targets[index];
  64234. };
  64235. MorphTargetManager.prototype.addTarget = function (target) {
  64236. var _this = this;
  64237. if (this._vertexCount) {
  64238. if (this._vertexCount !== target.getPositions().length / 3) {
  64239. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  64240. return;
  64241. }
  64242. }
  64243. this._targets.push(target);
  64244. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  64245. _this._syncActiveTargets(needUpdate);
  64246. }));
  64247. this._syncActiveTargets(true);
  64248. };
  64249. MorphTargetManager.prototype.removeTarget = function (target) {
  64250. var index = this._targets.indexOf(target);
  64251. if (index >= 0) {
  64252. this._targets.splice(index, 1);
  64253. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  64254. this._vertexCount = 0;
  64255. this._syncActiveTargets(true);
  64256. }
  64257. };
  64258. /**
  64259. * Serializes the current manager into a Serialization object.
  64260. * Returns the serialized object.
  64261. */
  64262. MorphTargetManager.prototype.serialize = function () {
  64263. var serializationObject = {};
  64264. serializationObject.id = this.uniqueId;
  64265. serializationObject.targets = [];
  64266. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  64267. var target = _a[_i];
  64268. serializationObject.targets.push(target.serialize());
  64269. }
  64270. return serializationObject;
  64271. };
  64272. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  64273. this._syncActiveTargets(needUpdate);
  64274. };
  64275. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  64276. var influenceCount = 0;
  64277. this._activeTargets.reset();
  64278. this._supportsNormals = true;
  64279. this._supportsTangents = true;
  64280. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  64281. var target = _a[_i];
  64282. if (target.influence > 0) {
  64283. this._activeTargets.push(target);
  64284. this._tempInfluences[influenceCount++] = target.influence;
  64285. this._supportsNormals = this._supportsNormals && target.hasNormals;
  64286. this._supportsTangents = this._supportsTangents && target.hasTangents;
  64287. if (this._vertexCount === 0) {
  64288. this._vertexCount = target.getPositions().length / 3;
  64289. }
  64290. }
  64291. }
  64292. if (!this._influences || this._influences.length !== influenceCount) {
  64293. this._influences = new Float32Array(influenceCount);
  64294. }
  64295. for (var index = 0; index < influenceCount; index++) {
  64296. this._influences[index] = this._tempInfluences[index];
  64297. }
  64298. if (needUpdate) {
  64299. // Flag meshes as dirty to resync with the active targets
  64300. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  64301. var mesh = _c[_b];
  64302. if (mesh.morphTargetManager === this) {
  64303. mesh._syncGeometryWithMorphTargetManager();
  64304. }
  64305. }
  64306. }
  64307. };
  64308. // Statics
  64309. MorphTargetManager.Parse = function (serializationObject, scene) {
  64310. var result = new MorphTargetManager(scene);
  64311. result._uniqueId = serializationObject.id;
  64312. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  64313. var targetData = _a[_i];
  64314. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  64315. }
  64316. return result;
  64317. };
  64318. return MorphTargetManager;
  64319. }());
  64320. BABYLON.MorphTargetManager = MorphTargetManager;
  64321. })(BABYLON || (BABYLON = {}));
  64322. //# sourceMappingURL=babylon.morphTargetManager.js.map
  64323. var BABYLON;
  64324. (function (BABYLON) {
  64325. /**
  64326. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  64327. * It can help converting any input color in a desired output one. This can then be used to create effects
  64328. * from sepia, black and white to sixties or futuristic rendering...
  64329. *
  64330. * The only supported format is currently 3dl.
  64331. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  64332. */
  64333. var ColorGradingTexture = (function (_super) {
  64334. __extends(ColorGradingTexture, _super);
  64335. /**
  64336. * Instantiates a ColorGradingTexture from the following parameters.
  64337. *
  64338. * @param url The location of the color gradind data (currently only supporting 3dl)
  64339. * @param scene The scene the texture will be used in
  64340. */
  64341. function ColorGradingTexture(url, scene) {
  64342. var _this = _super.call(this, scene) || this;
  64343. if (!url) {
  64344. return _this;
  64345. }
  64346. _this._textureMatrix = BABYLON.Matrix.Identity();
  64347. _this.name = url;
  64348. _this.url = url;
  64349. _this.hasAlpha = false;
  64350. _this.isCube = false;
  64351. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64352. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64353. _this.anisotropicFilteringLevel = 1;
  64354. _this._texture = _this._getFromCache(url, true);
  64355. if (!_this._texture) {
  64356. if (!scene.useDelayedTextureLoading) {
  64357. _this.loadTexture();
  64358. }
  64359. else {
  64360. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  64361. }
  64362. }
  64363. return _this;
  64364. }
  64365. /**
  64366. * Returns the texture matrix used in most of the material.
  64367. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  64368. */
  64369. ColorGradingTexture.prototype.getTextureMatrix = function () {
  64370. return this._textureMatrix;
  64371. };
  64372. /**
  64373. * Occurs when the file being loaded is a .3dl LUT file.
  64374. */
  64375. ColorGradingTexture.prototype.load3dlTexture = function () {
  64376. var _this = this;
  64377. var mipLevels = 0;
  64378. var floatArrayView = null;
  64379. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64380. this._texture = texture;
  64381. var callback = function (text) {
  64382. var data;
  64383. var tempData;
  64384. var line;
  64385. var lines = text.split('\n');
  64386. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  64387. var maxColor = 0;
  64388. for (var i = 0; i < lines.length; i++) {
  64389. line = lines[i];
  64390. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  64391. continue;
  64392. if (line.indexOf('#') === 0)
  64393. continue;
  64394. var words = line.split(" ");
  64395. if (size === 0) {
  64396. // Number of space + one
  64397. size = words.length;
  64398. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  64399. tempData = new Float32Array(size * size * size * 4);
  64400. continue;
  64401. }
  64402. if (size != 0) {
  64403. var r = Math.max(parseInt(words[0]), 0);
  64404. var g = Math.max(parseInt(words[1]), 0);
  64405. var b = Math.max(parseInt(words[2]), 0);
  64406. maxColor = Math.max(r, maxColor);
  64407. maxColor = Math.max(g, maxColor);
  64408. maxColor = Math.max(b, maxColor);
  64409. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  64410. tempData[pixelStorageIndex + 0] = r;
  64411. tempData[pixelStorageIndex + 1] = g;
  64412. tempData[pixelStorageIndex + 2] = b;
  64413. pixelIndexSlice++;
  64414. if (pixelIndexSlice % size == 0) {
  64415. pixelIndexH++;
  64416. pixelIndexSlice = 0;
  64417. if (pixelIndexH % size == 0) {
  64418. pixelIndexW++;
  64419. pixelIndexH = 0;
  64420. }
  64421. }
  64422. }
  64423. }
  64424. for (var i = 0; i < tempData.length; i++) {
  64425. if (i > 0 && (i + 1) % 4 === 0) {
  64426. data[i] = 255;
  64427. }
  64428. else {
  64429. var value = tempData[i];
  64430. data[i] = (value / maxColor * 255);
  64431. }
  64432. }
  64433. texture.updateSize(size * size, size);
  64434. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  64435. };
  64436. BABYLON.Tools.LoadFile(this.url, callback);
  64437. return this._texture;
  64438. };
  64439. /**
  64440. * Starts the loading process of the texture.
  64441. */
  64442. ColorGradingTexture.prototype.loadTexture = function () {
  64443. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  64444. this.load3dlTexture();
  64445. }
  64446. };
  64447. /**
  64448. * Clones the color gradind texture.
  64449. */
  64450. ColorGradingTexture.prototype.clone = function () {
  64451. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  64452. // Base texture
  64453. newTexture.level = this.level;
  64454. return newTexture;
  64455. };
  64456. /**
  64457. * Called during delayed load for textures.
  64458. */
  64459. ColorGradingTexture.prototype.delayLoad = function () {
  64460. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  64461. return;
  64462. }
  64463. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  64464. this._texture = this._getFromCache(this.url, true);
  64465. if (!this._texture) {
  64466. this.loadTexture();
  64467. }
  64468. };
  64469. /**
  64470. * Parses a color grading texture serialized by Babylon.
  64471. * @param parsedTexture The texture information being parsedTexture
  64472. * @param scene The scene to load the texture in
  64473. * @param rootUrl The root url of the data assets to load
  64474. * @return A color gradind texture
  64475. */
  64476. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  64477. var texture = null;
  64478. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  64479. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  64480. texture.name = parsedTexture.name;
  64481. texture.level = parsedTexture.level;
  64482. }
  64483. return texture;
  64484. };
  64485. /**
  64486. * Serializes the LUT texture to json format.
  64487. */
  64488. ColorGradingTexture.prototype.serialize = function () {
  64489. if (!this.name) {
  64490. return null;
  64491. }
  64492. var serializationObject = {};
  64493. serializationObject.name = this.name;
  64494. serializationObject.level = this.level;
  64495. serializationObject.customType = "BABYLON.ColorGradingTexture";
  64496. return serializationObject;
  64497. };
  64498. /**
  64499. * Empty line regex stored for GC.
  64500. */
  64501. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  64502. return ColorGradingTexture;
  64503. }(BABYLON.BaseTexture));
  64504. BABYLON.ColorGradingTexture = ColorGradingTexture;
  64505. })(BABYLON || (BABYLON = {}));
  64506. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  64507. var BABYLON;
  64508. (function (BABYLON) {
  64509. /**
  64510. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  64511. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  64512. * 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;
  64513. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  64514. */
  64515. var ColorCurves = (function () {
  64516. function ColorCurves() {
  64517. this._dirty = true;
  64518. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  64519. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  64520. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  64521. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  64522. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  64523. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  64524. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  64525. this._globalHue = 30;
  64526. this._globalDensity = 0;
  64527. this._globalSaturation = 0;
  64528. this._globalExposure = 0;
  64529. this._highlightsHue = 30;
  64530. this._highlightsDensity = 0;
  64531. this._highlightsSaturation = 0;
  64532. this._highlightsExposure = 0;
  64533. this._midtonesHue = 30;
  64534. this._midtonesDensity = 0;
  64535. this._midtonesSaturation = 0;
  64536. this._midtonesExposure = 0;
  64537. this._shadowsHue = 30;
  64538. this._shadowsDensity = 0;
  64539. this._shadowsSaturation = 0;
  64540. this._shadowsExposure = 0;
  64541. }
  64542. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  64543. /**
  64544. * Gets the global Hue value.
  64545. * 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).
  64546. */
  64547. get: function () {
  64548. return this._globalHue;
  64549. },
  64550. /**
  64551. * Sets the global Hue value.
  64552. * 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).
  64553. */
  64554. set: function (value) {
  64555. this._globalHue = value;
  64556. this._dirty = true;
  64557. },
  64558. enumerable: true,
  64559. configurable: true
  64560. });
  64561. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  64562. /**
  64563. * Gets the global Density value.
  64564. * 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.
  64565. * Values less than zero provide a filter of opposite hue.
  64566. */
  64567. get: function () {
  64568. return this._globalDensity;
  64569. },
  64570. /**
  64571. * Sets the global Density value.
  64572. * 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.
  64573. * Values less than zero provide a filter of opposite hue.
  64574. */
  64575. set: function (value) {
  64576. this._globalDensity = value;
  64577. this._dirty = true;
  64578. },
  64579. enumerable: true,
  64580. configurable: true
  64581. });
  64582. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  64583. /**
  64584. * Gets the global Saturation value.
  64585. * 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.
  64586. */
  64587. get: function () {
  64588. return this._globalSaturation;
  64589. },
  64590. /**
  64591. * Sets the global Saturation value.
  64592. * 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.
  64593. */
  64594. set: function (value) {
  64595. this._globalSaturation = value;
  64596. this._dirty = true;
  64597. },
  64598. enumerable: true,
  64599. configurable: true
  64600. });
  64601. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  64602. /**
  64603. * Gets the highlights Hue value.
  64604. * 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).
  64605. */
  64606. get: function () {
  64607. return this._highlightsHue;
  64608. },
  64609. /**
  64610. * Sets the highlights Hue value.
  64611. * 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).
  64612. */
  64613. set: function (value) {
  64614. this._highlightsHue = value;
  64615. this._dirty = true;
  64616. },
  64617. enumerable: true,
  64618. configurable: true
  64619. });
  64620. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  64621. /**
  64622. * Gets the highlights Density value.
  64623. * 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.
  64624. * Values less than zero provide a filter of opposite hue.
  64625. */
  64626. get: function () {
  64627. return this._highlightsDensity;
  64628. },
  64629. /**
  64630. * Sets the highlights Density value.
  64631. * 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.
  64632. * Values less than zero provide a filter of opposite hue.
  64633. */
  64634. set: function (value) {
  64635. this._highlightsDensity = value;
  64636. this._dirty = true;
  64637. },
  64638. enumerable: true,
  64639. configurable: true
  64640. });
  64641. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  64642. /**
  64643. * Gets the highlights Saturation value.
  64644. * 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.
  64645. */
  64646. get: function () {
  64647. return this._highlightsSaturation;
  64648. },
  64649. /**
  64650. * Sets the highlights Saturation value.
  64651. * 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.
  64652. */
  64653. set: function (value) {
  64654. this._highlightsSaturation = value;
  64655. this._dirty = true;
  64656. },
  64657. enumerable: true,
  64658. configurable: true
  64659. });
  64660. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  64661. /**
  64662. * Gets the highlights Exposure value.
  64663. * 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.
  64664. */
  64665. get: function () {
  64666. return this._highlightsExposure;
  64667. },
  64668. /**
  64669. * Sets the highlights Exposure value.
  64670. * 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.
  64671. */
  64672. set: function (value) {
  64673. this._highlightsExposure = value;
  64674. this._dirty = true;
  64675. },
  64676. enumerable: true,
  64677. configurable: true
  64678. });
  64679. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  64680. /**
  64681. * Gets the midtones Hue value.
  64682. * 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).
  64683. */
  64684. get: function () {
  64685. return this._midtonesHue;
  64686. },
  64687. /**
  64688. * Sets the midtones Hue value.
  64689. * 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).
  64690. */
  64691. set: function (value) {
  64692. this._midtonesHue = value;
  64693. this._dirty = true;
  64694. },
  64695. enumerable: true,
  64696. configurable: true
  64697. });
  64698. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  64699. /**
  64700. * Gets the midtones Density value.
  64701. * 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.
  64702. * Values less than zero provide a filter of opposite hue.
  64703. */
  64704. get: function () {
  64705. return this._midtonesDensity;
  64706. },
  64707. /**
  64708. * Sets the midtones Density value.
  64709. * 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.
  64710. * Values less than zero provide a filter of opposite hue.
  64711. */
  64712. set: function (value) {
  64713. this._midtonesDensity = value;
  64714. this._dirty = true;
  64715. },
  64716. enumerable: true,
  64717. configurable: true
  64718. });
  64719. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  64720. /**
  64721. * Gets the midtones Saturation value.
  64722. * 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.
  64723. */
  64724. get: function () {
  64725. return this._midtonesSaturation;
  64726. },
  64727. /**
  64728. * Sets the midtones Saturation value.
  64729. * 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.
  64730. */
  64731. set: function (value) {
  64732. this._midtonesSaturation = value;
  64733. this._dirty = true;
  64734. },
  64735. enumerable: true,
  64736. configurable: true
  64737. });
  64738. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  64739. /**
  64740. * Gets the midtones Exposure value.
  64741. * 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.
  64742. */
  64743. get: function () {
  64744. return this._midtonesExposure;
  64745. },
  64746. /**
  64747. * Sets the midtones Exposure value.
  64748. * 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.
  64749. */
  64750. set: function (value) {
  64751. this._midtonesExposure = value;
  64752. this._dirty = true;
  64753. },
  64754. enumerable: true,
  64755. configurable: true
  64756. });
  64757. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  64758. /**
  64759. * Gets the shadows Hue value.
  64760. * 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).
  64761. */
  64762. get: function () {
  64763. return this._shadowsHue;
  64764. },
  64765. /**
  64766. * Sets the shadows Hue value.
  64767. * 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).
  64768. */
  64769. set: function (value) {
  64770. this._shadowsHue = value;
  64771. this._dirty = true;
  64772. },
  64773. enumerable: true,
  64774. configurable: true
  64775. });
  64776. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  64777. /**
  64778. * Gets the shadows Density value.
  64779. * 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.
  64780. * Values less than zero provide a filter of opposite hue.
  64781. */
  64782. get: function () {
  64783. return this._shadowsDensity;
  64784. },
  64785. /**
  64786. * Sets the shadows Density value.
  64787. * 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.
  64788. * Values less than zero provide a filter of opposite hue.
  64789. */
  64790. set: function (value) {
  64791. this._shadowsDensity = value;
  64792. this._dirty = true;
  64793. },
  64794. enumerable: true,
  64795. configurable: true
  64796. });
  64797. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  64798. /**
  64799. * Gets the shadows Saturation value.
  64800. * 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.
  64801. */
  64802. get: function () {
  64803. return this._shadowsSaturation;
  64804. },
  64805. /**
  64806. * Sets the shadows Saturation value.
  64807. * 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.
  64808. */
  64809. set: function (value) {
  64810. this._shadowsSaturation = value;
  64811. this._dirty = true;
  64812. },
  64813. enumerable: true,
  64814. configurable: true
  64815. });
  64816. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  64817. /**
  64818. * Gets the shadows Exposure value.
  64819. * 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.
  64820. */
  64821. get: function () {
  64822. return this._shadowsExposure;
  64823. },
  64824. /**
  64825. * Sets the shadows Exposure value.
  64826. * 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.
  64827. */
  64828. set: function (value) {
  64829. this._shadowsExposure = value;
  64830. this._dirty = true;
  64831. },
  64832. enumerable: true,
  64833. configurable: true
  64834. });
  64835. ColorCurves.prototype.getClassName = function () {
  64836. return "ColorCurves";
  64837. };
  64838. /**
  64839. * Binds the color curves to the shader.
  64840. * @param colorCurves The color curve to bind
  64841. * @param effect The effect to bind to
  64842. */
  64843. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  64844. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  64845. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  64846. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  64847. if (colorCurves._dirty) {
  64848. colorCurves._dirty = false;
  64849. // Fill in global info.
  64850. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  64851. // Compute highlights info.
  64852. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  64853. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  64854. // Compute midtones info.
  64855. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  64856. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  64857. // Compute shadows info.
  64858. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  64859. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  64860. // Compute deltas (neutral is midtones).
  64861. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  64862. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  64863. }
  64864. if (effect) {
  64865. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  64866. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  64867. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  64868. }
  64869. };
  64870. /**
  64871. * Prepare the list of uniforms associated with the ColorCurves effects.
  64872. * @param uniformsList The list of uniforms used in the effect
  64873. */
  64874. ColorCurves.PrepareUniforms = function (uniformsList) {
  64875. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  64876. };
  64877. /**
  64878. * Returns color grading data based on a hue, density, saturation and exposure value.
  64879. * @param filterHue The hue of the color filter.
  64880. * @param filterDensity The density of the color filter.
  64881. * @param saturation The saturation.
  64882. * @param exposure The exposure.
  64883. * @param result The result data container.
  64884. */
  64885. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  64886. if (hue == null) {
  64887. return;
  64888. }
  64889. hue = ColorCurves.clamp(hue, 0, 360);
  64890. density = ColorCurves.clamp(density, -100, 100);
  64891. saturation = ColorCurves.clamp(saturation, -100, 100);
  64892. exposure = ColorCurves.clamp(exposure, -100, 100);
  64893. // Remap the slider/config filter density with non-linear mapping and also scale by half
  64894. // so that the maximum filter density is only 50% control. This provides fine control
  64895. // for small values and reasonable range.
  64896. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  64897. density *= 0.5;
  64898. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  64899. if (density < 0) {
  64900. density *= -1;
  64901. hue = (hue + 180) % 360;
  64902. }
  64903. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  64904. result.scaleToRef(2, result);
  64905. result.a = 1 + 0.01 * saturation;
  64906. };
  64907. /**
  64908. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  64909. * @param value The input slider value in range [-100,100].
  64910. * @returns Adjusted value.
  64911. */
  64912. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  64913. value /= 100;
  64914. var x = Math.abs(value);
  64915. x = Math.pow(x, 2);
  64916. if (value < 0) {
  64917. x *= -1;
  64918. }
  64919. x *= 100;
  64920. return x;
  64921. };
  64922. /**
  64923. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  64924. * @param hue The hue (H) input.
  64925. * @param saturation The saturation (S) input.
  64926. * @param brightness The brightness (B) input.
  64927. * @result An RGBA color represented as Vector4.
  64928. */
  64929. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  64930. var h = ColorCurves.clamp(hue, 0, 360);
  64931. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  64932. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  64933. if (s === 0) {
  64934. result.r = v;
  64935. result.g = v;
  64936. result.b = v;
  64937. }
  64938. else {
  64939. // sector 0 to 5
  64940. h /= 60;
  64941. var i = Math.floor(h);
  64942. // fractional part of h
  64943. var f = h - i;
  64944. var p = v * (1 - s);
  64945. var q = v * (1 - s * f);
  64946. var t = v * (1 - s * (1 - f));
  64947. switch (i) {
  64948. case 0:
  64949. result.r = v;
  64950. result.g = t;
  64951. result.b = p;
  64952. break;
  64953. case 1:
  64954. result.r = q;
  64955. result.g = v;
  64956. result.b = p;
  64957. break;
  64958. case 2:
  64959. result.r = p;
  64960. result.g = v;
  64961. result.b = t;
  64962. break;
  64963. case 3:
  64964. result.r = p;
  64965. result.g = q;
  64966. result.b = v;
  64967. break;
  64968. case 4:
  64969. result.r = t;
  64970. result.g = p;
  64971. result.b = v;
  64972. break;
  64973. default:// case 5:
  64974. result.r = v;
  64975. result.g = p;
  64976. result.b = q;
  64977. break;
  64978. }
  64979. }
  64980. result.a = 1;
  64981. };
  64982. /**
  64983. * Returns a value clamped between min and max
  64984. * @param value The value to clamp
  64985. * @param min The minimum of value
  64986. * @param max The maximum of value
  64987. * @returns The clamped value.
  64988. */
  64989. ColorCurves.clamp = function (value, min, max) {
  64990. return Math.min(Math.max(value, min), max);
  64991. };
  64992. /**
  64993. * Clones the current color curve instance.
  64994. * @return The cloned curves
  64995. */
  64996. ColorCurves.prototype.clone = function () {
  64997. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  64998. };
  64999. /**
  65000. * Serializes the current color curve instance to a json representation.
  65001. * @return a JSON representation
  65002. */
  65003. ColorCurves.prototype.serialize = function () {
  65004. return BABYLON.SerializationHelper.Serialize(this);
  65005. };
  65006. /**
  65007. * Parses the color curve from a json representation.
  65008. * @param source the JSON source to parse
  65009. * @return The parsed curves
  65010. */
  65011. ColorCurves.Parse = function (source) {
  65012. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  65013. };
  65014. __decorate([
  65015. BABYLON.serialize()
  65016. ], ColorCurves.prototype, "_globalHue", void 0);
  65017. __decorate([
  65018. BABYLON.serialize()
  65019. ], ColorCurves.prototype, "_globalDensity", void 0);
  65020. __decorate([
  65021. BABYLON.serialize()
  65022. ], ColorCurves.prototype, "_globalSaturation", void 0);
  65023. __decorate([
  65024. BABYLON.serialize()
  65025. ], ColorCurves.prototype, "_globalExposure", void 0);
  65026. __decorate([
  65027. BABYLON.serialize()
  65028. ], ColorCurves.prototype, "_highlightsHue", void 0);
  65029. __decorate([
  65030. BABYLON.serialize()
  65031. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  65032. __decorate([
  65033. BABYLON.serialize()
  65034. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  65035. __decorate([
  65036. BABYLON.serialize()
  65037. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  65038. __decorate([
  65039. BABYLON.serialize()
  65040. ], ColorCurves.prototype, "_midtonesHue", void 0);
  65041. __decorate([
  65042. BABYLON.serialize()
  65043. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  65044. __decorate([
  65045. BABYLON.serialize()
  65046. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  65047. __decorate([
  65048. BABYLON.serialize()
  65049. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  65050. return ColorCurves;
  65051. }());
  65052. BABYLON.ColorCurves = ColorCurves;
  65053. })(BABYLON || (BABYLON = {}));
  65054. //# sourceMappingURL=babylon.colorCurves.js.map
  65055. var BABYLON;
  65056. (function (BABYLON) {
  65057. var Octree = (function () {
  65058. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  65059. if (maxDepth === void 0) { maxDepth = 2; }
  65060. this.maxDepth = maxDepth;
  65061. this.dynamicContent = new Array();
  65062. this._maxBlockCapacity = maxBlockCapacity || 64;
  65063. this._selectionContent = new BABYLON.SmartArray(1024);
  65064. this._creationFunc = creationFunc;
  65065. }
  65066. // Methods
  65067. Octree.prototype.update = function (worldMin, worldMax, entries) {
  65068. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  65069. };
  65070. Octree.prototype.addMesh = function (entry) {
  65071. for (var index = 0; index < this.blocks.length; index++) {
  65072. var block = this.blocks[index];
  65073. block.addEntry(entry);
  65074. }
  65075. };
  65076. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  65077. this._selectionContent.reset();
  65078. for (var index = 0; index < this.blocks.length; index++) {
  65079. var block = this.blocks[index];
  65080. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  65081. }
  65082. if (allowDuplicate) {
  65083. this._selectionContent.concat(this.dynamicContent);
  65084. }
  65085. else {
  65086. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  65087. }
  65088. return this._selectionContent;
  65089. };
  65090. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  65091. this._selectionContent.reset();
  65092. for (var index = 0; index < this.blocks.length; index++) {
  65093. var block = this.blocks[index];
  65094. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  65095. }
  65096. if (allowDuplicate) {
  65097. this._selectionContent.concat(this.dynamicContent);
  65098. }
  65099. else {
  65100. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  65101. }
  65102. return this._selectionContent;
  65103. };
  65104. Octree.prototype.intersectsRay = function (ray) {
  65105. this._selectionContent.reset();
  65106. for (var index = 0; index < this.blocks.length; index++) {
  65107. var block = this.blocks[index];
  65108. block.intersectsRay(ray, this._selectionContent);
  65109. }
  65110. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  65111. return this._selectionContent;
  65112. };
  65113. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  65114. target.blocks = new Array();
  65115. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  65116. // Segmenting space
  65117. for (var x = 0; x < 2; x++) {
  65118. for (var y = 0; y < 2; y++) {
  65119. for (var z = 0; z < 2; z++) {
  65120. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  65121. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  65122. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  65123. block.addEntries(entries);
  65124. target.blocks.push(block);
  65125. }
  65126. }
  65127. }
  65128. };
  65129. Octree.CreationFuncForMeshes = function (entry, block) {
  65130. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  65131. block.entries.push(entry);
  65132. }
  65133. };
  65134. Octree.CreationFuncForSubMeshes = function (entry, block) {
  65135. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  65136. block.entries.push(entry);
  65137. }
  65138. };
  65139. return Octree;
  65140. }());
  65141. BABYLON.Octree = Octree;
  65142. })(BABYLON || (BABYLON = {}));
  65143. //# sourceMappingURL=babylon.octree.js.map
  65144. var BABYLON;
  65145. (function (BABYLON) {
  65146. var OctreeBlock = (function () {
  65147. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  65148. this.entries = new Array();
  65149. this._boundingVectors = new Array();
  65150. this._capacity = capacity;
  65151. this._depth = depth;
  65152. this._maxDepth = maxDepth;
  65153. this._creationFunc = creationFunc;
  65154. this._minPoint = minPoint;
  65155. this._maxPoint = maxPoint;
  65156. this._boundingVectors.push(minPoint.clone());
  65157. this._boundingVectors.push(maxPoint.clone());
  65158. this._boundingVectors.push(minPoint.clone());
  65159. this._boundingVectors[2].x = maxPoint.x;
  65160. this._boundingVectors.push(minPoint.clone());
  65161. this._boundingVectors[3].y = maxPoint.y;
  65162. this._boundingVectors.push(minPoint.clone());
  65163. this._boundingVectors[4].z = maxPoint.z;
  65164. this._boundingVectors.push(maxPoint.clone());
  65165. this._boundingVectors[5].z = minPoint.z;
  65166. this._boundingVectors.push(maxPoint.clone());
  65167. this._boundingVectors[6].x = minPoint.x;
  65168. this._boundingVectors.push(maxPoint.clone());
  65169. this._boundingVectors[7].y = minPoint.y;
  65170. }
  65171. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  65172. // Property
  65173. get: function () {
  65174. return this._capacity;
  65175. },
  65176. enumerable: true,
  65177. configurable: true
  65178. });
  65179. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  65180. get: function () {
  65181. return this._minPoint;
  65182. },
  65183. enumerable: true,
  65184. configurable: true
  65185. });
  65186. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  65187. get: function () {
  65188. return this._maxPoint;
  65189. },
  65190. enumerable: true,
  65191. configurable: true
  65192. });
  65193. // Methods
  65194. OctreeBlock.prototype.addEntry = function (entry) {
  65195. if (this.blocks) {
  65196. for (var index = 0; index < this.blocks.length; index++) {
  65197. var block = this.blocks[index];
  65198. block.addEntry(entry);
  65199. }
  65200. return;
  65201. }
  65202. this._creationFunc(entry, this);
  65203. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  65204. this.createInnerBlocks();
  65205. }
  65206. };
  65207. OctreeBlock.prototype.addEntries = function (entries) {
  65208. for (var index = 0; index < entries.length; index++) {
  65209. var mesh = entries[index];
  65210. this.addEntry(mesh);
  65211. }
  65212. };
  65213. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  65214. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  65215. if (this.blocks) {
  65216. for (var index = 0; index < this.blocks.length; index++) {
  65217. var block = this.blocks[index];
  65218. block.select(frustumPlanes, selection, allowDuplicate);
  65219. }
  65220. return;
  65221. }
  65222. if (allowDuplicate) {
  65223. selection.concat(this.entries);
  65224. }
  65225. else {
  65226. selection.concatWithNoDuplicate(this.entries);
  65227. }
  65228. }
  65229. };
  65230. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  65231. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  65232. if (this.blocks) {
  65233. for (var index = 0; index < this.blocks.length; index++) {
  65234. var block = this.blocks[index];
  65235. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  65236. }
  65237. return;
  65238. }
  65239. if (allowDuplicate) {
  65240. selection.concat(this.entries);
  65241. }
  65242. else {
  65243. selection.concatWithNoDuplicate(this.entries);
  65244. }
  65245. }
  65246. };
  65247. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  65248. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  65249. if (this.blocks) {
  65250. for (var index = 0; index < this.blocks.length; index++) {
  65251. var block = this.blocks[index];
  65252. block.intersectsRay(ray, selection);
  65253. }
  65254. return;
  65255. }
  65256. selection.concatWithNoDuplicate(this.entries);
  65257. }
  65258. };
  65259. OctreeBlock.prototype.createInnerBlocks = function () {
  65260. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  65261. };
  65262. return OctreeBlock;
  65263. }());
  65264. BABYLON.OctreeBlock = OctreeBlock;
  65265. })(BABYLON || (BABYLON = {}));
  65266. //# sourceMappingURL=babylon.octreeBlock.js.map
  65267. var BABYLON;
  65268. (function (BABYLON) {
  65269. var SIMDVector3 = (function () {
  65270. function SIMDVector3() {
  65271. }
  65272. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  65273. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  65274. };
  65275. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  65276. var m = transformation.m;
  65277. var m0 = SIMD.Float32x4.load(m, 0);
  65278. var m1 = SIMD.Float32x4.load(m, 4);
  65279. var m2 = SIMD.Float32x4.load(m, 8);
  65280. var m3 = SIMD.Float32x4.load(m, 12);
  65281. 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));
  65282. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  65283. result.x = SIMD.Float32x4.extractLane(r, 0);
  65284. result.y = SIMD.Float32x4.extractLane(r, 1);
  65285. result.z = SIMD.Float32x4.extractLane(r, 2);
  65286. };
  65287. return SIMDVector3;
  65288. }());
  65289. var SIMDMatrix = (function () {
  65290. function SIMDMatrix() {
  65291. }
  65292. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  65293. var tm = this.m;
  65294. var om = other.m;
  65295. var m0 = SIMD.Float32x4.load(om, 0);
  65296. var m1 = SIMD.Float32x4.load(om, 4);
  65297. var m2 = SIMD.Float32x4.load(om, 8);
  65298. var m3 = SIMD.Float32x4.load(om, 12);
  65299. for (var i = 0; i < 16; i += 4) {
  65300. 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)))));
  65301. }
  65302. return this;
  65303. };
  65304. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  65305. var src = this.m;
  65306. var dest = other.m;
  65307. // Load the 4 rows
  65308. var src0 = SIMD.Float32x4.load(src, 0);
  65309. var src1 = SIMD.Float32x4.load(src, 4);
  65310. var src2 = SIMD.Float32x4.load(src, 8);
  65311. var src3 = SIMD.Float32x4.load(src, 12);
  65312. // Transpose the source matrix. Sort of. Not a true transpose operation
  65313. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  65314. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  65315. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  65316. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  65317. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  65318. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  65319. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  65320. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  65321. // This is a true transposition, but it will lead to an incorrect result
  65322. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  65323. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  65324. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  65325. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  65326. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  65327. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  65328. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  65329. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  65330. // ----
  65331. tmp1 = SIMD.Float32x4.mul(row2, row3);
  65332. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65333. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  65334. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  65335. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  65336. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  65337. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  65338. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  65339. // ----
  65340. tmp1 = SIMD.Float32x4.mul(row1, row2);
  65341. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65342. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  65343. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  65344. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  65345. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  65346. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  65347. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  65348. // ----
  65349. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  65350. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65351. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  65352. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  65353. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  65354. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  65355. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  65356. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  65357. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  65358. // ----
  65359. tmp1 = SIMD.Float32x4.mul(row0, row1);
  65360. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65361. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  65362. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  65363. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  65364. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  65365. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  65366. // ----
  65367. tmp1 = SIMD.Float32x4.mul(row0, row3);
  65368. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65369. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  65370. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  65371. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  65372. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  65373. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  65374. // ----
  65375. tmp1 = SIMD.Float32x4.mul(row0, row2);
  65376. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  65377. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  65378. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  65379. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  65380. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  65381. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  65382. // Compute determinant
  65383. var det = SIMD.Float32x4.mul(row0, minor0);
  65384. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  65385. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  65386. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  65387. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  65388. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  65389. // These shuffles aren't necessary if the faulty transposition is done
  65390. // up at the top of this function.
  65391. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  65392. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  65393. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  65394. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  65395. // Compute final values by multiplying with 1/det
  65396. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  65397. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  65398. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  65399. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  65400. return this;
  65401. };
  65402. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  65403. var out = result.m;
  65404. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  65405. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  65406. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  65407. // cc.kmVec3Subtract(f, pCenter, pEye);
  65408. var f = SIMD.Float32x4.sub(center, eye);
  65409. // cc.kmVec3Normalize(f, f);
  65410. var tmp = SIMD.Float32x4.mul(f, f);
  65411. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  65412. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  65413. // cc.kmVec3Assign(up, pUp);
  65414. // cc.kmVec3Normalize(up, up);
  65415. tmp = SIMD.Float32x4.mul(up, up);
  65416. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  65417. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  65418. // cc.kmVec3Cross(s, f, up);
  65419. 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)));
  65420. // cc.kmVec3Normalize(s, s);
  65421. tmp = SIMD.Float32x4.mul(s, s);
  65422. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  65423. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  65424. // cc.kmVec3Cross(u, s, f);
  65425. 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)));
  65426. // cc.kmVec3Normalize(s, s);
  65427. tmp = SIMD.Float32x4.mul(s, s);
  65428. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  65429. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  65430. var zero = SIMD.Float32x4.splat(0.0);
  65431. s = SIMD.Float32x4.neg(s);
  65432. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  65433. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  65434. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  65435. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  65436. 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);
  65437. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  65438. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  65439. 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)))));
  65440. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  65441. 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)))));
  65442. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  65443. 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)))));
  65444. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  65445. 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)))));
  65446. };
  65447. return SIMDMatrix;
  65448. }());
  65449. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  65450. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  65451. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  65452. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  65453. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  65454. var SIMDHelper = (function () {
  65455. function SIMDHelper() {
  65456. }
  65457. Object.defineProperty(SIMDHelper, "IsEnabled", {
  65458. get: function () {
  65459. return SIMDHelper._isEnabled;
  65460. },
  65461. enumerable: true,
  65462. configurable: true
  65463. });
  65464. SIMDHelper.DisableSIMD = function () {
  65465. // Replace functions
  65466. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  65467. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  65468. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  65469. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  65470. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  65471. SIMDHelper._isEnabled = false;
  65472. };
  65473. SIMDHelper.EnableSIMD = function () {
  65474. if (self.SIMD === undefined) {
  65475. return;
  65476. }
  65477. // check if polyfills needed
  65478. if (!self.Math.fround) {
  65479. self.Math.fround = (function (array) { return function (x) {
  65480. return array[0] = x, array[0];
  65481. }; })(new Float32Array(1));
  65482. }
  65483. if (!self.Math.imul) {
  65484. self.Math.imul = function (a, b) {
  65485. var ah = (a >>> 16) & 0xffff;
  65486. var al = a & 0xffff;
  65487. var bh = (b >>> 16) & 0xffff;
  65488. var bl = b & 0xffff;
  65489. // the shift by 0 fixes the sign on the high part
  65490. // the final |0 converts the unsigned value into a signed value
  65491. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  65492. };
  65493. }
  65494. // Replace functions
  65495. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  65496. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  65497. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  65498. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  65499. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  65500. SIMDHelper._isEnabled = true;
  65501. };
  65502. SIMDHelper._isEnabled = false;
  65503. return SIMDHelper;
  65504. }());
  65505. BABYLON.SIMDHelper = SIMDHelper;
  65506. })(BABYLON || (BABYLON = {}));
  65507. //# sourceMappingURL=babylon.math.SIMD.js.map
  65508. var BABYLON;
  65509. (function (BABYLON) {
  65510. var VRDistortionCorrectionPostProcess = (function (_super) {
  65511. __extends(VRDistortionCorrectionPostProcess, _super);
  65512. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  65513. var _this = _super.call(this, name, "vrDistortionCorrection", [
  65514. 'LensCenter',
  65515. 'Scale',
  65516. 'ScaleIn',
  65517. 'HmdWarpParam'
  65518. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  65519. _this._isRightEye = isRightEye;
  65520. _this._distortionFactors = vrMetrics.distortionK;
  65521. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  65522. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  65523. _this.adaptScaleToCurrentViewport = true;
  65524. _this.onSizeChangedObservable.add(function () {
  65525. _this.aspectRatio = _this.width * .5 / _this.height;
  65526. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  65527. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  65528. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  65529. });
  65530. _this.onApplyObservable.add(function (effect) {
  65531. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  65532. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  65533. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  65534. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  65535. });
  65536. return _this;
  65537. }
  65538. return VRDistortionCorrectionPostProcess;
  65539. }(BABYLON.PostProcess));
  65540. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  65541. })(BABYLON || (BABYLON = {}));
  65542. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  65543. var BABYLON;
  65544. (function (BABYLON) {
  65545. var AnaglyphPostProcess = (function (_super) {
  65546. __extends(AnaglyphPostProcess, _super);
  65547. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  65548. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  65549. _this._passedProcess = rigCameras[0]._rigPostProcess;
  65550. _this.onApplyObservable.add(function (effect) {
  65551. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  65552. });
  65553. return _this;
  65554. }
  65555. return AnaglyphPostProcess;
  65556. }(BABYLON.PostProcess));
  65557. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  65558. })(BABYLON || (BABYLON = {}));
  65559. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  65560. var BABYLON;
  65561. (function (BABYLON) {
  65562. var StereoscopicInterlacePostProcess = (function (_super) {
  65563. __extends(StereoscopicInterlacePostProcess, _super);
  65564. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  65565. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  65566. _this._passedProcess = rigCameras[0]._rigPostProcess;
  65567. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  65568. _this.onSizeChangedObservable.add(function () {
  65569. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  65570. });
  65571. _this.onApplyObservable.add(function (effect) {
  65572. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  65573. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  65574. });
  65575. return _this;
  65576. }
  65577. return StereoscopicInterlacePostProcess;
  65578. }(BABYLON.PostProcess));
  65579. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  65580. })(BABYLON || (BABYLON = {}));
  65581. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  65582. var BABYLON;
  65583. (function (BABYLON) {
  65584. var FreeCameraDeviceOrientationInput = (function () {
  65585. function FreeCameraDeviceOrientationInput() {
  65586. var _this = this;
  65587. this._screenOrientationAngle = 0;
  65588. this._screenQuaternion = new BABYLON.Quaternion();
  65589. this._alpha = 0;
  65590. this._beta = 0;
  65591. this._gamma = 0;
  65592. this._orientationChanged = function () {
  65593. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  65594. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  65595. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  65596. };
  65597. this._deviceOrientation = function (evt) {
  65598. _this._alpha = evt.alpha;
  65599. _this._beta = evt.beta;
  65600. _this._gamma = evt.gamma;
  65601. };
  65602. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  65603. this._orientationChanged();
  65604. }
  65605. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  65606. get: function () {
  65607. return this._camera;
  65608. },
  65609. set: function (camera) {
  65610. this._camera = camera;
  65611. if (this._camera != null && !this._camera.rotationQuaternion) {
  65612. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  65613. }
  65614. },
  65615. enumerable: true,
  65616. configurable: true
  65617. });
  65618. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  65619. window.addEventListener("orientationchange", this._orientationChanged);
  65620. window.addEventListener("deviceorientation", this._deviceOrientation);
  65621. //In certain cases, the attach control is called AFTER orientation was changed,
  65622. //So this is needed.
  65623. this._orientationChanged();
  65624. };
  65625. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  65626. window.removeEventListener("orientationchange", this._orientationChanged);
  65627. window.removeEventListener("deviceorientation", this._deviceOrientation);
  65628. };
  65629. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  65630. //if no device orientation provided, don't update the rotation.
  65631. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  65632. if (!this._alpha)
  65633. return;
  65634. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  65635. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  65636. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  65637. //Mirror on XY Plane
  65638. this._camera.rotationQuaternion.z *= -1;
  65639. this._camera.rotationQuaternion.w *= -1;
  65640. };
  65641. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  65642. return "FreeCameraDeviceOrientationInput";
  65643. };
  65644. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  65645. return "deviceOrientation";
  65646. };
  65647. return FreeCameraDeviceOrientationInput;
  65648. }());
  65649. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  65650. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  65651. })(BABYLON || (BABYLON = {}));
  65652. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  65653. var BABYLON;
  65654. (function (BABYLON) {
  65655. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  65656. function ArcRotateCameraVRDeviceOrientationInput() {
  65657. this.alphaCorrection = 1;
  65658. this.betaCorrection = 1;
  65659. this.gammaCorrection = 1;
  65660. this._alpha = 0;
  65661. this._beta = 0;
  65662. this._gamma = 0;
  65663. this._dirty = false;
  65664. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  65665. }
  65666. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  65667. this.camera.attachControl(element, noPreventDefault);
  65668. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  65669. };
  65670. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  65671. var camera = this.camera;
  65672. this._alpha = +evt.alpha | 0;
  65673. this._beta = +evt.beta | 0;
  65674. this._gamma = +evt.gamma | 0;
  65675. this._dirty = true;
  65676. };
  65677. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  65678. if (this._dirty) {
  65679. this._dirty = false;
  65680. if (this._gamma < 0) {
  65681. this._gamma = 180 + this._gamma;
  65682. }
  65683. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  65684. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  65685. }
  65686. };
  65687. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  65688. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  65689. };
  65690. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  65691. return "ArcRotateCameraVRDeviceOrientationInput";
  65692. };
  65693. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  65694. return "VRDeviceOrientation";
  65695. };
  65696. return ArcRotateCameraVRDeviceOrientationInput;
  65697. }());
  65698. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  65699. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  65700. })(BABYLON || (BABYLON = {}));
  65701. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  65702. var BABYLON;
  65703. (function (BABYLON) {
  65704. var VRCameraMetrics = (function () {
  65705. function VRCameraMetrics() {
  65706. this.compensateDistortion = true;
  65707. }
  65708. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  65709. get: function () {
  65710. return this.hResolution / (2 * this.vResolution);
  65711. },
  65712. enumerable: true,
  65713. configurable: true
  65714. });
  65715. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  65716. get: function () {
  65717. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  65718. },
  65719. enumerable: true,
  65720. configurable: true
  65721. });
  65722. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  65723. get: function () {
  65724. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  65725. var h = (4 * meters) / this.hScreenSize;
  65726. return BABYLON.Matrix.Translation(h, 0, 0);
  65727. },
  65728. enumerable: true,
  65729. configurable: true
  65730. });
  65731. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  65732. get: function () {
  65733. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  65734. var h = (4 * meters) / this.hScreenSize;
  65735. return BABYLON.Matrix.Translation(-h, 0, 0);
  65736. },
  65737. enumerable: true,
  65738. configurable: true
  65739. });
  65740. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  65741. get: function () {
  65742. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  65743. },
  65744. enumerable: true,
  65745. configurable: true
  65746. });
  65747. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  65748. get: function () {
  65749. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  65750. },
  65751. enumerable: true,
  65752. configurable: true
  65753. });
  65754. VRCameraMetrics.GetDefault = function () {
  65755. var result = new VRCameraMetrics();
  65756. result.hResolution = 1280;
  65757. result.vResolution = 800;
  65758. result.hScreenSize = 0.149759993;
  65759. result.vScreenSize = 0.0935999975;
  65760. result.vScreenCenter = 0.0467999987;
  65761. result.eyeToScreenDistance = 0.0410000011;
  65762. result.lensSeparationDistance = 0.0635000020;
  65763. result.interpupillaryDistance = 0.0640000030;
  65764. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  65765. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  65766. result.postProcessScaleFactor = 1.714605507808412;
  65767. result.lensCenterOffset = 0.151976421;
  65768. return result;
  65769. };
  65770. return VRCameraMetrics;
  65771. }());
  65772. BABYLON.VRCameraMetrics = VRCameraMetrics;
  65773. })(BABYLON || (BABYLON = {}));
  65774. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  65775. var BABYLON;
  65776. (function (BABYLON) {
  65777. var WebVRFreeCamera = (function (_super) {
  65778. __extends(WebVRFreeCamera, _super);
  65779. function WebVRFreeCamera(name, position, scene, webVROptions) {
  65780. if (webVROptions === void 0) { webVROptions = {}; }
  65781. var _this = _super.call(this, name, position, scene) || this;
  65782. _this.webVROptions = webVROptions;
  65783. _this._vrDevice = null;
  65784. _this.rawPose = null;
  65785. _this._vrEnabled = false;
  65786. _this._specsVersion = 1.1;
  65787. _this._attached = false;
  65788. _this._positionOffset = BABYLON.Vector3.Zero();
  65789. _this._descendants = [];
  65790. _this.devicePosition = BABYLON.Vector3.Zero();
  65791. _this.deviceScaleFactor = 1;
  65792. _this.controllers = [];
  65793. _this.onControllersAttachedObservable = new BABYLON.Observable();
  65794. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  65795. _this.minZ = 0.1;
  65796. //legacy support - the compensation boolean was removed.
  65797. if (arguments.length === 5) {
  65798. _this.webVROptions = arguments[4];
  65799. }
  65800. // default webVR options
  65801. if (_this.webVROptions.trackPosition == undefined) {
  65802. _this.webVROptions.trackPosition = true;
  65803. }
  65804. if (_this.webVROptions.controllerMeshes == undefined) {
  65805. _this.webVROptions.controllerMeshes = true;
  65806. }
  65807. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  65808. _this.webVROptions.defaultLightingOnControllers = true;
  65809. }
  65810. _this.rotationQuaternion = new BABYLON.Quaternion();
  65811. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  65812. if (_this.webVROptions && _this.webVROptions.positionScale) {
  65813. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  65814. }
  65815. //enable VR
  65816. _this.getEngine().initWebVR();
  65817. //check specs version
  65818. if (!window.VRFrameData) {
  65819. _this._specsVersion = 1.0;
  65820. _this._frameData = {};
  65821. }
  65822. else {
  65823. _this._frameData = new VRFrameData();
  65824. }
  65825. _this.getEngine().getVRDevice(_this.webVROptions.displayName, function (device) {
  65826. if (!device) {
  65827. return;
  65828. }
  65829. _this._vrEnabled = true;
  65830. _this._vrDevice = device;
  65831. //reset the rig parameters.
  65832. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  65833. if (_this._attached) {
  65834. _this.getEngine().enableVR(_this._vrDevice);
  65835. }
  65836. });
  65837. /**
  65838. * The idea behind the following lines:
  65839. * objects that have the camera as parent should actually have the rig cameras as a parent.
  65840. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  65841. * the second will not show it correctly.
  65842. *
  65843. * To solve this - each object that has the camera as parent will be added to a protected array.
  65844. * When the rig camera renders, it will take this array and set all of those to be its children.
  65845. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  65846. * Amazing!
  65847. */
  65848. scene.onBeforeCameraRenderObservable.add(function (camera) {
  65849. if (camera.parent === _this && _this.rigParenting) {
  65850. _this._descendants = _this.getDescendants(true, function (n) {
  65851. // don't take the cameras or the controllers!
  65852. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  65853. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  65854. return !isController && !isRigCamera;
  65855. });
  65856. _this._descendants.forEach(function (node) {
  65857. node.parent = camera;
  65858. });
  65859. }
  65860. });
  65861. scene.onAfterCameraRenderObservable.add(function (camera) {
  65862. if (camera.parent === _this && _this.rigParenting) {
  65863. _this._descendants.forEach(function (node) {
  65864. node.parent = _this;
  65865. });
  65866. }
  65867. });
  65868. return _this;
  65869. }
  65870. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  65871. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  65872. var gp = _a[_i];
  65873. if (gp.hand === name) {
  65874. return gp;
  65875. }
  65876. }
  65877. return undefined;
  65878. };
  65879. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  65880. get: function () {
  65881. if (!this._leftController) {
  65882. this._leftController = this.getControllerByName("left");
  65883. }
  65884. return this._leftController;
  65885. },
  65886. enumerable: true,
  65887. configurable: true
  65888. });
  65889. ;
  65890. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  65891. get: function () {
  65892. if (!this._rightController) {
  65893. this._rightController = this.getControllerByName("right");
  65894. }
  65895. return this._rightController;
  65896. },
  65897. enumerable: true,
  65898. configurable: true
  65899. });
  65900. ;
  65901. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  65902. if (length === void 0) { length = 100; }
  65903. if (this.leftCamera) {
  65904. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  65905. }
  65906. else {
  65907. return _super.prototype.getForwardRay.call(this, length);
  65908. }
  65909. };
  65910. WebVRFreeCamera.prototype._checkInputs = function () {
  65911. if (this._vrEnabled) {
  65912. if (this._specsVersion === 1.1) {
  65913. this._vrDevice.getFrameData(this._frameData);
  65914. }
  65915. else {
  65916. //backwards comp
  65917. var pose = this._vrDevice.getPose();
  65918. this._frameData.pose = pose;
  65919. }
  65920. this.updateFromDevice(this._frameData.pose);
  65921. }
  65922. _super.prototype._checkInputs.call(this);
  65923. };
  65924. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  65925. if (poseData && poseData.orientation) {
  65926. this.rawPose = poseData;
  65927. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  65928. if (this.getScene().useRightHandedSystem) {
  65929. this.deviceRotationQuaternion.z *= -1;
  65930. this.deviceRotationQuaternion.w *= -1;
  65931. }
  65932. if (this.webVROptions.trackPosition && this.rawPose.position) {
  65933. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  65934. if (this.getScene().useRightHandedSystem) {
  65935. this.devicePosition.z *= -1;
  65936. }
  65937. }
  65938. }
  65939. };
  65940. /**
  65941. * WebVR's attach control will start broadcasting frames to the device.
  65942. * Note that in certain browsers (chrome for example) this function must be called
  65943. * within a user-interaction callback. Example:
  65944. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  65945. *
  65946. * @param {HTMLElement} element
  65947. * @param {boolean} [noPreventDefault]
  65948. *
  65949. * @memberOf WebVRFreeCamera
  65950. */
  65951. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  65952. _super.prototype.attachControl.call(this, element, noPreventDefault);
  65953. this._attached = true;
  65954. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  65955. if (this._vrEnabled) {
  65956. this.getEngine().enableVR(this._vrDevice);
  65957. }
  65958. // try to attach the controllers, if found.
  65959. this.initControllers();
  65960. };
  65961. WebVRFreeCamera.prototype.detachControl = function (element) {
  65962. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65963. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65964. _super.prototype.detachControl.call(this, element);
  65965. this._vrEnabled = false;
  65966. this._attached = false;
  65967. this.getEngine().disableVR();
  65968. };
  65969. WebVRFreeCamera.prototype.getClassName = function () {
  65970. return "WebVRFreeCamera";
  65971. };
  65972. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  65973. //uses the vrDisplay's "resetPose()".
  65974. //pitch and roll won't be affected.
  65975. this._vrDevice.resetPose();
  65976. };
  65977. WebVRFreeCamera.prototype._updateRigCameras = function () {
  65978. var camLeft = this._rigCameras[0];
  65979. var camRight = this._rigCameras[1];
  65980. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  65981. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  65982. camLeft.position.copyFrom(this.devicePosition);
  65983. camRight.position.copyFrom(this.devicePosition);
  65984. };
  65985. /**
  65986. * This function is called by the two RIG cameras.
  65987. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  65988. */
  65989. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  65990. var _this = this;
  65991. //WebVR 1.0
  65992. if (this._cameraRigParams["specs"] === 1.0) {
  65993. this._updateCameraRotationMatrix();
  65994. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  65995. // Computing target and final matrix
  65996. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  65997. if (this.getScene().useRightHandedSystem) {
  65998. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  65999. }
  66000. else {
  66001. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  66002. }
  66003. //now move the eye in the right direction
  66004. var eyeParams = this._cameraRigParams["eyeParameters"];
  66005. var offset = eyeParams.offset;
  66006. // it will actually always be 0, but just in case
  66007. if (this.getScene().useRightHandedSystem) {
  66008. offset[2] *= -1;
  66009. }
  66010. BABYLON.Matrix.TranslationToRef(-offset[0], offset[1], -offset[2], BABYLON.Tmp.Matrix[0]);
  66011. this._webvrViewMatrix.multiplyToRef(BABYLON.Tmp.Matrix[0], this._webvrViewMatrix);
  66012. }
  66013. else {
  66014. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  66015. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  66016. if (!this.getScene().useRightHandedSystem) {
  66017. [2, 6, 8, 9, 14].forEach(function (num) {
  66018. _this._webvrViewMatrix.m[num] *= -1;
  66019. });
  66020. }
  66021. // update the camera rotation matrix
  66022. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  66023. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  66024. // Computing target and final matrix
  66025. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  66026. }
  66027. var parentCamera = this._cameraRigParams["parentCamera"];
  66028. // should the view matrix be updated with scale and position offset?
  66029. if (parentCamera.deviceScaleFactor !== 1) {
  66030. this._webvrViewMatrix.invert();
  66031. // scale the position, if set
  66032. if (parentCamera.deviceScaleFactor) {
  66033. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  66034. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  66035. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  66036. }
  66037. this._webvrViewMatrix.invert();
  66038. }
  66039. return this._webvrViewMatrix;
  66040. };
  66041. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  66042. var _this = this;
  66043. if (this._cameraRigParams["specs"] === 1.0) {
  66044. var eyeParams = this._cameraRigParams["eyeParameters"];
  66045. // deprecated!!
  66046. BABYLON.Matrix.PerspectiveFovWebVRToRef(eyeParams.fieldOfView, this.minZ, this.maxZ, this._projectionMatrix, this.getScene().useRightHandedSystem);
  66047. }
  66048. else {
  66049. var parentCamera = this.parent;
  66050. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  66051. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  66052. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  66053. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  66054. //babylon compatible matrix
  66055. if (!this.getScene().useRightHandedSystem) {
  66056. [8, 9, 10, 11].forEach(function (num) {
  66057. _this._projectionMatrix.m[num] *= -1;
  66058. });
  66059. }
  66060. }
  66061. return this._projectionMatrix;
  66062. };
  66063. WebVRFreeCamera.prototype.initControllers = function () {
  66064. var _this = this;
  66065. this.controllers = [];
  66066. var manager = this.getScene().gamepadManager;
  66067. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  66068. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  66069. var webVrController = gamepad;
  66070. var index = _this.controllers.indexOf(webVrController);
  66071. if (index === -1) {
  66072. // we are good
  66073. return;
  66074. }
  66075. _this.controllers.splice(index, 1);
  66076. }
  66077. });
  66078. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  66079. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  66080. var webVrController = gamepad;
  66081. if (_this.webVROptions.controllerMeshes) {
  66082. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  66083. if (_this.webVROptions.defaultLightingOnControllers) {
  66084. if (!_this._lightOnControllers) {
  66085. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  66086. }
  66087. var activateLightOnSubMeshes_1 = function (mesh, light) {
  66088. var children = mesh.getChildren();
  66089. if (children.length !== 0) {
  66090. children.forEach(function (mesh) {
  66091. light.includedOnlyMeshes.push(mesh);
  66092. activateLightOnSubMeshes_1(mesh, light);
  66093. });
  66094. }
  66095. };
  66096. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  66097. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  66098. }
  66099. });
  66100. }
  66101. webVrController.attachToPoseControlledCamera(_this);
  66102. // since this is async - sanity check. Is the controller already stored?
  66103. if (_this.controllers.indexOf(webVrController) === -1) {
  66104. //add to the controllers array
  66105. _this.controllers.push(webVrController);
  66106. //did we find enough controllers? Great! let the developer know.
  66107. if (_this.controllers.length >= 2) {
  66108. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  66109. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  66110. // So we're overriding setting left & right manually to be sure
  66111. var firstViveWandDetected = false;
  66112. for (var i = 0; i < _this.controllers.length; i++) {
  66113. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  66114. if (!firstViveWandDetected) {
  66115. firstViveWandDetected = true;
  66116. _this.controllers[i].hand = "left";
  66117. }
  66118. else {
  66119. _this.controllers[i].hand = "right";
  66120. }
  66121. }
  66122. }
  66123. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  66124. }
  66125. }
  66126. }
  66127. });
  66128. };
  66129. return WebVRFreeCamera;
  66130. }(BABYLON.FreeCamera));
  66131. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  66132. })(BABYLON || (BABYLON = {}));
  66133. //# sourceMappingURL=babylon.webVRCamera.js.map
  66134. /// <reference path="babylon.freeCamera.ts" />
  66135. var BABYLON;
  66136. (function (BABYLON) {
  66137. // We're mainly based on the logic defined into the FreeCamera code
  66138. var DeviceOrientationCamera = (function (_super) {
  66139. __extends(DeviceOrientationCamera, _super);
  66140. function DeviceOrientationCamera(name, position, scene) {
  66141. var _this = _super.call(this, name, position, scene) || this;
  66142. _this._quaternionCache = new BABYLON.Quaternion();
  66143. _this.inputs.addDeviceOrientation();
  66144. return _this;
  66145. }
  66146. DeviceOrientationCamera.prototype.getClassName = function () {
  66147. return "DeviceOrientationCamera";
  66148. };
  66149. DeviceOrientationCamera.prototype._checkInputs = function () {
  66150. _super.prototype._checkInputs.call(this);
  66151. this._quaternionCache.copyFrom(this.rotationQuaternion);
  66152. if (this._initialQuaternion) {
  66153. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  66154. }
  66155. };
  66156. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  66157. var _this = this;
  66158. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  66159. //can only work if this camera has a rotation quaternion already.
  66160. if (!this.rotationQuaternion)
  66161. return;
  66162. if (!this._initialQuaternion) {
  66163. this._initialQuaternion = new BABYLON.Quaternion();
  66164. }
  66165. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  66166. ['x', 'y', 'z'].forEach(function (axisName) {
  66167. if (!axis[axisName]) {
  66168. _this._initialQuaternion[axisName] = 0;
  66169. }
  66170. else {
  66171. _this._initialQuaternion[axisName] *= -1;
  66172. }
  66173. });
  66174. this._initialQuaternion.normalize();
  66175. //force rotation update
  66176. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  66177. };
  66178. return DeviceOrientationCamera;
  66179. }(BABYLON.FreeCamera));
  66180. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  66181. })(BABYLON || (BABYLON = {}));
  66182. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  66183. var BABYLON;
  66184. (function (BABYLON) {
  66185. var VRDeviceOrientationFreeCamera = (function (_super) {
  66186. __extends(VRDeviceOrientationFreeCamera, _super);
  66187. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  66188. if (compensateDistortion === void 0) { compensateDistortion = true; }
  66189. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  66190. var _this = _super.call(this, name, position, scene) || this;
  66191. vrCameraMetrics.compensateDistortion = compensateDistortion;
  66192. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  66193. return _this;
  66194. }
  66195. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  66196. return "VRDeviceOrientationFreeCamera";
  66197. };
  66198. return VRDeviceOrientationFreeCamera;
  66199. }(BABYLON.DeviceOrientationCamera));
  66200. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  66201. var VRDeviceOrientationGamepadCamera = (function (_super) {
  66202. __extends(VRDeviceOrientationGamepadCamera, _super);
  66203. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  66204. if (compensateDistortion === void 0) { compensateDistortion = true; }
  66205. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  66206. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  66207. _this.inputs.addGamepad();
  66208. return _this;
  66209. }
  66210. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  66211. return "VRDeviceOrientationGamepadCamera";
  66212. };
  66213. return VRDeviceOrientationGamepadCamera;
  66214. }(VRDeviceOrientationFreeCamera));
  66215. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  66216. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  66217. __extends(VRDeviceOrientationArcRotateCamera, _super);
  66218. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  66219. if (compensateDistortion === void 0) { compensateDistortion = true; }
  66220. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  66221. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  66222. vrCameraMetrics.compensateDistortion = compensateDistortion;
  66223. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  66224. _this.inputs.addVRDeviceOrientation();
  66225. return _this;
  66226. }
  66227. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  66228. return "VRDeviceOrientationArcRotateCamera";
  66229. };
  66230. return VRDeviceOrientationArcRotateCamera;
  66231. }(BABYLON.ArcRotateCamera));
  66232. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  66233. })(BABYLON || (BABYLON = {}));
  66234. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  66235. /// <reference path="babylon.freeCamera.ts" />
  66236. /// <reference path="babylon.arcRotateCamera.ts" />
  66237. /// <reference path="babylon.gamepadCamera.ts" />
  66238. /// <reference path="babylon.universalCamera.ts" />
  66239. var BABYLON;
  66240. (function (BABYLON) {
  66241. var AnaglyphFreeCamera = (function (_super) {
  66242. __extends(AnaglyphFreeCamera, _super);
  66243. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  66244. var _this = _super.call(this, name, position, scene) || this;
  66245. _this.interaxialDistance = interaxialDistance;
  66246. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  66247. return _this;
  66248. }
  66249. AnaglyphFreeCamera.prototype.getClassName = function () {
  66250. return "AnaglyphFreeCamera";
  66251. };
  66252. return AnaglyphFreeCamera;
  66253. }(BABYLON.FreeCamera));
  66254. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  66255. var AnaglyphArcRotateCamera = (function (_super) {
  66256. __extends(AnaglyphArcRotateCamera, _super);
  66257. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  66258. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  66259. _this.interaxialDistance = interaxialDistance;
  66260. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  66261. return _this;
  66262. }
  66263. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  66264. return "AnaglyphArcRotateCamera";
  66265. };
  66266. return AnaglyphArcRotateCamera;
  66267. }(BABYLON.ArcRotateCamera));
  66268. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  66269. var AnaglyphGamepadCamera = (function (_super) {
  66270. __extends(AnaglyphGamepadCamera, _super);
  66271. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  66272. var _this = _super.call(this, name, position, scene) || this;
  66273. _this.interaxialDistance = interaxialDistance;
  66274. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  66275. return _this;
  66276. }
  66277. AnaglyphGamepadCamera.prototype.getClassName = function () {
  66278. return "AnaglyphGamepadCamera";
  66279. };
  66280. return AnaglyphGamepadCamera;
  66281. }(BABYLON.GamepadCamera));
  66282. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  66283. var AnaglyphUniversalCamera = (function (_super) {
  66284. __extends(AnaglyphUniversalCamera, _super);
  66285. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  66286. var _this = _super.call(this, name, position, scene) || this;
  66287. _this.interaxialDistance = interaxialDistance;
  66288. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  66289. return _this;
  66290. }
  66291. AnaglyphUniversalCamera.prototype.getClassName = function () {
  66292. return "AnaglyphUniversalCamera";
  66293. };
  66294. return AnaglyphUniversalCamera;
  66295. }(BABYLON.UniversalCamera));
  66296. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  66297. var StereoscopicFreeCamera = (function (_super) {
  66298. __extends(StereoscopicFreeCamera, _super);
  66299. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  66300. var _this = _super.call(this, name, position, scene) || this;
  66301. _this.interaxialDistance = interaxialDistance;
  66302. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  66303. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  66304. return _this;
  66305. }
  66306. StereoscopicFreeCamera.prototype.getClassName = function () {
  66307. return "StereoscopicFreeCamera";
  66308. };
  66309. return StereoscopicFreeCamera;
  66310. }(BABYLON.FreeCamera));
  66311. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  66312. var StereoscopicArcRotateCamera = (function (_super) {
  66313. __extends(StereoscopicArcRotateCamera, _super);
  66314. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  66315. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  66316. _this.interaxialDistance = interaxialDistance;
  66317. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  66318. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  66319. return _this;
  66320. }
  66321. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  66322. return "StereoscopicArcRotateCamera";
  66323. };
  66324. return StereoscopicArcRotateCamera;
  66325. }(BABYLON.ArcRotateCamera));
  66326. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  66327. var StereoscopicGamepadCamera = (function (_super) {
  66328. __extends(StereoscopicGamepadCamera, _super);
  66329. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  66330. var _this = _super.call(this, name, position, scene) || this;
  66331. _this.interaxialDistance = interaxialDistance;
  66332. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  66333. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  66334. return _this;
  66335. }
  66336. StereoscopicGamepadCamera.prototype.getClassName = function () {
  66337. return "StereoscopicGamepadCamera";
  66338. };
  66339. return StereoscopicGamepadCamera;
  66340. }(BABYLON.GamepadCamera));
  66341. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  66342. var StereoscopicUniversalCamera = (function (_super) {
  66343. __extends(StereoscopicUniversalCamera, _super);
  66344. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  66345. var _this = _super.call(this, name, position, scene) || this;
  66346. _this.interaxialDistance = interaxialDistance;
  66347. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  66348. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  66349. return _this;
  66350. }
  66351. StereoscopicUniversalCamera.prototype.getClassName = function () {
  66352. return "StereoscopicUniversalCamera";
  66353. };
  66354. return StereoscopicUniversalCamera;
  66355. }(BABYLON.UniversalCamera));
  66356. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  66357. })(BABYLON || (BABYLON = {}));
  66358. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  66359. var BABYLON;
  66360. (function (BABYLON) {
  66361. var VRExperienceHelper = (function () {
  66362. function VRExperienceHelper(scene, webVROptions) {
  66363. if (webVROptions === void 0) { webVROptions = {}; }
  66364. var _this = this;
  66365. this.webVROptions = webVROptions;
  66366. this._webVRsupportedAndReady = false;
  66367. this._isInVRMode = false;
  66368. this._scene = scene;
  66369. if (!this._scene.activeCamera) {
  66370. this._scene.activeCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  66371. }
  66372. else {
  66373. var newCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  66374. if (scene.activeCamera.rotation) {
  66375. newCamera.rotation = scene.activeCamera.rotation.clone();
  66376. }
  66377. newCamera.minZ = this._scene.activeCamera.minZ;
  66378. newCamera.maxZ = this._scene.activeCamera.maxZ;
  66379. this._scene.activeCamera = newCamera;
  66380. }
  66381. this._position = this._scene.activeCamera.position;
  66382. this._canvas = scene.getEngine().getRenderingCanvas();
  66383. this._scene.activeCamera.attachControl(this._canvas);
  66384. this._btnVR = document.createElement("BUTTON");
  66385. this._btnVR.className = "babylonVRicon";
  66386. this._btnVR.id = "babylonVRiconbtn";
  66387. this._btnVR.title = "Click to switch to VR";
  66388. 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) }";
  66389. var style = document.createElement('style');
  66390. style.appendChild(document.createTextNode(css));
  66391. document.getElementsByTagName('head')[0].appendChild(style);
  66392. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  66393. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  66394. window.addEventListener("resize", function () {
  66395. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  66396. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  66397. });
  66398. // Exiting VR mode using 'ESC' key on desktop
  66399. document.addEventListener("keydown", function (event) {
  66400. if (event.keyCode === 27 && _this._isInVRMode) {
  66401. _this.exitVR();
  66402. }
  66403. });
  66404. // Exiting VR mode double tapping the touch screen
  66405. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  66406. if (_this._isInVRMode) {
  66407. _this.exitVR();
  66408. }
  66409. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  66410. if (navigator.getVRDisplays) {
  66411. navigator.getVRDisplays().then(function (headsets) {
  66412. if (headsets.length > 0) {
  66413. scene.getEngine().initWebVR();
  66414. _this._webVRsupportedAndReady = true;
  66415. }
  66416. document.body.appendChild(_this._btnVR);
  66417. });
  66418. }
  66419. else {
  66420. document.body.appendChild(this._btnVR);
  66421. }
  66422. this._btnVR.addEventListener("click", function () {
  66423. _this.enterVR();
  66424. });
  66425. }
  66426. VRExperienceHelper.prototype.enterVR = function () {
  66427. this._scene.activeCamera.dispose();
  66428. // If WebVR is supported and a headset is connected
  66429. if (this._webVRsupportedAndReady) {
  66430. this._scene.activeCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene);
  66431. }
  66432. else {
  66433. this._scene.activeCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  66434. this._scene.getEngine().switchFullscreen(true);
  66435. }
  66436. this._scene.activeCamera.attachControl(this._canvas);
  66437. this._isInVRMode = true;
  66438. this._btnVR.style.display = "none";
  66439. };
  66440. VRExperienceHelper.prototype.exitVR = function () {
  66441. if (this._webVRsupportedAndReady) {
  66442. this._scene.getEngine().disableVR();
  66443. }
  66444. if (this._scene.activeCamera) {
  66445. this._position = this._scene.activeCamera.position;
  66446. this._scene.activeCamera.dispose();
  66447. }
  66448. this._scene.activeCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position, this._scene);
  66449. this._scene.activeCamera.attachControl(this._canvas);
  66450. this._isInVRMode = false;
  66451. this._btnVR.style.display = "";
  66452. };
  66453. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  66454. get: function () {
  66455. return this._position;
  66456. },
  66457. set: function (value) {
  66458. this._position = value;
  66459. this._scene.activeCamera.position = value;
  66460. },
  66461. enumerable: true,
  66462. configurable: true
  66463. });
  66464. VRExperienceHelper.prototype.dispose = function () {
  66465. if (this._isInVRMode) {
  66466. this.exitVR();
  66467. }
  66468. document.body.removeChild(this._btnVR);
  66469. };
  66470. VRExperienceHelper.prototype.getClassName = function () {
  66471. return "VRExperienceHelper";
  66472. };
  66473. return VRExperienceHelper;
  66474. }());
  66475. BABYLON.VRExperienceHelper = VRExperienceHelper;
  66476. })(BABYLON || (BABYLON = {}));
  66477. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  66478. // Mainly based on these 2 articles :
  66479. // 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
  66480. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  66481. var BABYLON;
  66482. (function (BABYLON) {
  66483. var JoystickAxis;
  66484. (function (JoystickAxis) {
  66485. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  66486. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  66487. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  66488. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  66489. var VirtualJoystick = (function () {
  66490. function VirtualJoystick(leftJoystick) {
  66491. var _this = this;
  66492. if (leftJoystick) {
  66493. this._leftJoystick = true;
  66494. }
  66495. else {
  66496. this._leftJoystick = false;
  66497. }
  66498. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  66499. VirtualJoystick._globalJoystickIndex++;
  66500. // By default left & right arrow keys are moving the X
  66501. // and up & down keys are moving the Y
  66502. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  66503. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  66504. this.reverseLeftRight = false;
  66505. this.reverseUpDown = false;
  66506. // collections of pointers
  66507. this._touches = new BABYLON.StringDictionary();
  66508. this.deltaPosition = BABYLON.Vector3.Zero();
  66509. this._joystickSensibility = 25;
  66510. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  66511. this._rotationSpeed = 25;
  66512. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  66513. this._rotateOnAxisRelativeToMesh = false;
  66514. this._onResize = function (evt) {
  66515. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  66516. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  66517. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  66518. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  66519. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  66520. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  66521. };
  66522. // injecting a canvas element on top of the canvas 3D game
  66523. if (!VirtualJoystick.vjCanvas) {
  66524. window.addEventListener("resize", this._onResize, false);
  66525. VirtualJoystick.vjCanvas = document.createElement("canvas");
  66526. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  66527. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  66528. VirtualJoystick.vjCanvas.width = window.innerWidth;
  66529. VirtualJoystick.vjCanvas.height = window.innerHeight;
  66530. VirtualJoystick.vjCanvas.style.width = "100%";
  66531. VirtualJoystick.vjCanvas.style.height = "100%";
  66532. VirtualJoystick.vjCanvas.style.position = "absolute";
  66533. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  66534. VirtualJoystick.vjCanvas.style.top = "0px";
  66535. VirtualJoystick.vjCanvas.style.left = "0px";
  66536. VirtualJoystick.vjCanvas.style.zIndex = "5";
  66537. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  66538. // Support for jQuery PEP polyfill
  66539. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  66540. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  66541. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  66542. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  66543. document.body.appendChild(VirtualJoystick.vjCanvas);
  66544. }
  66545. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  66546. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  66547. this.pressed = false;
  66548. // default joystick color
  66549. this._joystickColor = "cyan";
  66550. this._joystickPointerID = -1;
  66551. // current joystick position
  66552. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  66553. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  66554. // origin joystick position
  66555. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  66556. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  66557. this._onPointerDownHandlerRef = function (evt) {
  66558. _this._onPointerDown(evt);
  66559. };
  66560. this._onPointerMoveHandlerRef = function (evt) {
  66561. _this._onPointerMove(evt);
  66562. };
  66563. this._onPointerOutHandlerRef = function (evt) {
  66564. _this._onPointerUp(evt);
  66565. };
  66566. this._onPointerUpHandlerRef = function (evt) {
  66567. _this._onPointerUp(evt);
  66568. };
  66569. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  66570. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  66571. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  66572. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  66573. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  66574. evt.preventDefault(); // Disables system menu
  66575. }, false);
  66576. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  66577. }
  66578. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  66579. this._joystickSensibility = newJoystickSensibility;
  66580. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  66581. };
  66582. VirtualJoystick.prototype._onPointerDown = function (e) {
  66583. var positionOnScreenCondition;
  66584. e.preventDefault();
  66585. if (this._leftJoystick === true) {
  66586. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  66587. }
  66588. else {
  66589. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  66590. }
  66591. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  66592. // First contact will be dedicated to the virtual joystick
  66593. this._joystickPointerID = e.pointerId;
  66594. this._joystickPointerStartPos.x = e.clientX;
  66595. this._joystickPointerStartPos.y = e.clientY;
  66596. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  66597. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  66598. this._deltaJoystickVector.x = 0;
  66599. this._deltaJoystickVector.y = 0;
  66600. this.pressed = true;
  66601. this._touches.add(e.pointerId.toString(), e);
  66602. }
  66603. else {
  66604. // You can only trigger the action buttons with a joystick declared
  66605. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  66606. this._action();
  66607. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  66608. }
  66609. }
  66610. };
  66611. VirtualJoystick.prototype._onPointerMove = function (e) {
  66612. // If the current pointer is the one associated to the joystick (first touch contact)
  66613. if (this._joystickPointerID == e.pointerId) {
  66614. this._joystickPointerPos.x = e.clientX;
  66615. this._joystickPointerPos.y = e.clientY;
  66616. this._deltaJoystickVector = this._joystickPointerPos.clone();
  66617. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  66618. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  66619. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  66620. switch (this._axisTargetedByLeftAndRight) {
  66621. case JoystickAxis.X:
  66622. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  66623. break;
  66624. case JoystickAxis.Y:
  66625. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  66626. break;
  66627. case JoystickAxis.Z:
  66628. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  66629. break;
  66630. }
  66631. var directionUpDown = this.reverseUpDown ? 1 : -1;
  66632. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  66633. switch (this._axisTargetedByUpAndDown) {
  66634. case JoystickAxis.X:
  66635. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  66636. break;
  66637. case JoystickAxis.Y:
  66638. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  66639. break;
  66640. case JoystickAxis.Z:
  66641. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  66642. break;
  66643. }
  66644. }
  66645. else {
  66646. var data = this._touches.get(e.pointerId.toString());
  66647. if (data) {
  66648. data.x = e.clientX;
  66649. data.y = e.clientY;
  66650. }
  66651. }
  66652. };
  66653. VirtualJoystick.prototype._onPointerUp = function (e) {
  66654. if (this._joystickPointerID == e.pointerId) {
  66655. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  66656. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  66657. this._joystickPointerID = -1;
  66658. this.pressed = false;
  66659. }
  66660. else {
  66661. var touch = this._touches.get(e.pointerId.toString());
  66662. if (touch) {
  66663. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  66664. }
  66665. }
  66666. this._deltaJoystickVector.x = 0;
  66667. this._deltaJoystickVector.y = 0;
  66668. this._touches.remove(e.pointerId.toString());
  66669. };
  66670. /**
  66671. * Change the color of the virtual joystick
  66672. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  66673. */
  66674. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  66675. this._joystickColor = newColor;
  66676. };
  66677. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  66678. this._action = action;
  66679. };
  66680. // Define which axis you'd like to control for left & right
  66681. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  66682. switch (axis) {
  66683. case JoystickAxis.X:
  66684. case JoystickAxis.Y:
  66685. case JoystickAxis.Z:
  66686. this._axisTargetedByLeftAndRight = axis;
  66687. break;
  66688. default:
  66689. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  66690. break;
  66691. }
  66692. };
  66693. // Define which axis you'd like to control for up & down
  66694. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  66695. switch (axis) {
  66696. case JoystickAxis.X:
  66697. case JoystickAxis.Y:
  66698. case JoystickAxis.Z:
  66699. this._axisTargetedByUpAndDown = axis;
  66700. break;
  66701. default:
  66702. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  66703. break;
  66704. }
  66705. };
  66706. VirtualJoystick.prototype._clearCanvas = function () {
  66707. if (this._leftJoystick) {
  66708. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  66709. }
  66710. else {
  66711. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  66712. }
  66713. };
  66714. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  66715. var _this = this;
  66716. if (this.pressed) {
  66717. this._touches.forEach(function (key, touch) {
  66718. if (touch.pointerId === _this._joystickPointerID) {
  66719. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  66720. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  66721. VirtualJoystick.vjCanvasContext.beginPath();
  66722. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  66723. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  66724. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  66725. VirtualJoystick.vjCanvasContext.stroke();
  66726. VirtualJoystick.vjCanvasContext.closePath();
  66727. VirtualJoystick.vjCanvasContext.beginPath();
  66728. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  66729. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  66730. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  66731. VirtualJoystick.vjCanvasContext.stroke();
  66732. VirtualJoystick.vjCanvasContext.closePath();
  66733. VirtualJoystick.vjCanvasContext.beginPath();
  66734. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  66735. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  66736. VirtualJoystick.vjCanvasContext.stroke();
  66737. VirtualJoystick.vjCanvasContext.closePath();
  66738. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  66739. }
  66740. else {
  66741. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  66742. VirtualJoystick.vjCanvasContext.beginPath();
  66743. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  66744. VirtualJoystick.vjCanvasContext.beginPath();
  66745. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  66746. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  66747. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  66748. VirtualJoystick.vjCanvasContext.stroke();
  66749. VirtualJoystick.vjCanvasContext.closePath();
  66750. touch.prevX = touch.x;
  66751. touch.prevY = touch.y;
  66752. }
  66753. ;
  66754. });
  66755. }
  66756. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  66757. };
  66758. VirtualJoystick.prototype.releaseCanvas = function () {
  66759. if (VirtualJoystick.vjCanvas) {
  66760. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  66761. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  66762. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  66763. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  66764. window.removeEventListener("resize", this._onResize);
  66765. document.body.removeChild(VirtualJoystick.vjCanvas);
  66766. VirtualJoystick.vjCanvas = null;
  66767. }
  66768. };
  66769. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  66770. VirtualJoystick._globalJoystickIndex = 0;
  66771. return VirtualJoystick;
  66772. }());
  66773. BABYLON.VirtualJoystick = VirtualJoystick;
  66774. })(BABYLON || (BABYLON = {}));
  66775. //# sourceMappingURL=babylon.virtualJoystick.js.map
  66776. var BABYLON;
  66777. (function (BABYLON) {
  66778. // We're mainly based on the logic defined into the FreeCamera code
  66779. var VirtualJoysticksCamera = (function (_super) {
  66780. __extends(VirtualJoysticksCamera, _super);
  66781. function VirtualJoysticksCamera(name, position, scene) {
  66782. var _this = _super.call(this, name, position, scene) || this;
  66783. _this.inputs.addVirtualJoystick();
  66784. return _this;
  66785. }
  66786. VirtualJoysticksCamera.prototype.getClassName = function () {
  66787. return "VirtualJoysticksCamera";
  66788. };
  66789. return VirtualJoysticksCamera;
  66790. }(BABYLON.FreeCamera));
  66791. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  66792. })(BABYLON || (BABYLON = {}));
  66793. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  66794. var BABYLON;
  66795. (function (BABYLON) {
  66796. var FreeCameraVirtualJoystickInput = (function () {
  66797. function FreeCameraVirtualJoystickInput() {
  66798. }
  66799. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  66800. return this._leftjoystick;
  66801. };
  66802. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  66803. return this._rightjoystick;
  66804. };
  66805. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  66806. if (this._leftjoystick) {
  66807. var camera = this.camera;
  66808. var speed = camera._computeLocalCameraSpeed() * 50;
  66809. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  66810. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  66811. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  66812. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  66813. if (!this._leftjoystick.pressed) {
  66814. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  66815. }
  66816. if (!this._rightjoystick.pressed) {
  66817. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  66818. }
  66819. }
  66820. };
  66821. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  66822. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  66823. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  66824. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  66825. this._leftjoystick.setJoystickSensibility(0.15);
  66826. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  66827. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  66828. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  66829. this._rightjoystick.reverseUpDown = true;
  66830. this._rightjoystick.setJoystickSensibility(0.05);
  66831. this._rightjoystick.setJoystickColor("yellow");
  66832. };
  66833. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  66834. this._leftjoystick.releaseCanvas();
  66835. this._rightjoystick.releaseCanvas();
  66836. };
  66837. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  66838. return "FreeCameraVirtualJoystickInput";
  66839. };
  66840. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  66841. return "virtualJoystick";
  66842. };
  66843. return FreeCameraVirtualJoystickInput;
  66844. }());
  66845. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  66846. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  66847. })(BABYLON || (BABYLON = {}));
  66848. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  66849. var BABYLON;
  66850. (function (BABYLON) {
  66851. var SimplificationSettings = (function () {
  66852. function SimplificationSettings(quality, distance, optimizeMesh) {
  66853. this.quality = quality;
  66854. this.distance = distance;
  66855. this.optimizeMesh = optimizeMesh;
  66856. }
  66857. return SimplificationSettings;
  66858. }());
  66859. BABYLON.SimplificationSettings = SimplificationSettings;
  66860. var SimplificationQueue = (function () {
  66861. function SimplificationQueue() {
  66862. this.running = false;
  66863. this._simplificationArray = [];
  66864. }
  66865. SimplificationQueue.prototype.addTask = function (task) {
  66866. this._simplificationArray.push(task);
  66867. };
  66868. SimplificationQueue.prototype.executeNext = function () {
  66869. var task = this._simplificationArray.pop();
  66870. if (task) {
  66871. this.running = true;
  66872. this.runSimplification(task);
  66873. }
  66874. else {
  66875. this.running = false;
  66876. }
  66877. };
  66878. SimplificationQueue.prototype.runSimplification = function (task) {
  66879. var _this = this;
  66880. if (task.parallelProcessing) {
  66881. //parallel simplifier
  66882. task.settings.forEach(function (setting) {
  66883. var simplifier = _this.getSimplifier(task);
  66884. simplifier.simplify(setting, function (newMesh) {
  66885. task.mesh.addLODLevel(setting.distance, newMesh);
  66886. newMesh.isVisible = true;
  66887. //check if it is the last
  66888. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  66889. //all done, run the success callback.
  66890. task.successCallback();
  66891. }
  66892. _this.executeNext();
  66893. });
  66894. });
  66895. }
  66896. else {
  66897. //single simplifier.
  66898. var simplifier = this.getSimplifier(task);
  66899. var runDecimation = function (setting, callback) {
  66900. simplifier.simplify(setting, function (newMesh) {
  66901. task.mesh.addLODLevel(setting.distance, newMesh);
  66902. newMesh.isVisible = true;
  66903. //run the next quality level
  66904. callback();
  66905. });
  66906. };
  66907. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  66908. runDecimation(task.settings[loop.index], function () {
  66909. loop.executeNext();
  66910. });
  66911. }, function () {
  66912. //execution ended, run the success callback.
  66913. if (task.successCallback) {
  66914. task.successCallback();
  66915. }
  66916. _this.executeNext();
  66917. });
  66918. }
  66919. };
  66920. SimplificationQueue.prototype.getSimplifier = function (task) {
  66921. switch (task.simplificationType) {
  66922. case SimplificationType.QUADRATIC:
  66923. default:
  66924. return new QuadraticErrorSimplification(task.mesh);
  66925. }
  66926. };
  66927. return SimplificationQueue;
  66928. }());
  66929. BABYLON.SimplificationQueue = SimplificationQueue;
  66930. /**
  66931. * The implemented types of simplification.
  66932. * At the moment only Quadratic Error Decimation is implemented.
  66933. */
  66934. var SimplificationType;
  66935. (function (SimplificationType) {
  66936. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  66937. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  66938. var DecimationTriangle = (function () {
  66939. function DecimationTriangle(vertices) {
  66940. this.vertices = vertices;
  66941. this.error = new Array(4);
  66942. this.deleted = false;
  66943. this.isDirty = false;
  66944. this.deletePending = false;
  66945. this.borderFactor = 0;
  66946. }
  66947. return DecimationTriangle;
  66948. }());
  66949. BABYLON.DecimationTriangle = DecimationTriangle;
  66950. var DecimationVertex = (function () {
  66951. function DecimationVertex(position, id) {
  66952. this.position = position;
  66953. this.id = id;
  66954. this.isBorder = true;
  66955. this.q = new QuadraticMatrix();
  66956. this.triangleCount = 0;
  66957. this.triangleStart = 0;
  66958. this.originalOffsets = [];
  66959. }
  66960. DecimationVertex.prototype.updatePosition = function (newPosition) {
  66961. this.position.copyFrom(newPosition);
  66962. };
  66963. return DecimationVertex;
  66964. }());
  66965. BABYLON.DecimationVertex = DecimationVertex;
  66966. var QuadraticMatrix = (function () {
  66967. function QuadraticMatrix(data) {
  66968. this.data = new Array(10);
  66969. for (var i = 0; i < 10; ++i) {
  66970. if (data && data[i]) {
  66971. this.data[i] = data[i];
  66972. }
  66973. else {
  66974. this.data[i] = 0;
  66975. }
  66976. }
  66977. }
  66978. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  66979. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  66980. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  66981. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  66982. return det;
  66983. };
  66984. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  66985. for (var i = 0; i < 10; ++i) {
  66986. this.data[i] += matrix.data[i];
  66987. }
  66988. };
  66989. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  66990. for (var i = 0; i < 10; ++i) {
  66991. this.data[i] += data[i];
  66992. }
  66993. };
  66994. QuadraticMatrix.prototype.add = function (matrix) {
  66995. var m = new QuadraticMatrix();
  66996. for (var i = 0; i < 10; ++i) {
  66997. m.data[i] = this.data[i] + matrix.data[i];
  66998. }
  66999. return m;
  67000. };
  67001. QuadraticMatrix.FromData = function (a, b, c, d) {
  67002. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  67003. };
  67004. //returning an array to avoid garbage collection
  67005. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  67006. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  67007. };
  67008. return QuadraticMatrix;
  67009. }());
  67010. BABYLON.QuadraticMatrix = QuadraticMatrix;
  67011. var Reference = (function () {
  67012. function Reference(vertexId, triangleId) {
  67013. this.vertexId = vertexId;
  67014. this.triangleId = triangleId;
  67015. }
  67016. return Reference;
  67017. }());
  67018. BABYLON.Reference = Reference;
  67019. /**
  67020. * An implementation of the Quadratic Error simplification algorithm.
  67021. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  67022. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  67023. * @author RaananW
  67024. */
  67025. var QuadraticErrorSimplification = (function () {
  67026. function QuadraticErrorSimplification(_mesh) {
  67027. this._mesh = _mesh;
  67028. this.initialized = false;
  67029. this.syncIterations = 5000;
  67030. this.aggressiveness = 7;
  67031. this.decimationIterations = 100;
  67032. this.boundingBoxEpsilon = BABYLON.Epsilon;
  67033. }
  67034. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  67035. var _this = this;
  67036. this.initDecimatedMesh();
  67037. //iterating through the submeshes array, one after the other.
  67038. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  67039. _this.initWithMesh(loop.index, function () {
  67040. _this.runDecimation(settings, loop.index, function () {
  67041. loop.executeNext();
  67042. });
  67043. }, settings.optimizeMesh);
  67044. }, function () {
  67045. setTimeout(function () {
  67046. successCallback(_this._reconstructedMesh);
  67047. }, 0);
  67048. });
  67049. };
  67050. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  67051. var _this = this;
  67052. var gCount = 0;
  67053. triangle.vertices.forEach(function (vertex) {
  67054. var count = 0;
  67055. var vPos = vertex.position;
  67056. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  67057. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  67058. ++count;
  67059. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  67060. ++count;
  67061. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  67062. ++count;
  67063. if (count > 1) {
  67064. ++gCount;
  67065. }
  67066. ;
  67067. });
  67068. if (gCount > 1) {
  67069. console.log(triangle, gCount);
  67070. }
  67071. return gCount > 1;
  67072. };
  67073. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  67074. var _this = this;
  67075. var targetCount = ~~(this.triangles.length * settings.quality);
  67076. var deletedTriangles = 0;
  67077. var triangleCount = this.triangles.length;
  67078. var iterationFunction = function (iteration, callback) {
  67079. setTimeout(function () {
  67080. if (iteration % 5 === 0) {
  67081. _this.updateMesh(iteration === 0);
  67082. }
  67083. for (var i = 0; i < _this.triangles.length; ++i) {
  67084. _this.triangles[i].isDirty = false;
  67085. }
  67086. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  67087. var trianglesIterator = function (i) {
  67088. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  67089. var t = _this.triangles[tIdx];
  67090. if (!t)
  67091. return;
  67092. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  67093. return;
  67094. }
  67095. for (var j = 0; j < 3; ++j) {
  67096. if (t.error[j] < threshold) {
  67097. var deleted0 = [];
  67098. var deleted1 = [];
  67099. var v0 = t.vertices[j];
  67100. var v1 = t.vertices[(j + 1) % 3];
  67101. if (v0.isBorder || v1.isBorder)
  67102. continue;
  67103. var p = BABYLON.Vector3.Zero();
  67104. var n = BABYLON.Vector3.Zero();
  67105. var uv = BABYLON.Vector2.Zero();
  67106. var color = new BABYLON.Color4(0, 0, 0, 1);
  67107. _this.calculateError(v0, v1, p, n, uv, color);
  67108. var delTr = [];
  67109. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  67110. continue;
  67111. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  67112. continue;
  67113. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  67114. continue;
  67115. var uniqueArray = [];
  67116. delTr.forEach(function (deletedT) {
  67117. if (uniqueArray.indexOf(deletedT) === -1) {
  67118. deletedT.deletePending = true;
  67119. uniqueArray.push(deletedT);
  67120. }
  67121. });
  67122. if (uniqueArray.length % 2 !== 0) {
  67123. continue;
  67124. }
  67125. v0.q = v1.q.add(v0.q);
  67126. v0.updatePosition(p);
  67127. var tStart = _this.references.length;
  67128. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  67129. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  67130. var tCount = _this.references.length - tStart;
  67131. if (tCount <= v0.triangleCount) {
  67132. if (tCount) {
  67133. for (var c = 0; c < tCount; c++) {
  67134. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  67135. }
  67136. }
  67137. }
  67138. else {
  67139. v0.triangleStart = tStart;
  67140. }
  67141. v0.triangleCount = tCount;
  67142. break;
  67143. }
  67144. }
  67145. };
  67146. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  67147. }, 0);
  67148. };
  67149. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  67150. if (triangleCount - deletedTriangles <= targetCount)
  67151. loop.breakLoop();
  67152. else {
  67153. iterationFunction(loop.index, function () {
  67154. loop.executeNext();
  67155. });
  67156. }
  67157. }, function () {
  67158. setTimeout(function () {
  67159. //reconstruct this part of the mesh
  67160. _this.reconstructMesh(submeshIndex);
  67161. successCallback();
  67162. }, 0);
  67163. });
  67164. };
  67165. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  67166. var _this = this;
  67167. this.vertices = [];
  67168. this.triangles = [];
  67169. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67170. var indices = this._mesh.getIndices();
  67171. var submesh = this._mesh.subMeshes[submeshIndex];
  67172. var findInVertices = function (positionToSearch) {
  67173. if (optimizeMesh) {
  67174. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  67175. if (_this.vertices[ii].position.equals(positionToSearch)) {
  67176. return _this.vertices[ii];
  67177. }
  67178. }
  67179. }
  67180. return null;
  67181. };
  67182. var vertexReferences = [];
  67183. var vertexInit = function (i) {
  67184. var offset = i + submesh.verticesStart;
  67185. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  67186. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  67187. vertex.originalOffsets.push(offset);
  67188. if (vertex.id === _this.vertices.length) {
  67189. _this.vertices.push(vertex);
  67190. }
  67191. vertexReferences.push(vertex.id);
  67192. };
  67193. //var totalVertices = mesh.getTotalVertices();
  67194. var totalVertices = submesh.verticesCount;
  67195. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  67196. var indicesInit = function (i) {
  67197. var offset = (submesh.indexStart / 3) + i;
  67198. var pos = (offset * 3);
  67199. var i0 = indices[pos + 0];
  67200. var i1 = indices[pos + 1];
  67201. var i2 = indices[pos + 2];
  67202. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  67203. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  67204. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  67205. var triangle = new DecimationTriangle([v0, v1, v2]);
  67206. triangle.originalOffset = pos;
  67207. _this.triangles.push(triangle);
  67208. };
  67209. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  67210. _this.init(callback);
  67211. });
  67212. });
  67213. };
  67214. QuadraticErrorSimplification.prototype.init = function (callback) {
  67215. var _this = this;
  67216. var triangleInit1 = function (i) {
  67217. var t = _this.triangles[i];
  67218. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  67219. for (var j = 0; j < 3; j++) {
  67220. 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))));
  67221. }
  67222. };
  67223. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  67224. var triangleInit2 = function (i) {
  67225. var t = _this.triangles[i];
  67226. for (var j = 0; j < 3; ++j) {
  67227. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  67228. }
  67229. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  67230. };
  67231. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  67232. _this.initialized = true;
  67233. callback();
  67234. });
  67235. });
  67236. };
  67237. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  67238. var newTriangles = [];
  67239. var i;
  67240. for (i = 0; i < this.vertices.length; ++i) {
  67241. this.vertices[i].triangleCount = 0;
  67242. }
  67243. var t;
  67244. var j;
  67245. for (i = 0; i < this.triangles.length; ++i) {
  67246. if (!this.triangles[i].deleted) {
  67247. t = this.triangles[i];
  67248. for (j = 0; j < 3; ++j) {
  67249. t.vertices[j].triangleCount = 1;
  67250. }
  67251. newTriangles.push(t);
  67252. }
  67253. }
  67254. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  67255. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  67256. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  67257. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  67258. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  67259. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  67260. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  67261. var vertexCount = 0;
  67262. for (i = 0; i < this.vertices.length; ++i) {
  67263. var vertex = this.vertices[i];
  67264. vertex.id = vertexCount;
  67265. if (vertex.triangleCount) {
  67266. vertex.originalOffsets.forEach(function (originalOffset) {
  67267. newPositionData.push(vertex.position.x);
  67268. newPositionData.push(vertex.position.y);
  67269. newPositionData.push(vertex.position.z);
  67270. newNormalData.push(normalData[originalOffset * 3]);
  67271. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  67272. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  67273. if (uvs && uvs.length) {
  67274. newUVsData.push(uvs[(originalOffset * 2)]);
  67275. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  67276. }
  67277. else if (colorsData && colorsData.length) {
  67278. newColorsData.push(colorsData[(originalOffset * 4)]);
  67279. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  67280. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  67281. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  67282. }
  67283. ++vertexCount;
  67284. });
  67285. }
  67286. }
  67287. var startingIndex = this._reconstructedMesh.getTotalIndices();
  67288. var startingVertex = this._reconstructedMesh.getTotalVertices();
  67289. var submeshesArray = this._reconstructedMesh.subMeshes;
  67290. this._reconstructedMesh.subMeshes = [];
  67291. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  67292. var originalIndices = this._mesh.getIndices();
  67293. for (i = 0; i < newTriangles.length; ++i) {
  67294. t = newTriangles[i]; //now get the new referencing point for each vertex
  67295. [0, 1, 2].forEach(function (idx) {
  67296. var id = originalIndices[t.originalOffset + idx];
  67297. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  67298. if (offset < 0)
  67299. offset = 0;
  67300. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  67301. });
  67302. }
  67303. //overwriting the old vertex buffers and indices.
  67304. this._reconstructedMesh.setIndices(newIndicesArray);
  67305. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  67306. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  67307. if (newUVsData.length > 0)
  67308. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  67309. if (newColorsData.length > 0)
  67310. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  67311. //create submesh
  67312. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  67313. if (submeshIndex > 0) {
  67314. this._reconstructedMesh.subMeshes = [];
  67315. submeshesArray.forEach(function (submesh) {
  67316. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  67317. });
  67318. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  67319. }
  67320. };
  67321. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  67322. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  67323. this._reconstructedMesh.material = this._mesh.material;
  67324. this._reconstructedMesh.parent = this._mesh.parent;
  67325. this._reconstructedMesh.isVisible = false;
  67326. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  67327. };
  67328. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  67329. for (var i = 0; i < vertex1.triangleCount; ++i) {
  67330. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  67331. if (t.deleted)
  67332. continue;
  67333. var s = this.references[vertex1.triangleStart + i].vertexId;
  67334. var v1 = t.vertices[(s + 1) % 3];
  67335. var v2 = t.vertices[(s + 2) % 3];
  67336. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  67337. deletedArray[i] = true;
  67338. delTr.push(t);
  67339. continue;
  67340. }
  67341. var d1 = v1.position.subtract(point);
  67342. d1 = d1.normalize();
  67343. var d2 = v2.position.subtract(point);
  67344. d2 = d2.normalize();
  67345. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  67346. return true;
  67347. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  67348. deletedArray[i] = false;
  67349. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  67350. return true;
  67351. }
  67352. return false;
  67353. };
  67354. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  67355. var newDeleted = deletedTriangles;
  67356. for (var i = 0; i < vertex.triangleCount; ++i) {
  67357. var ref = this.references[vertex.triangleStart + i];
  67358. var t = this.triangles[ref.triangleId];
  67359. if (t.deleted)
  67360. continue;
  67361. if (deletedArray[i] && t.deletePending) {
  67362. t.deleted = true;
  67363. newDeleted++;
  67364. continue;
  67365. }
  67366. t.vertices[ref.vertexId] = origVertex;
  67367. t.isDirty = true;
  67368. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  67369. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  67370. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  67371. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  67372. this.references.push(ref);
  67373. }
  67374. return newDeleted;
  67375. };
  67376. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  67377. for (var i = 0; i < this.vertices.length; ++i) {
  67378. var vCount = [];
  67379. var vId = [];
  67380. var v = this.vertices[i];
  67381. var j;
  67382. for (j = 0; j < v.triangleCount; ++j) {
  67383. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  67384. for (var ii = 0; ii < 3; ii++) {
  67385. var ofs = 0;
  67386. var vv = triangle.vertices[ii];
  67387. while (ofs < vCount.length) {
  67388. if (vId[ofs] === vv.id)
  67389. break;
  67390. ++ofs;
  67391. }
  67392. if (ofs === vCount.length) {
  67393. vCount.push(1);
  67394. vId.push(vv.id);
  67395. }
  67396. else {
  67397. vCount[ofs]++;
  67398. }
  67399. }
  67400. }
  67401. for (j = 0; j < vCount.length; ++j) {
  67402. if (vCount[j] === 1) {
  67403. this.vertices[vId[j]].isBorder = true;
  67404. }
  67405. else {
  67406. this.vertices[vId[j]].isBorder = false;
  67407. }
  67408. }
  67409. }
  67410. };
  67411. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  67412. if (identifyBorders === void 0) { identifyBorders = false; }
  67413. var i;
  67414. if (!identifyBorders) {
  67415. var newTrianglesVector = [];
  67416. for (i = 0; i < this.triangles.length; ++i) {
  67417. if (!this.triangles[i].deleted) {
  67418. newTrianglesVector.push(this.triangles[i]);
  67419. }
  67420. }
  67421. this.triangles = newTrianglesVector;
  67422. }
  67423. for (i = 0; i < this.vertices.length; ++i) {
  67424. this.vertices[i].triangleCount = 0;
  67425. this.vertices[i].triangleStart = 0;
  67426. }
  67427. var t;
  67428. var j;
  67429. var v;
  67430. for (i = 0; i < this.triangles.length; ++i) {
  67431. t = this.triangles[i];
  67432. for (j = 0; j < 3; ++j) {
  67433. v = t.vertices[j];
  67434. v.triangleCount++;
  67435. }
  67436. }
  67437. var tStart = 0;
  67438. for (i = 0; i < this.vertices.length; ++i) {
  67439. this.vertices[i].triangleStart = tStart;
  67440. tStart += this.vertices[i].triangleCount;
  67441. this.vertices[i].triangleCount = 0;
  67442. }
  67443. var newReferences = new Array(this.triangles.length * 3);
  67444. for (i = 0; i < this.triangles.length; ++i) {
  67445. t = this.triangles[i];
  67446. for (j = 0; j < 3; ++j) {
  67447. v = t.vertices[j];
  67448. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  67449. v.triangleCount++;
  67450. }
  67451. }
  67452. this.references = newReferences;
  67453. if (identifyBorders) {
  67454. this.identifyBorder();
  67455. }
  67456. };
  67457. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  67458. var x = point.x;
  67459. var y = point.y;
  67460. var z = point.z;
  67461. 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
  67462. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  67463. };
  67464. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  67465. var q = vertex1.q.add(vertex2.q);
  67466. var border = vertex1.isBorder && vertex2.isBorder;
  67467. var error = 0;
  67468. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  67469. if (qDet !== 0 && !border) {
  67470. if (!pointResult) {
  67471. pointResult = BABYLON.Vector3.Zero();
  67472. }
  67473. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  67474. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  67475. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  67476. error = this.vertexError(q, pointResult);
  67477. }
  67478. else {
  67479. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  67480. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  67481. var error1 = this.vertexError(q, vertex1.position);
  67482. var error2 = this.vertexError(q, vertex2.position);
  67483. var error3 = this.vertexError(q, p3);
  67484. error = Math.min(error1, error2, error3);
  67485. if (error === error1) {
  67486. if (pointResult) {
  67487. pointResult.copyFrom(vertex1.position);
  67488. }
  67489. }
  67490. else if (error === error2) {
  67491. if (pointResult) {
  67492. pointResult.copyFrom(vertex2.position);
  67493. }
  67494. }
  67495. else {
  67496. if (pointResult) {
  67497. pointResult.copyFrom(p3);
  67498. }
  67499. }
  67500. }
  67501. return error;
  67502. };
  67503. return QuadraticErrorSimplification;
  67504. }());
  67505. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  67506. })(BABYLON || (BABYLON = {}));
  67507. //# sourceMappingURL=babylon.meshSimplification.js.map
  67508. var BABYLON;
  67509. (function (BABYLON) {
  67510. var Internals;
  67511. (function (Internals) {
  67512. var MeshLODLevel = (function () {
  67513. function MeshLODLevel(distance, mesh) {
  67514. this.distance = distance;
  67515. this.mesh = mesh;
  67516. }
  67517. return MeshLODLevel;
  67518. }());
  67519. Internals.MeshLODLevel = MeshLODLevel;
  67520. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67521. })(BABYLON || (BABYLON = {}));
  67522. //# sourceMappingURL=babylon.meshLODLevel.js.map
  67523. var BABYLON;
  67524. (function (BABYLON) {
  67525. // Standard optimizations
  67526. var SceneOptimization = (function () {
  67527. function SceneOptimization(priority) {
  67528. if (priority === void 0) { priority = 0; }
  67529. this.priority = priority;
  67530. this.apply = function (scene) {
  67531. return true; // Return true if everything that can be done was applied
  67532. };
  67533. }
  67534. return SceneOptimization;
  67535. }());
  67536. BABYLON.SceneOptimization = SceneOptimization;
  67537. var TextureOptimization = (function (_super) {
  67538. __extends(TextureOptimization, _super);
  67539. function TextureOptimization(priority, maximumSize) {
  67540. if (priority === void 0) { priority = 0; }
  67541. if (maximumSize === void 0) { maximumSize = 1024; }
  67542. var _this = _super.call(this, priority) || this;
  67543. _this.priority = priority;
  67544. _this.maximumSize = maximumSize;
  67545. _this.apply = function (scene) {
  67546. var allDone = true;
  67547. for (var index = 0; index < scene.textures.length; index++) {
  67548. var texture = scene.textures[index];
  67549. if (!texture.canRescale || texture.getContext) {
  67550. continue;
  67551. }
  67552. var currentSize = texture.getSize();
  67553. var maxDimension = Math.max(currentSize.width, currentSize.height);
  67554. if (maxDimension > _this.maximumSize) {
  67555. texture.scale(0.5);
  67556. allDone = false;
  67557. }
  67558. }
  67559. return allDone;
  67560. };
  67561. return _this;
  67562. }
  67563. return TextureOptimization;
  67564. }(SceneOptimization));
  67565. BABYLON.TextureOptimization = TextureOptimization;
  67566. var HardwareScalingOptimization = (function (_super) {
  67567. __extends(HardwareScalingOptimization, _super);
  67568. function HardwareScalingOptimization(priority, maximumScale) {
  67569. if (priority === void 0) { priority = 0; }
  67570. if (maximumScale === void 0) { maximumScale = 2; }
  67571. var _this = _super.call(this, priority) || this;
  67572. _this.priority = priority;
  67573. _this.maximumScale = maximumScale;
  67574. _this._currentScale = 1;
  67575. _this.apply = function (scene) {
  67576. _this._currentScale++;
  67577. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  67578. return _this._currentScale >= _this.maximumScale;
  67579. };
  67580. return _this;
  67581. }
  67582. return HardwareScalingOptimization;
  67583. }(SceneOptimization));
  67584. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  67585. var ShadowsOptimization = (function (_super) {
  67586. __extends(ShadowsOptimization, _super);
  67587. function ShadowsOptimization() {
  67588. var _this = _super !== null && _super.apply(this, arguments) || this;
  67589. _this.apply = function (scene) {
  67590. scene.shadowsEnabled = false;
  67591. return true;
  67592. };
  67593. return _this;
  67594. }
  67595. return ShadowsOptimization;
  67596. }(SceneOptimization));
  67597. BABYLON.ShadowsOptimization = ShadowsOptimization;
  67598. var PostProcessesOptimization = (function (_super) {
  67599. __extends(PostProcessesOptimization, _super);
  67600. function PostProcessesOptimization() {
  67601. var _this = _super !== null && _super.apply(this, arguments) || this;
  67602. _this.apply = function (scene) {
  67603. scene.postProcessesEnabled = false;
  67604. return true;
  67605. };
  67606. return _this;
  67607. }
  67608. return PostProcessesOptimization;
  67609. }(SceneOptimization));
  67610. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  67611. var LensFlaresOptimization = (function (_super) {
  67612. __extends(LensFlaresOptimization, _super);
  67613. function LensFlaresOptimization() {
  67614. var _this = _super !== null && _super.apply(this, arguments) || this;
  67615. _this.apply = function (scene) {
  67616. scene.lensFlaresEnabled = false;
  67617. return true;
  67618. };
  67619. return _this;
  67620. }
  67621. return LensFlaresOptimization;
  67622. }(SceneOptimization));
  67623. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  67624. var ParticlesOptimization = (function (_super) {
  67625. __extends(ParticlesOptimization, _super);
  67626. function ParticlesOptimization() {
  67627. var _this = _super !== null && _super.apply(this, arguments) || this;
  67628. _this.apply = function (scene) {
  67629. scene.particlesEnabled = false;
  67630. return true;
  67631. };
  67632. return _this;
  67633. }
  67634. return ParticlesOptimization;
  67635. }(SceneOptimization));
  67636. BABYLON.ParticlesOptimization = ParticlesOptimization;
  67637. var RenderTargetsOptimization = (function (_super) {
  67638. __extends(RenderTargetsOptimization, _super);
  67639. function RenderTargetsOptimization() {
  67640. var _this = _super !== null && _super.apply(this, arguments) || this;
  67641. _this.apply = function (scene) {
  67642. scene.renderTargetsEnabled = false;
  67643. return true;
  67644. };
  67645. return _this;
  67646. }
  67647. return RenderTargetsOptimization;
  67648. }(SceneOptimization));
  67649. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  67650. var MergeMeshesOptimization = (function (_super) {
  67651. __extends(MergeMeshesOptimization, _super);
  67652. function MergeMeshesOptimization() {
  67653. var _this = _super !== null && _super.apply(this, arguments) || this;
  67654. _this._canBeMerged = function (abstractMesh) {
  67655. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  67656. return false;
  67657. }
  67658. var mesh = abstractMesh;
  67659. if (!mesh.isVisible || !mesh.isEnabled()) {
  67660. return false;
  67661. }
  67662. if (mesh.instances.length > 0) {
  67663. return false;
  67664. }
  67665. if (mesh.skeleton || mesh.hasLODLevels) {
  67666. return false;
  67667. }
  67668. if (mesh.parent) {
  67669. return false;
  67670. }
  67671. return true;
  67672. };
  67673. _this.apply = function (scene, updateSelectionTree) {
  67674. var globalPool = scene.meshes.slice(0);
  67675. var globalLength = globalPool.length;
  67676. for (var index = 0; index < globalLength; index++) {
  67677. var currentPool = new Array();
  67678. var current = globalPool[index];
  67679. // Checks
  67680. if (!_this._canBeMerged(current)) {
  67681. continue;
  67682. }
  67683. currentPool.push(current);
  67684. // Find compatible meshes
  67685. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  67686. var otherMesh = globalPool[subIndex];
  67687. if (!_this._canBeMerged(otherMesh)) {
  67688. continue;
  67689. }
  67690. if (otherMesh.material !== current.material) {
  67691. continue;
  67692. }
  67693. if (otherMesh.checkCollisions !== current.checkCollisions) {
  67694. continue;
  67695. }
  67696. currentPool.push(otherMesh);
  67697. globalLength--;
  67698. globalPool.splice(subIndex, 1);
  67699. subIndex--;
  67700. }
  67701. if (currentPool.length < 2) {
  67702. continue;
  67703. }
  67704. // Merge meshes
  67705. BABYLON.Mesh.MergeMeshes(currentPool);
  67706. }
  67707. if (updateSelectionTree != undefined) {
  67708. if (updateSelectionTree) {
  67709. scene.createOrUpdateSelectionOctree();
  67710. }
  67711. }
  67712. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  67713. scene.createOrUpdateSelectionOctree();
  67714. }
  67715. return true;
  67716. };
  67717. return _this;
  67718. }
  67719. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  67720. get: function () {
  67721. return MergeMeshesOptimization._UpdateSelectionTree;
  67722. },
  67723. set: function (value) {
  67724. MergeMeshesOptimization._UpdateSelectionTree = value;
  67725. },
  67726. enumerable: true,
  67727. configurable: true
  67728. });
  67729. MergeMeshesOptimization._UpdateSelectionTree = false;
  67730. return MergeMeshesOptimization;
  67731. }(SceneOptimization));
  67732. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  67733. // Options
  67734. var SceneOptimizerOptions = (function () {
  67735. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  67736. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  67737. if (trackerDuration === void 0) { trackerDuration = 2000; }
  67738. this.targetFrameRate = targetFrameRate;
  67739. this.trackerDuration = trackerDuration;
  67740. this.optimizations = new Array();
  67741. }
  67742. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  67743. var result = new SceneOptimizerOptions(targetFrameRate);
  67744. var priority = 0;
  67745. result.optimizations.push(new MergeMeshesOptimization(priority));
  67746. result.optimizations.push(new ShadowsOptimization(priority));
  67747. result.optimizations.push(new LensFlaresOptimization(priority));
  67748. // Next priority
  67749. priority++;
  67750. result.optimizations.push(new PostProcessesOptimization(priority));
  67751. result.optimizations.push(new ParticlesOptimization(priority));
  67752. // Next priority
  67753. priority++;
  67754. result.optimizations.push(new TextureOptimization(priority, 1024));
  67755. return result;
  67756. };
  67757. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  67758. var result = new SceneOptimizerOptions(targetFrameRate);
  67759. var priority = 0;
  67760. result.optimizations.push(new MergeMeshesOptimization(priority));
  67761. result.optimizations.push(new ShadowsOptimization(priority));
  67762. result.optimizations.push(new LensFlaresOptimization(priority));
  67763. // Next priority
  67764. priority++;
  67765. result.optimizations.push(new PostProcessesOptimization(priority));
  67766. result.optimizations.push(new ParticlesOptimization(priority));
  67767. // Next priority
  67768. priority++;
  67769. result.optimizations.push(new TextureOptimization(priority, 512));
  67770. // Next priority
  67771. priority++;
  67772. result.optimizations.push(new RenderTargetsOptimization(priority));
  67773. // Next priority
  67774. priority++;
  67775. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  67776. return result;
  67777. };
  67778. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  67779. var result = new SceneOptimizerOptions(targetFrameRate);
  67780. var priority = 0;
  67781. result.optimizations.push(new MergeMeshesOptimization(priority));
  67782. result.optimizations.push(new ShadowsOptimization(priority));
  67783. result.optimizations.push(new LensFlaresOptimization(priority));
  67784. // Next priority
  67785. priority++;
  67786. result.optimizations.push(new PostProcessesOptimization(priority));
  67787. result.optimizations.push(new ParticlesOptimization(priority));
  67788. // Next priority
  67789. priority++;
  67790. result.optimizations.push(new TextureOptimization(priority, 256));
  67791. // Next priority
  67792. priority++;
  67793. result.optimizations.push(new RenderTargetsOptimization(priority));
  67794. // Next priority
  67795. priority++;
  67796. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  67797. return result;
  67798. };
  67799. return SceneOptimizerOptions;
  67800. }());
  67801. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  67802. // Scene optimizer tool
  67803. var SceneOptimizer = (function () {
  67804. function SceneOptimizer() {
  67805. }
  67806. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  67807. // TODO: add an epsilon
  67808. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  67809. if (onSuccess) {
  67810. onSuccess();
  67811. }
  67812. return;
  67813. }
  67814. // Apply current level of optimizations
  67815. var allDone = true;
  67816. var noOptimizationApplied = true;
  67817. for (var index = 0; index < options.optimizations.length; index++) {
  67818. var optimization = options.optimizations[index];
  67819. if (optimization.priority === currentPriorityLevel) {
  67820. noOptimizationApplied = false;
  67821. allDone = allDone && optimization.apply(scene);
  67822. }
  67823. }
  67824. // If no optimization was applied, this is a failure :(
  67825. if (noOptimizationApplied) {
  67826. if (onFailure) {
  67827. onFailure();
  67828. }
  67829. return;
  67830. }
  67831. // If all optimizations were done, move to next level
  67832. if (allDone) {
  67833. currentPriorityLevel++;
  67834. }
  67835. // Let's the system running for a specific amount of time before checking FPS
  67836. scene.executeWhenReady(function () {
  67837. setTimeout(function () {
  67838. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  67839. }, options.trackerDuration);
  67840. });
  67841. };
  67842. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  67843. if (!options) {
  67844. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  67845. }
  67846. // Let's the system running for a specific amount of time before checking FPS
  67847. scene.executeWhenReady(function () {
  67848. setTimeout(function () {
  67849. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  67850. }, options.trackerDuration);
  67851. });
  67852. };
  67853. return SceneOptimizer;
  67854. }());
  67855. BABYLON.SceneOptimizer = SceneOptimizer;
  67856. })(BABYLON || (BABYLON = {}));
  67857. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  67858. var BABYLON;
  67859. (function (BABYLON) {
  67860. var OutlineRenderer = (function () {
  67861. function OutlineRenderer(scene) {
  67862. this.zOffset = 1;
  67863. this._scene = scene;
  67864. }
  67865. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  67866. var _this = this;
  67867. if (useOverlay === void 0) { useOverlay = false; }
  67868. var scene = this._scene;
  67869. var engine = this._scene.getEngine();
  67870. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  67871. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  67872. return;
  67873. }
  67874. var mesh = subMesh.getRenderingMesh();
  67875. var material = subMesh.getMaterial();
  67876. engine.enableEffect(this._effect);
  67877. // Logarithmic depth
  67878. if (material.useLogarithmicDepth) {
  67879. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  67880. }
  67881. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  67882. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  67883. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67884. // Bones
  67885. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67886. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67887. }
  67888. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  67889. // Alpha test
  67890. if (material && material.needAlphaTesting()) {
  67891. var alphaTexture = material.getAlphaTestTexture();
  67892. if (alphaTexture) {
  67893. this._effect.setTexture("diffuseSampler", alphaTexture);
  67894. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67895. }
  67896. }
  67897. engine.setZOffset(-this.zOffset);
  67898. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  67899. engine.setZOffset(0);
  67900. };
  67901. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  67902. var defines = [];
  67903. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  67904. var mesh = subMesh.getMesh();
  67905. var material = subMesh.getMaterial();
  67906. if (material) {
  67907. // Alpha test
  67908. if (material.needAlphaTesting()) {
  67909. defines.push("#define ALPHATEST");
  67910. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67911. attribs.push(BABYLON.VertexBuffer.UVKind);
  67912. defines.push("#define UV1");
  67913. }
  67914. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67915. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67916. defines.push("#define UV2");
  67917. }
  67918. }
  67919. //Logarithmic depth
  67920. if (material.useLogarithmicDepth) {
  67921. defines.push("#define LOGARITHMICDEPTH");
  67922. }
  67923. }
  67924. // Bones
  67925. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67926. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67927. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67928. if (mesh.numBoneInfluencers > 4) {
  67929. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67930. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67931. }
  67932. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67933. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  67934. }
  67935. else {
  67936. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67937. }
  67938. // Instances
  67939. if (useInstances) {
  67940. defines.push("#define INSTANCES");
  67941. attribs.push("world0");
  67942. attribs.push("world1");
  67943. attribs.push("world2");
  67944. attribs.push("world3");
  67945. }
  67946. // Get correct effect
  67947. var join = defines.join("\n");
  67948. if (this._cachedDefines !== join) {
  67949. this._cachedDefines = join;
  67950. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  67951. }
  67952. return this._effect.isReady();
  67953. };
  67954. return OutlineRenderer;
  67955. }());
  67956. BABYLON.OutlineRenderer = OutlineRenderer;
  67957. })(BABYLON || (BABYLON = {}));
  67958. //# sourceMappingURL=babylon.outlineRenderer.js.map
  67959. var BABYLON;
  67960. (function (BABYLON) {
  67961. var FaceAdjacencies = (function () {
  67962. function FaceAdjacencies() {
  67963. this.edges = new Array();
  67964. this.edgesConnectedCount = 0;
  67965. }
  67966. return FaceAdjacencies;
  67967. }());
  67968. var EdgesRenderer = (function () {
  67969. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  67970. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  67971. if (epsilon === void 0) { epsilon = 0.95; }
  67972. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  67973. this.edgesWidthScalerForOrthographic = 1000.0;
  67974. this.edgesWidthScalerForPerspective = 50.0;
  67975. this._linesPositions = new Array();
  67976. this._linesNormals = new Array();
  67977. this._linesIndices = new Array();
  67978. this._buffers = {};
  67979. this._checkVerticesInsteadOfIndices = false;
  67980. this._source = source;
  67981. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  67982. this._epsilon = epsilon;
  67983. this._prepareRessources();
  67984. this._generateEdgesLines();
  67985. }
  67986. EdgesRenderer.prototype._prepareRessources = function () {
  67987. if (this._lineShader) {
  67988. return;
  67989. }
  67990. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  67991. attributes: ["position", "normal"],
  67992. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  67993. });
  67994. this._lineShader.disableDepthWrite = true;
  67995. this._lineShader.backFaceCulling = false;
  67996. };
  67997. EdgesRenderer.prototype._rebuild = function () {
  67998. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  67999. if (buffer) {
  68000. buffer._rebuild();
  68001. }
  68002. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  68003. if (buffer) {
  68004. buffer._rebuild();
  68005. }
  68006. var scene = this._source.getScene();
  68007. var engine = scene.getEngine();
  68008. this._ib = engine.createIndexBuffer(this._linesIndices);
  68009. };
  68010. EdgesRenderer.prototype.dispose = function () {
  68011. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  68012. if (buffer) {
  68013. buffer.dispose();
  68014. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  68015. }
  68016. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  68017. if (buffer) {
  68018. buffer.dispose();
  68019. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  68020. }
  68021. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  68022. this._lineShader.dispose();
  68023. };
  68024. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  68025. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  68026. return 0;
  68027. }
  68028. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  68029. return 1;
  68030. }
  68031. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  68032. return 2;
  68033. }
  68034. return -1;
  68035. };
  68036. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  68037. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  68038. return 0;
  68039. }
  68040. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  68041. return 1;
  68042. }
  68043. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  68044. return 2;
  68045. }
  68046. return -1;
  68047. };
  68048. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  68049. var needToCreateLine;
  68050. if (edge === undefined) {
  68051. needToCreateLine = true;
  68052. }
  68053. else {
  68054. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  68055. needToCreateLine = dotProduct < this._epsilon;
  68056. }
  68057. if (needToCreateLine) {
  68058. var offset = this._linesPositions.length / 3;
  68059. var normal = p0.subtract(p1);
  68060. normal.normalize();
  68061. // Positions
  68062. this._linesPositions.push(p0.x);
  68063. this._linesPositions.push(p0.y);
  68064. this._linesPositions.push(p0.z);
  68065. this._linesPositions.push(p0.x);
  68066. this._linesPositions.push(p0.y);
  68067. this._linesPositions.push(p0.z);
  68068. this._linesPositions.push(p1.x);
  68069. this._linesPositions.push(p1.y);
  68070. this._linesPositions.push(p1.z);
  68071. this._linesPositions.push(p1.x);
  68072. this._linesPositions.push(p1.y);
  68073. this._linesPositions.push(p1.z);
  68074. // Normals
  68075. this._linesNormals.push(p1.x);
  68076. this._linesNormals.push(p1.y);
  68077. this._linesNormals.push(p1.z);
  68078. this._linesNormals.push(-1);
  68079. this._linesNormals.push(p1.x);
  68080. this._linesNormals.push(p1.y);
  68081. this._linesNormals.push(p1.z);
  68082. this._linesNormals.push(1);
  68083. this._linesNormals.push(p0.x);
  68084. this._linesNormals.push(p0.y);
  68085. this._linesNormals.push(p0.z);
  68086. this._linesNormals.push(-1);
  68087. this._linesNormals.push(p0.x);
  68088. this._linesNormals.push(p0.y);
  68089. this._linesNormals.push(p0.z);
  68090. this._linesNormals.push(1);
  68091. // Indices
  68092. this._linesIndices.push(offset);
  68093. this._linesIndices.push(offset + 1);
  68094. this._linesIndices.push(offset + 2);
  68095. this._linesIndices.push(offset);
  68096. this._linesIndices.push(offset + 2);
  68097. this._linesIndices.push(offset + 3);
  68098. }
  68099. };
  68100. EdgesRenderer.prototype._generateEdgesLines = function () {
  68101. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68102. var indices = this._source.getIndices();
  68103. // First let's find adjacencies
  68104. var adjacencies = new Array();
  68105. var faceNormals = new Array();
  68106. var index;
  68107. var faceAdjacencies;
  68108. // Prepare faces
  68109. for (index = 0; index < indices.length; index += 3) {
  68110. faceAdjacencies = new FaceAdjacencies();
  68111. var p0Index = indices[index];
  68112. var p1Index = indices[index + 1];
  68113. var p2Index = indices[index + 2];
  68114. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  68115. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  68116. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  68117. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  68118. faceNormal.normalize();
  68119. faceNormals.push(faceNormal);
  68120. adjacencies.push(faceAdjacencies);
  68121. }
  68122. // Scan
  68123. for (index = 0; index < adjacencies.length; index++) {
  68124. faceAdjacencies = adjacencies[index];
  68125. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  68126. var otherFaceAdjacencies = adjacencies[otherIndex];
  68127. if (faceAdjacencies.edgesConnectedCount === 3) {
  68128. break;
  68129. }
  68130. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  68131. continue;
  68132. }
  68133. var otherP0 = indices[otherIndex * 3];
  68134. var otherP1 = indices[otherIndex * 3 + 1];
  68135. var otherP2 = indices[otherIndex * 3 + 2];
  68136. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  68137. var otherEdgeIndex;
  68138. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  68139. continue;
  68140. }
  68141. switch (edgeIndex) {
  68142. case 0:
  68143. if (this._checkVerticesInsteadOfIndices) {
  68144. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  68145. }
  68146. else {
  68147. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  68148. }
  68149. break;
  68150. case 1:
  68151. if (this._checkVerticesInsteadOfIndices) {
  68152. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  68153. }
  68154. else {
  68155. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  68156. }
  68157. break;
  68158. case 2:
  68159. if (this._checkVerticesInsteadOfIndices) {
  68160. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  68161. }
  68162. else {
  68163. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  68164. }
  68165. break;
  68166. }
  68167. if (otherEdgeIndex === -1) {
  68168. continue;
  68169. }
  68170. faceAdjacencies.edges[edgeIndex] = otherIndex;
  68171. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  68172. faceAdjacencies.edgesConnectedCount++;
  68173. otherFaceAdjacencies.edgesConnectedCount++;
  68174. if (faceAdjacencies.edgesConnectedCount === 3) {
  68175. break;
  68176. }
  68177. }
  68178. }
  68179. }
  68180. // Create lines
  68181. for (index = 0; index < adjacencies.length; index++) {
  68182. // 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
  68183. var current = adjacencies[index];
  68184. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  68185. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  68186. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  68187. }
  68188. // Merge into a single mesh
  68189. var engine = this._source.getScene().getEngine();
  68190. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  68191. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  68192. this._ib = engine.createIndexBuffer(this._linesIndices);
  68193. this._indicesCount = this._linesIndices.length;
  68194. };
  68195. EdgesRenderer.prototype.render = function () {
  68196. if (!this._lineShader.isReady()) {
  68197. return;
  68198. }
  68199. var scene = this._source.getScene();
  68200. var engine = scene.getEngine();
  68201. this._lineShader._preBind();
  68202. // VBOs
  68203. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  68204. scene.resetCachedMaterial();
  68205. this._lineShader.setColor4("color", this._source.edgesColor);
  68206. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  68207. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  68208. }
  68209. else {
  68210. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  68211. }
  68212. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  68213. this._lineShader.bind(this._source.getWorldMatrix());
  68214. // Draw order
  68215. engine.draw(true, 0, this._indicesCount);
  68216. this._lineShader.unbind();
  68217. engine.setDepthWrite(true);
  68218. };
  68219. return EdgesRenderer;
  68220. }());
  68221. BABYLON.EdgesRenderer = EdgesRenderer;
  68222. })(BABYLON || (BABYLON = {}));
  68223. //# sourceMappingURL=babylon.edgesRenderer.js.map
  68224. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  68225. /// <reference path="..\Math\babylon.math.ts" />
  68226. var BABYLON;
  68227. (function (BABYLON) {
  68228. /**
  68229. * Special Glow Blur post process only blurring the alpha channel
  68230. * It enforces keeping the most luminous color in the color channel.
  68231. */
  68232. var GlowBlurPostProcess = (function (_super) {
  68233. __extends(GlowBlurPostProcess, _super);
  68234. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  68235. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68236. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  68237. _this.direction = direction;
  68238. _this.kernel = kernel;
  68239. _this.onApplyObservable.add(function (effect) {
  68240. effect.setFloat2("screenSize", _this.width, _this.height);
  68241. effect.setVector2("direction", _this.direction);
  68242. effect.setFloat("blurWidth", _this.kernel);
  68243. });
  68244. return _this;
  68245. }
  68246. return GlowBlurPostProcess;
  68247. }(BABYLON.PostProcess));
  68248. /**
  68249. * The highlight layer Helps adding a glow effect around a mesh.
  68250. *
  68251. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  68252. * glowy meshes to your scene.
  68253. *
  68254. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  68255. */
  68256. var HighlightLayer = (function () {
  68257. /**
  68258. * Instantiates a new highlight Layer and references it to the scene..
  68259. * @param name The name of the layer
  68260. * @param scene The scene to use the layer in
  68261. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  68262. */
  68263. function HighlightLayer(name, scene, options) {
  68264. this.name = name;
  68265. this._vertexBuffers = {};
  68266. this._mainTextureDesiredSize = { width: 0, height: 0 };
  68267. this._meshes = {};
  68268. this._maxSize = 0;
  68269. this._shouldRender = false;
  68270. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  68271. this._excludedMeshes = {};
  68272. /**
  68273. * Specifies whether or not the inner glow is ACTIVE in the layer.
  68274. */
  68275. this.innerGlow = true;
  68276. /**
  68277. * Specifies whether or not the outer glow is ACTIVE in the layer.
  68278. */
  68279. this.outerGlow = true;
  68280. /**
  68281. * Specifies wether the highlight layer is enabled or not.
  68282. */
  68283. this.isEnabled = true;
  68284. /**
  68285. * An event triggered when the highlight layer has been disposed.
  68286. * @type {BABYLON.Observable}
  68287. */
  68288. this.onDisposeObservable = new BABYLON.Observable();
  68289. /**
  68290. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  68291. * @type {BABYLON.Observable}
  68292. */
  68293. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  68294. /**
  68295. * An event triggered when the highlight layer is being blurred.
  68296. * @type {BABYLON.Observable}
  68297. */
  68298. this.onBeforeBlurObservable = new BABYLON.Observable();
  68299. /**
  68300. * An event triggered when the highlight layer has been blurred.
  68301. * @type {BABYLON.Observable}
  68302. */
  68303. this.onAfterBlurObservable = new BABYLON.Observable();
  68304. /**
  68305. * An event triggered when the glowing blurred texture is being merged in the scene.
  68306. * @type {BABYLON.Observable}
  68307. */
  68308. this.onBeforeComposeObservable = new BABYLON.Observable();
  68309. /**
  68310. * An event triggered when the glowing blurred texture has been merged in the scene.
  68311. * @type {BABYLON.Observable}
  68312. */
  68313. this.onAfterComposeObservable = new BABYLON.Observable();
  68314. /**
  68315. * An event triggered when the highlight layer changes its size.
  68316. * @type {BABYLON.Observable}
  68317. */
  68318. this.onSizeChangedObservable = new BABYLON.Observable();
  68319. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  68320. var engine = scene.getEngine();
  68321. this._engine = engine;
  68322. this._maxSize = this._engine.getCaps().maxTextureSize;
  68323. this._scene.highlightLayers.push(this);
  68324. // Warn on stencil.
  68325. if (!this._engine.isStencilEnable) {
  68326. 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 }");
  68327. }
  68328. // Adapt options
  68329. this._options = options || {
  68330. mainTextureRatio: 0.5,
  68331. blurTextureSizeRatio: 0.5,
  68332. blurHorizontalSize: 1.0,
  68333. blurVerticalSize: 1.0,
  68334. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  68335. };
  68336. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  68337. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  68338. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  68339. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  68340. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  68341. // VBO
  68342. var vertices = [];
  68343. vertices.push(1, 1);
  68344. vertices.push(-1, 1);
  68345. vertices.push(-1, -1);
  68346. vertices.push(1, -1);
  68347. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  68348. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  68349. this._createIndexBuffer();
  68350. // Effect
  68351. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  68352. // Render target
  68353. this.setMainTextureSize();
  68354. // Create Textures and post processes
  68355. this.createTextureAndPostProcesses();
  68356. }
  68357. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  68358. /**
  68359. * Gets the horizontal size of the blur.
  68360. */
  68361. get: function () {
  68362. return this._horizontalBlurPostprocess.kernel;
  68363. },
  68364. /**
  68365. * Specifies the horizontal size of the blur.
  68366. */
  68367. set: function (value) {
  68368. this._horizontalBlurPostprocess.kernel = value;
  68369. },
  68370. enumerable: true,
  68371. configurable: true
  68372. });
  68373. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  68374. /**
  68375. * Gets the vertical size of the blur.
  68376. */
  68377. get: function () {
  68378. return this._verticalBlurPostprocess.kernel;
  68379. },
  68380. /**
  68381. * Specifies the vertical size of the blur.
  68382. */
  68383. set: function (value) {
  68384. this._verticalBlurPostprocess.kernel = value;
  68385. },
  68386. enumerable: true,
  68387. configurable: true
  68388. });
  68389. Object.defineProperty(HighlightLayer.prototype, "camera", {
  68390. /**
  68391. * Gets the camera attached to the layer.
  68392. */
  68393. get: function () {
  68394. return this._options.camera;
  68395. },
  68396. enumerable: true,
  68397. configurable: true
  68398. });
  68399. HighlightLayer.prototype._createIndexBuffer = function () {
  68400. var engine = this._scene.getEngine();
  68401. // Indices
  68402. var indices = [];
  68403. indices.push(0);
  68404. indices.push(1);
  68405. indices.push(2);
  68406. indices.push(0);
  68407. indices.push(2);
  68408. indices.push(3);
  68409. this._indexBuffer = engine.createIndexBuffer(indices);
  68410. };
  68411. HighlightLayer.prototype._rebuild = function () {
  68412. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  68413. this._createIndexBuffer();
  68414. };
  68415. /**
  68416. * Creates the render target textures and post processes used in the highlight layer.
  68417. */
  68418. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  68419. var _this = this;
  68420. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  68421. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  68422. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  68423. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  68424. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  68425. width: this._mainTextureDesiredSize.width,
  68426. height: this._mainTextureDesiredSize.height
  68427. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68428. this._mainTexture.activeCamera = this._options.camera;
  68429. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68430. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68431. this._mainTexture.anisotropicFilteringLevel = 1;
  68432. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68433. this._mainTexture.renderParticles = false;
  68434. this._mainTexture.renderList = null;
  68435. this._mainTexture.ignoreCameraViewport = true;
  68436. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  68437. width: blurTextureWidth,
  68438. height: blurTextureHeight
  68439. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68440. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68441. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68442. this._blurTexture.anisotropicFilteringLevel = 16;
  68443. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68444. this._blurTexture.renderParticles = false;
  68445. this._blurTexture.ignoreCameraViewport = true;
  68446. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  68447. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  68448. effect.setTexture("textureSampler", _this._mainTexture);
  68449. });
  68450. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  68451. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  68452. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  68453. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  68454. });
  68455. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  68456. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  68457. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  68458. });
  68459. }
  68460. else {
  68461. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  68462. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  68463. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  68464. });
  68465. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  68466. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  68467. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  68468. });
  68469. }
  68470. this._mainTexture.onAfterUnbindObservable.add(function () {
  68471. _this.onBeforeBlurObservable.notifyObservers(_this);
  68472. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture(), true);
  68473. _this.onAfterBlurObservable.notifyObservers(_this);
  68474. });
  68475. // Custom render function
  68476. var renderSubMesh = function (subMesh) {
  68477. var mesh = subMesh.getRenderingMesh();
  68478. var scene = _this._scene;
  68479. var engine = scene.getEngine();
  68480. // Culling
  68481. engine.setState(subMesh.getMaterial().backFaceCulling);
  68482. // Managing instances
  68483. var batch = mesh._getInstancesRenderList(subMesh._id);
  68484. if (batch.mustReturn) {
  68485. return;
  68486. }
  68487. // Excluded Mesh
  68488. if (_this._excludedMeshes[mesh.uniqueId]) {
  68489. return;
  68490. }
  68491. ;
  68492. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  68493. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  68494. var material = subMesh.getMaterial();
  68495. var emissiveTexture = null;
  68496. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  68497. emissiveTexture = material.emissiveTexture;
  68498. }
  68499. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  68500. engine.enableEffect(_this._glowMapGenerationEffect);
  68501. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  68502. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  68503. if (highlightLayerMesh) {
  68504. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  68505. }
  68506. else {
  68507. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  68508. }
  68509. // Alpha test
  68510. if (material && material.needAlphaTesting()) {
  68511. var alphaTexture = material.getAlphaTestTexture();
  68512. if (alphaTexture) {
  68513. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  68514. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68515. }
  68516. }
  68517. // Glow emissive only
  68518. if (emissiveTexture) {
  68519. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  68520. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  68521. }
  68522. // Bones
  68523. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68524. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68525. }
  68526. // Draw
  68527. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  68528. }
  68529. else {
  68530. // Need to reset refresh rate of the shadowMap
  68531. _this._mainTexture.resetRefreshCounter();
  68532. }
  68533. };
  68534. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68535. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  68536. var index;
  68537. var engine = _this._scene.getEngine();
  68538. if (depthOnlySubMeshes.length) {
  68539. engine.setColorWrite(false);
  68540. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68541. renderSubMesh(depthOnlySubMeshes.data[index]);
  68542. }
  68543. engine.setColorWrite(true);
  68544. }
  68545. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68546. renderSubMesh(opaqueSubMeshes.data[index]);
  68547. }
  68548. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68549. renderSubMesh(alphaTestSubMeshes.data[index]);
  68550. }
  68551. for (index = 0; index < transparentSubMeshes.length; index++) {
  68552. renderSubMesh(transparentSubMeshes.data[index]);
  68553. }
  68554. };
  68555. this._mainTexture.onClearObservable.add(function (engine) {
  68556. engine.clear(HighlightLayer.neutralColor, true, true, true);
  68557. });
  68558. };
  68559. /**
  68560. * Checks for the readiness of the element composing the layer.
  68561. * @param subMesh the mesh to check for
  68562. * @param useInstances specify wether or not to use instances to render the mesh
  68563. * @param emissiveTexture the associated emissive texture used to generate the glow
  68564. * @return true if ready otherwise, false
  68565. */
  68566. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  68567. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  68568. return false;
  68569. }
  68570. var defines = [];
  68571. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68572. var mesh = subMesh.getMesh();
  68573. var material = subMesh.getMaterial();
  68574. var uv1 = false;
  68575. var uv2 = false;
  68576. // Alpha test
  68577. if (material && material.needAlphaTesting()) {
  68578. var alphaTexture = material.getAlphaTestTexture();
  68579. if (alphaTexture) {
  68580. defines.push("#define ALPHATEST");
  68581. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  68582. alphaTexture.coordinatesIndex === 1) {
  68583. defines.push("#define DIFFUSEUV2");
  68584. uv2 = true;
  68585. }
  68586. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68587. defines.push("#define DIFFUSEUV1");
  68588. uv1 = true;
  68589. }
  68590. }
  68591. }
  68592. // Emissive
  68593. if (emissiveTexture) {
  68594. defines.push("#define EMISSIVE");
  68595. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  68596. emissiveTexture.coordinatesIndex === 1) {
  68597. defines.push("#define EMISSIVEUV2");
  68598. uv2 = true;
  68599. }
  68600. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68601. defines.push("#define EMISSIVEUV1");
  68602. uv1 = true;
  68603. }
  68604. }
  68605. if (uv1) {
  68606. attribs.push(BABYLON.VertexBuffer.UVKind);
  68607. defines.push("#define UV1");
  68608. }
  68609. if (uv2) {
  68610. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68611. defines.push("#define UV2");
  68612. }
  68613. // Bones
  68614. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68615. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68616. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68617. if (mesh.numBoneInfluencers > 4) {
  68618. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68619. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68620. }
  68621. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68622. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  68623. }
  68624. else {
  68625. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68626. }
  68627. // Instances
  68628. if (useInstances) {
  68629. defines.push("#define INSTANCES");
  68630. attribs.push("world0");
  68631. attribs.push("world1");
  68632. attribs.push("world2");
  68633. attribs.push("world3");
  68634. }
  68635. // Get correct effect
  68636. var join = defines.join("\n");
  68637. if (this._cachedDefines !== join) {
  68638. this._cachedDefines = join;
  68639. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  68640. }
  68641. return this._glowMapGenerationEffect.isReady();
  68642. };
  68643. /**
  68644. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  68645. */
  68646. HighlightLayer.prototype.render = function () {
  68647. var currentEffect = this._glowMapMergeEffect;
  68648. // Check
  68649. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  68650. return;
  68651. var engine = this._scene.getEngine();
  68652. this.onBeforeComposeObservable.notifyObservers(this);
  68653. // Render
  68654. engine.enableEffect(currentEffect);
  68655. engine.setState(false);
  68656. // Cache
  68657. var previousStencilBuffer = engine.getStencilBuffer();
  68658. var previousStencilFunction = engine.getStencilFunction();
  68659. var previousStencilMask = engine.getStencilMask();
  68660. var previousStencilOperationPass = engine.getStencilOperationPass();
  68661. var previousStencilOperationFail = engine.getStencilOperationFail();
  68662. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  68663. var previousAlphaMode = engine.getAlphaMode();
  68664. // Texture
  68665. currentEffect.setTexture("textureSampler", this._blurTexture);
  68666. // VBOs
  68667. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  68668. // Stencil operations
  68669. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  68670. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  68671. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  68672. // Draw order
  68673. engine.setAlphaMode(this._options.alphaBlendingMode);
  68674. engine.setStencilMask(0x00);
  68675. engine.setStencilBuffer(true);
  68676. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  68677. if (this.outerGlow) {
  68678. currentEffect.setFloat("offset", 0);
  68679. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  68680. engine.draw(true, 0, 6);
  68681. }
  68682. if (this.innerGlow) {
  68683. currentEffect.setFloat("offset", 1);
  68684. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  68685. engine.draw(true, 0, 6);
  68686. }
  68687. // Restore Cache
  68688. engine.setStencilFunction(previousStencilFunction);
  68689. engine.setStencilMask(previousStencilMask);
  68690. engine.setAlphaMode(previousAlphaMode);
  68691. engine.setStencilBuffer(previousStencilBuffer);
  68692. engine.setStencilOperationPass(previousStencilOperationPass);
  68693. engine.setStencilOperationFail(previousStencilOperationFail);
  68694. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  68695. engine._stencilState.reset();
  68696. this.onAfterComposeObservable.notifyObservers(this);
  68697. // Handle size changes.
  68698. var size = this._mainTexture.getSize();
  68699. this.setMainTextureSize();
  68700. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  68701. // Recreate RTT and post processes on size change.
  68702. this.onSizeChangedObservable.notifyObservers(this);
  68703. this.disposeTextureAndPostProcesses();
  68704. this.createTextureAndPostProcesses();
  68705. }
  68706. };
  68707. /**
  68708. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  68709. * @param mesh The mesh to exclude from the highlight layer
  68710. */
  68711. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  68712. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  68713. if (!meshExcluded) {
  68714. this._excludedMeshes[mesh.uniqueId] = {
  68715. mesh: mesh,
  68716. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  68717. mesh.getEngine().setStencilBuffer(false);
  68718. }),
  68719. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  68720. mesh.getEngine().setStencilBuffer(true);
  68721. }),
  68722. };
  68723. }
  68724. };
  68725. /**
  68726. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  68727. * @param mesh The mesh to highlight
  68728. */
  68729. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  68730. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  68731. if (meshExcluded) {
  68732. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  68733. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  68734. }
  68735. this._excludedMeshes[mesh.uniqueId] = undefined;
  68736. };
  68737. /**
  68738. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  68739. * @param mesh The mesh to highlight
  68740. * @param color The color of the highlight
  68741. * @param glowEmissiveOnly Extract the glow from the emissive texture
  68742. */
  68743. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  68744. var _this = this;
  68745. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  68746. var meshHighlight = this._meshes[mesh.uniqueId];
  68747. if (meshHighlight) {
  68748. meshHighlight.color = color;
  68749. }
  68750. else {
  68751. this._meshes[mesh.uniqueId] = {
  68752. mesh: mesh,
  68753. color: color,
  68754. // Lambda required for capture due to Observable this context
  68755. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  68756. if (_this._excludedMeshes[mesh.uniqueId]) {
  68757. _this.defaultStencilReference(mesh);
  68758. }
  68759. else {
  68760. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  68761. }
  68762. }),
  68763. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  68764. glowEmissiveOnly: glowEmissiveOnly
  68765. };
  68766. }
  68767. this._shouldRender = true;
  68768. };
  68769. /**
  68770. * Remove a mesh from the highlight layer in order to make it stop glowing.
  68771. * @param mesh The mesh to highlight
  68772. */
  68773. HighlightLayer.prototype.removeMesh = function (mesh) {
  68774. var meshHighlight = this._meshes[mesh.uniqueId];
  68775. if (meshHighlight) {
  68776. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  68777. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  68778. }
  68779. this._meshes[mesh.uniqueId] = undefined;
  68780. this._shouldRender = false;
  68781. for (var meshHighlightToCheck in this._meshes) {
  68782. if (meshHighlightToCheck) {
  68783. this._shouldRender = true;
  68784. break;
  68785. }
  68786. }
  68787. };
  68788. /**
  68789. * Returns true if the layer contains information to display, otherwise false.
  68790. */
  68791. HighlightLayer.prototype.shouldRender = function () {
  68792. return this.isEnabled && this._shouldRender;
  68793. };
  68794. /**
  68795. * Sets the main texture desired size which is the closest power of two
  68796. * of the engine canvas size.
  68797. */
  68798. HighlightLayer.prototype.setMainTextureSize = function () {
  68799. if (this._options.mainTextureFixedSize) {
  68800. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  68801. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  68802. }
  68803. else {
  68804. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  68805. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  68806. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  68807. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  68808. }
  68809. };
  68810. /**
  68811. * Force the stencil to the normal expected value for none glowing parts
  68812. */
  68813. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  68814. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  68815. };
  68816. /**
  68817. * Dispose only the render target textures and post process.
  68818. */
  68819. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  68820. this._blurTexture.dispose();
  68821. this._mainTexture.dispose();
  68822. this._downSamplePostprocess.dispose();
  68823. this._horizontalBlurPostprocess.dispose();
  68824. this._verticalBlurPostprocess.dispose();
  68825. };
  68826. /**
  68827. * Dispose the highlight layer and free resources.
  68828. */
  68829. HighlightLayer.prototype.dispose = function () {
  68830. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68831. if (vertexBuffer) {
  68832. vertexBuffer.dispose();
  68833. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68834. }
  68835. if (this._indexBuffer) {
  68836. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  68837. this._indexBuffer = null;
  68838. }
  68839. // Clean textures and post processes
  68840. this.disposeTextureAndPostProcesses();
  68841. // Clean mesh references
  68842. for (var id in this._meshes) {
  68843. var meshHighlight = this._meshes[id];
  68844. if (meshHighlight && meshHighlight.mesh) {
  68845. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  68846. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  68847. }
  68848. }
  68849. this._meshes = null;
  68850. for (var id in this._excludedMeshes) {
  68851. var meshHighlight = this._excludedMeshes[id];
  68852. if (meshHighlight) {
  68853. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  68854. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  68855. }
  68856. }
  68857. this._excludedMeshes = null;
  68858. // Remove from scene
  68859. var index = this._scene.highlightLayers.indexOf(this, 0);
  68860. if (index > -1) {
  68861. this._scene.highlightLayers.splice(index, 1);
  68862. }
  68863. // Callback
  68864. this.onDisposeObservable.notifyObservers(this);
  68865. this.onDisposeObservable.clear();
  68866. this.onBeforeRenderMainTextureObservable.clear();
  68867. this.onBeforeBlurObservable.clear();
  68868. this.onBeforeComposeObservable.clear();
  68869. this.onAfterComposeObservable.clear();
  68870. this.onSizeChangedObservable.clear();
  68871. };
  68872. /**
  68873. * The neutral color used during the preparation of the glow effect.
  68874. * This is black by default as the blend operation is a blend operation.
  68875. */
  68876. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  68877. /**
  68878. * Stencil value used for glowing meshes.
  68879. */
  68880. HighlightLayer.glowingMeshStencilReference = 0x02;
  68881. /**
  68882. * Stencil value used for the other meshes in the scene.
  68883. */
  68884. HighlightLayer.normalMeshStencilReference = 0x01;
  68885. return HighlightLayer;
  68886. }());
  68887. BABYLON.HighlightLayer = HighlightLayer;
  68888. })(BABYLON || (BABYLON = {}));
  68889. //# sourceMappingURL=babylon.highlightlayer.js.map
  68890. var BABYLON;
  68891. (function (BABYLON) {
  68892. var MeshAssetTask = (function () {
  68893. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  68894. this.name = name;
  68895. this.meshesNames = meshesNames;
  68896. this.rootUrl = rootUrl;
  68897. this.sceneFilename = sceneFilename;
  68898. this.isCompleted = false;
  68899. }
  68900. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68901. var _this = this;
  68902. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  68903. _this.loadedMeshes = meshes;
  68904. _this.loadedParticleSystems = particleSystems;
  68905. _this.loadedSkeletons = skeletons;
  68906. _this.isCompleted = true;
  68907. if (_this.onSuccess) {
  68908. _this.onSuccess(_this);
  68909. }
  68910. onSuccess();
  68911. }, null, function () {
  68912. if (_this.onError) {
  68913. _this.onError(_this);
  68914. }
  68915. onError();
  68916. });
  68917. };
  68918. return MeshAssetTask;
  68919. }());
  68920. BABYLON.MeshAssetTask = MeshAssetTask;
  68921. var TextFileAssetTask = (function () {
  68922. function TextFileAssetTask(name, url) {
  68923. this.name = name;
  68924. this.url = url;
  68925. this.isCompleted = false;
  68926. }
  68927. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68928. var _this = this;
  68929. BABYLON.Tools.LoadFile(this.url, function (data) {
  68930. _this.text = data;
  68931. _this.isCompleted = true;
  68932. if (_this.onSuccess) {
  68933. _this.onSuccess(_this);
  68934. }
  68935. onSuccess();
  68936. }, null, scene.database, false, function () {
  68937. if (_this.onError) {
  68938. _this.onError(_this);
  68939. }
  68940. onError();
  68941. });
  68942. };
  68943. return TextFileAssetTask;
  68944. }());
  68945. BABYLON.TextFileAssetTask = TextFileAssetTask;
  68946. var BinaryFileAssetTask = (function () {
  68947. function BinaryFileAssetTask(name, url) {
  68948. this.name = name;
  68949. this.url = url;
  68950. this.isCompleted = false;
  68951. }
  68952. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68953. var _this = this;
  68954. BABYLON.Tools.LoadFile(this.url, function (data) {
  68955. _this.data = data;
  68956. _this.isCompleted = true;
  68957. if (_this.onSuccess) {
  68958. _this.onSuccess(_this);
  68959. }
  68960. onSuccess();
  68961. }, null, scene.database, true, function () {
  68962. if (_this.onError) {
  68963. _this.onError(_this);
  68964. }
  68965. onError();
  68966. });
  68967. };
  68968. return BinaryFileAssetTask;
  68969. }());
  68970. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  68971. var ImageAssetTask = (function () {
  68972. function ImageAssetTask(name, url) {
  68973. this.name = name;
  68974. this.url = url;
  68975. this.isCompleted = false;
  68976. }
  68977. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68978. var _this = this;
  68979. var img = new Image();
  68980. BABYLON.Tools.SetCorsBehavior(this.url, img);
  68981. img.onload = function () {
  68982. _this.image = img;
  68983. _this.isCompleted = true;
  68984. if (_this.onSuccess) {
  68985. _this.onSuccess(_this);
  68986. }
  68987. onSuccess();
  68988. };
  68989. img.onerror = function () {
  68990. if (_this.onError) {
  68991. _this.onError(_this);
  68992. }
  68993. onError();
  68994. };
  68995. img.src = this.url;
  68996. };
  68997. return ImageAssetTask;
  68998. }());
  68999. BABYLON.ImageAssetTask = ImageAssetTask;
  69000. var TextureAssetTask = (function () {
  69001. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  69002. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69003. this.name = name;
  69004. this.url = url;
  69005. this.noMipmap = noMipmap;
  69006. this.invertY = invertY;
  69007. this.samplingMode = samplingMode;
  69008. this.isCompleted = false;
  69009. }
  69010. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69011. var _this = this;
  69012. var onload = function () {
  69013. _this.isCompleted = true;
  69014. if (_this.onSuccess) {
  69015. _this.onSuccess(_this);
  69016. }
  69017. onSuccess();
  69018. };
  69019. var onerror = function () {
  69020. if (_this.onError) {
  69021. _this.onError(_this);
  69022. }
  69023. onError();
  69024. };
  69025. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  69026. };
  69027. return TextureAssetTask;
  69028. }());
  69029. BABYLON.TextureAssetTask = TextureAssetTask;
  69030. var CubeTextureAssetTask = (function () {
  69031. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  69032. this.name = name;
  69033. this.url = url;
  69034. this.extensions = extensions;
  69035. this.noMipmap = noMipmap;
  69036. this.files = files;
  69037. this.isCompleted = false;
  69038. }
  69039. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69040. var _this = this;
  69041. var onload = function () {
  69042. _this.isCompleted = true;
  69043. if (_this.onSuccess) {
  69044. _this.onSuccess(_this);
  69045. }
  69046. onSuccess();
  69047. };
  69048. var onerror = function () {
  69049. if (_this.onError) {
  69050. _this.onError(_this);
  69051. }
  69052. onError();
  69053. };
  69054. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  69055. };
  69056. return CubeTextureAssetTask;
  69057. }());
  69058. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  69059. var HDRCubeTextureAssetTask = (function () {
  69060. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  69061. if (noMipmap === void 0) { noMipmap = false; }
  69062. if (generateHarmonics === void 0) { generateHarmonics = true; }
  69063. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  69064. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  69065. this.name = name;
  69066. this.url = url;
  69067. this.size = size;
  69068. this.noMipmap = noMipmap;
  69069. this.generateHarmonics = generateHarmonics;
  69070. this.useInGammaSpace = useInGammaSpace;
  69071. this.usePMREMGenerator = usePMREMGenerator;
  69072. this.isCompleted = false;
  69073. }
  69074. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  69075. var _this = this;
  69076. var onload = function () {
  69077. _this.isCompleted = true;
  69078. if (_this.onSuccess) {
  69079. _this.onSuccess(_this);
  69080. }
  69081. onSuccess();
  69082. };
  69083. var onerror = function () {
  69084. if (_this.onError) {
  69085. _this.onError(_this);
  69086. }
  69087. onError();
  69088. };
  69089. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  69090. };
  69091. return HDRCubeTextureAssetTask;
  69092. }());
  69093. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  69094. var AssetsManager = (function () {
  69095. function AssetsManager(scene) {
  69096. this.tasks = new Array();
  69097. this.waitingTasksCount = 0;
  69098. this.useDefaultLoadingScreen = true;
  69099. this._scene = scene;
  69100. }
  69101. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  69102. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  69103. this.tasks.push(task);
  69104. return task;
  69105. };
  69106. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  69107. var task = new TextFileAssetTask(taskName, url);
  69108. this.tasks.push(task);
  69109. return task;
  69110. };
  69111. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  69112. var task = new BinaryFileAssetTask(taskName, url);
  69113. this.tasks.push(task);
  69114. return task;
  69115. };
  69116. AssetsManager.prototype.addImageTask = function (taskName, url) {
  69117. var task = new ImageAssetTask(taskName, url);
  69118. this.tasks.push(task);
  69119. return task;
  69120. };
  69121. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  69122. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69123. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  69124. this.tasks.push(task);
  69125. return task;
  69126. };
  69127. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  69128. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  69129. this.tasks.push(task);
  69130. return task;
  69131. };
  69132. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  69133. if (noMipmap === void 0) { noMipmap = false; }
  69134. if (generateHarmonics === void 0) { generateHarmonics = true; }
  69135. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  69136. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  69137. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  69138. this.tasks.push(task);
  69139. return task;
  69140. };
  69141. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  69142. this.waitingTasksCount--;
  69143. if (this.waitingTasksCount === 0) {
  69144. if (this.onFinish) {
  69145. this.onFinish(this.tasks);
  69146. }
  69147. this._scene.getEngine().hideLoadingUI();
  69148. }
  69149. };
  69150. AssetsManager.prototype._runTask = function (task) {
  69151. var _this = this;
  69152. task.run(this._scene, function () {
  69153. if (_this.onTaskSuccess) {
  69154. _this.onTaskSuccess(task);
  69155. }
  69156. _this._decreaseWaitingTasksCount();
  69157. }, function () {
  69158. if (_this.onTaskError) {
  69159. _this.onTaskError(task);
  69160. }
  69161. _this._decreaseWaitingTasksCount();
  69162. });
  69163. };
  69164. AssetsManager.prototype.reset = function () {
  69165. this.tasks = new Array();
  69166. return this;
  69167. };
  69168. AssetsManager.prototype.load = function () {
  69169. this.waitingTasksCount = this.tasks.length;
  69170. if (this.waitingTasksCount === 0) {
  69171. if (this.onFinish) {
  69172. this.onFinish(this.tasks);
  69173. }
  69174. return this;
  69175. }
  69176. if (this.useDefaultLoadingScreen) {
  69177. this._scene.getEngine().displayLoadingUI();
  69178. }
  69179. for (var index = 0; index < this.tasks.length; index++) {
  69180. var task = this.tasks[index];
  69181. this._runTask(task);
  69182. }
  69183. return this;
  69184. };
  69185. return AssetsManager;
  69186. }());
  69187. BABYLON.AssetsManager = AssetsManager;
  69188. })(BABYLON || (BABYLON = {}));
  69189. //# sourceMappingURL=babylon.assetsManager.js.map
  69190. var BABYLON;
  69191. (function (BABYLON) {
  69192. var MapTexture = (function (_super) {
  69193. __extends(MapTexture, _super);
  69194. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  69195. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69196. if (useMipMap === void 0) { useMipMap = false; }
  69197. if (margin === void 0) { margin = 0; }
  69198. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  69199. _this.name = name;
  69200. _this._size = size;
  69201. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69202. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69203. // Create the rectPackMap that will allocate portion of the texture
  69204. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  69205. // Create the texture that will store the content
  69206. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  69207. return _this;
  69208. }
  69209. /**
  69210. * Allocate a rectangle of a given size in the texture map
  69211. * @param size the size of the rectangle to allocation
  69212. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  69213. */
  69214. MapTexture.prototype.allocateRect = function (size) {
  69215. return this._rectPackingMap.addRect(size);
  69216. };
  69217. /**
  69218. * Free a given rectangle from the texture map
  69219. * @param rectInfo the instance corresponding to the rect to free.
  69220. */
  69221. MapTexture.prototype.freeRect = function (rectInfo) {
  69222. if (rectInfo) {
  69223. rectInfo.freeContent();
  69224. }
  69225. };
  69226. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  69227. /**
  69228. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  69229. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  69230. * @returns {}
  69231. */
  69232. get: function () {
  69233. return this._rectPackingMap.freeSpace;
  69234. },
  69235. enumerable: true,
  69236. configurable: true
  69237. });
  69238. /**
  69239. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  69240. * 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.
  69241. * Don't forget to call unbindTexture when you're done rendering
  69242. * @param rect the zone to render to
  69243. * @param clear true to clear the portion's color/depth data
  69244. */
  69245. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  69246. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  69247. };
  69248. /**
  69249. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  69250. * 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.
  69251. * Don't forget to call unbindTexture when you're done rendering
  69252. * @param pos the position into the texture
  69253. * @param size the portion to fit the clip space to
  69254. * @param clear true to clear the portion's color/depth data
  69255. */
  69256. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  69257. var engine = this.getScene().getEngine();
  69258. engine.bindFramebuffer(this._texture);
  69259. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  69260. if (clear) {
  69261. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  69262. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  69263. }
  69264. };
  69265. /**
  69266. * Unbind the texture map from the rendering engine.
  69267. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  69268. * @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.
  69269. */
  69270. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  69271. // Dump ?
  69272. if (dumpForDebug) {
  69273. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  69274. }
  69275. var engine = this.getScene().getEngine();
  69276. if (this._replacedViewport) {
  69277. engine.setViewport(this._replacedViewport);
  69278. this._replacedViewport = null;
  69279. }
  69280. engine.unBindFramebuffer(this._texture);
  69281. };
  69282. Object.defineProperty(MapTexture.prototype, "canRescale", {
  69283. get: function () {
  69284. return false;
  69285. },
  69286. enumerable: true,
  69287. configurable: true
  69288. });
  69289. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  69290. // Anyway, there's not much point to use this method for this kind of texture I guess
  69291. MapTexture.prototype.clone = function () {
  69292. return null;
  69293. };
  69294. return MapTexture;
  69295. }(BABYLON.Texture));
  69296. BABYLON.MapTexture = MapTexture;
  69297. })(BABYLON || (BABYLON = {}));
  69298. //# sourceMappingURL=babylon.mapTexture.js.map
  69299. var BABYLON;
  69300. (function (BABYLON) {
  69301. /**
  69302. * This class describe a rectangle that were added to the map.
  69303. * You have access to its coordinates either in pixel or normalized (UV)
  69304. */
  69305. var PackedRect = (function () {
  69306. function PackedRect(root, parent, pos, size) {
  69307. this._pos = pos;
  69308. this._size = size;
  69309. this._root = root;
  69310. this._parent = parent;
  69311. this._contentSize = null;
  69312. this._bottomNode = null;
  69313. this._leftNode = null;
  69314. this._initialSize = null;
  69315. this._rightNode = null;
  69316. }
  69317. Object.defineProperty(PackedRect.prototype, "pos", {
  69318. /**
  69319. * @returns the position of this node into the map
  69320. */
  69321. get: function () {
  69322. return this._pos;
  69323. },
  69324. enumerable: true,
  69325. configurable: true
  69326. });
  69327. Object.defineProperty(PackedRect.prototype, "contentSize", {
  69328. /**
  69329. * @returns the size of the rectangle this node handles
  69330. */
  69331. get: function () {
  69332. return this._contentSize;
  69333. },
  69334. enumerable: true,
  69335. configurable: true
  69336. });
  69337. /**
  69338. * Retrieve the inner position (considering the margin) and stores it into the res object
  69339. * @param res must be a valid Vector2 that will contain the inner position after this call
  69340. */
  69341. PackedRect.prototype.getInnerPosToRef = function (res) {
  69342. var m = this._root._margin;
  69343. res.x = this._pos.x + m;
  69344. res.y = this._pos.y + m;
  69345. };
  69346. /**
  69347. * Retrieve the inner size (considering the margin) and stores it into the res object
  69348. * @param res must be a valid Size that will contain the inner size after this call
  69349. */
  69350. PackedRect.prototype.getInnerSizeToRef = function (res) {
  69351. var m = this._root._margin;
  69352. res.width = this._contentSize.width - (m * 2);
  69353. res.height = this._contentSize.height - (m * 2);
  69354. };
  69355. Object.defineProperty(PackedRect.prototype, "UVs", {
  69356. /**
  69357. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  69358. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  69359. */
  69360. get: function () {
  69361. if (!this._contentSize) {
  69362. throw new Error("Can't compute UVs for this object because it's nor allocated");
  69363. }
  69364. return this.getUVsForCustomSize(this._contentSize);
  69365. },
  69366. enumerable: true,
  69367. configurable: true
  69368. });
  69369. /**
  69370. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  69371. * and then using only a part of the PackRect.
  69372. * This method will return the UVs for this part by given the custom size of what you really use
  69373. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  69374. */
  69375. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  69376. var mainWidth = this._root._size.width;
  69377. var mainHeight = this._root._size.height;
  69378. var margin = this._root._margin;
  69379. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  69380. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  69381. var uvs = new Array();
  69382. uvs.push(topLeft);
  69383. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  69384. uvs.push(rightBottom);
  69385. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  69386. return uvs;
  69387. };
  69388. /**
  69389. * Free this rectangle from the map.
  69390. * Call this method when you no longer need the rectangle to be in the map.
  69391. */
  69392. PackedRect.prototype.freeContent = function () {
  69393. if (!this.contentSize) {
  69394. return;
  69395. }
  69396. this._contentSize = null;
  69397. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  69398. this.attemptDefrag();
  69399. };
  69400. Object.defineProperty(PackedRect.prototype, "isUsed", {
  69401. get: function () {
  69402. return this._contentSize != null || this._leftNode != null;
  69403. },
  69404. enumerable: true,
  69405. configurable: true
  69406. });
  69407. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  69408. var node = this.findNode(contentSize);
  69409. // Not enough space...
  69410. if (!node) {
  69411. return null;
  69412. }
  69413. node.splitNode(contentSize);
  69414. return node;
  69415. };
  69416. PackedRect.prototype.findNode = function (size) {
  69417. var resNode = null;
  69418. var margin = this._root._margin * 2;
  69419. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  69420. if (this.isUsed) {
  69421. if (this._leftNode) {
  69422. resNode = this._leftNode.findNode(size);
  69423. }
  69424. if (!resNode && this._rightNode) {
  69425. resNode = this._rightNode.findNode(size);
  69426. }
  69427. if (!resNode && this._bottomNode) {
  69428. resNode = this._bottomNode.findNode(size);
  69429. }
  69430. }
  69431. else if (this._initialSize) {
  69432. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  69433. resNode = this;
  69434. }
  69435. else {
  69436. return null;
  69437. }
  69438. }
  69439. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  69440. resNode = this;
  69441. }
  69442. return resNode;
  69443. };
  69444. PackedRect.prototype.splitNode = function (contentSize) {
  69445. var cs = PackedRect.TpsSize;
  69446. var margin = this._root._margin * 2;
  69447. cs.copyFrom(contentSize);
  69448. cs.width += margin;
  69449. cs.height += margin;
  69450. // 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)
  69451. if (!this._contentSize && this._initialSize) {
  69452. this._contentSize = cs.clone();
  69453. 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));
  69454. return this._leftNode.splitNode(contentSize);
  69455. }
  69456. else {
  69457. this._contentSize = cs.clone();
  69458. this._initialSize = cs.clone();
  69459. if (cs.width !== this._size.width) {
  69460. 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));
  69461. }
  69462. if (cs.height !== this._size.height) {
  69463. 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));
  69464. }
  69465. return this;
  69466. }
  69467. };
  69468. PackedRect.prototype.attemptDefrag = function () {
  69469. if (!this.isUsed && this.isRecursiveFree) {
  69470. this.clearNode();
  69471. if (this._parent) {
  69472. this._parent.attemptDefrag();
  69473. }
  69474. }
  69475. };
  69476. PackedRect.prototype.clearNode = function () {
  69477. this._initialSize = null;
  69478. this._rightNode = null;
  69479. this._bottomNode = null;
  69480. };
  69481. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  69482. get: function () {
  69483. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  69484. },
  69485. enumerable: true,
  69486. configurable: true
  69487. });
  69488. PackedRect.prototype.evalFreeSize = function (size) {
  69489. var levelSize = 0;
  69490. if (!this.isUsed) {
  69491. var margin = this._root._margin;
  69492. var is = this._initialSize;
  69493. if (is) {
  69494. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  69495. }
  69496. else {
  69497. var size_1 = this._size;
  69498. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  69499. }
  69500. }
  69501. if (this._rightNode) {
  69502. levelSize += this._rightNode.evalFreeSize(0);
  69503. }
  69504. if (this._bottomNode) {
  69505. levelSize += this._bottomNode.evalFreeSize(0);
  69506. }
  69507. return levelSize + size;
  69508. };
  69509. PackedRect.TpsSize = BABYLON.Size.Zero();
  69510. return PackedRect;
  69511. }());
  69512. BABYLON.PackedRect = PackedRect;
  69513. /**
  69514. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  69515. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  69516. * 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.
  69517. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  69518. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  69519. */
  69520. var RectPackingMap = (function (_super) {
  69521. __extends(RectPackingMap, _super);
  69522. /**
  69523. * Create an instance of the object with a dimension using the given size
  69524. * @param size The dimension of the rectangle that will contain all the sub ones.
  69525. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  69526. */
  69527. function RectPackingMap(size, margin) {
  69528. if (margin === void 0) { margin = 0; }
  69529. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  69530. _this._margin = margin;
  69531. _this._root = _this;
  69532. return _this;
  69533. }
  69534. /**
  69535. * Add a rectangle, finding the best location to store it into the map
  69536. * @param size the dimension of the rectangle to store
  69537. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  69538. */
  69539. RectPackingMap.prototype.addRect = function (size) {
  69540. var node = this.findAndSplitNode(size);
  69541. return node;
  69542. };
  69543. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  69544. /**
  69545. * Return the current space free normalized between [0;1]
  69546. * @returns {}
  69547. */
  69548. get: function () {
  69549. var freeSize = 0;
  69550. freeSize = this.evalFreeSize(freeSize);
  69551. return freeSize / (this._size.width * this._size.height);
  69552. },
  69553. enumerable: true,
  69554. configurable: true
  69555. });
  69556. return RectPackingMap;
  69557. }(PackedRect));
  69558. BABYLON.RectPackingMap = RectPackingMap;
  69559. })(BABYLON || (BABYLON = {}));
  69560. //# sourceMappingURL=babylon.rectPackingMap.js.map
  69561. var BABYLON;
  69562. (function (BABYLON) {
  69563. /**
  69564. * This groups together the common properties used for image processing either in direct forward pass
  69565. * or through post processing effect depending on the use of the image processing pipeline in your scene
  69566. * or not.
  69567. */
  69568. var ImageProcessingConfiguration = (function () {
  69569. function ImageProcessingConfiguration() {
  69570. /**
  69571. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  69572. */
  69573. this.colorCurves = new BABYLON.ColorCurves();
  69574. this._colorCurvesEnabled = false;
  69575. this._colorGradingEnabled = false;
  69576. this._colorGradingWithGreenDepth = false;
  69577. this._colorGradingBGR = false;
  69578. this._exposure = 1.0;
  69579. this._toneMappingEnabled = false;
  69580. this._contrast = 1.0;
  69581. /**
  69582. * Vignette stretch size.
  69583. */
  69584. this.vignetteStretch = 0;
  69585. /**
  69586. * Vignette centre X Offset.
  69587. */
  69588. this.vignetteCentreX = 0;
  69589. /**
  69590. * Vignette centre Y Offset.
  69591. */
  69592. this.vignetteCentreY = 0;
  69593. /**
  69594. * Vignette weight or intensity of the vignette effect.
  69595. */
  69596. this.vignetteWeight = 1.5;
  69597. /**
  69598. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  69599. * if vignetteEnabled is set to true.
  69600. */
  69601. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  69602. /**
  69603. * Camera field of view used by the Vignette effect.
  69604. */
  69605. this.vignetteCameraFov = 0.5;
  69606. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  69607. this._vignetteEnabled = false;
  69608. this._applyByPostProcess = false;
  69609. /**
  69610. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  69611. * @type {BABYLON.Observable}
  69612. */
  69613. this.onUpdateParameters = new BABYLON.Observable();
  69614. }
  69615. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  69616. /**
  69617. * Gets wether the color curves effect is enabled.
  69618. */
  69619. get: function () {
  69620. return this._colorCurvesEnabled;
  69621. },
  69622. /**
  69623. * Sets wether the color curves effect is enabled.
  69624. */
  69625. set: function (value) {
  69626. if (this._colorCurvesEnabled === value) {
  69627. return;
  69628. }
  69629. this._colorCurvesEnabled = value;
  69630. this._updateParameters();
  69631. },
  69632. enumerable: true,
  69633. configurable: true
  69634. });
  69635. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  69636. /**
  69637. * Gets wether the color grading effect is enabled.
  69638. */
  69639. get: function () {
  69640. return this._colorGradingEnabled;
  69641. },
  69642. /**
  69643. * Sets wether the color grading effect is enabled.
  69644. */
  69645. set: function (value) {
  69646. if (this._colorGradingEnabled === value) {
  69647. return;
  69648. }
  69649. this._colorGradingEnabled = value;
  69650. this._updateParameters();
  69651. },
  69652. enumerable: true,
  69653. configurable: true
  69654. });
  69655. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  69656. /**
  69657. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  69658. */
  69659. get: function () {
  69660. return this._colorGradingWithGreenDepth;
  69661. },
  69662. /**
  69663. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  69664. */
  69665. set: function (value) {
  69666. if (this._colorGradingWithGreenDepth === value) {
  69667. return;
  69668. }
  69669. this._colorGradingWithGreenDepth = value;
  69670. this._updateParameters();
  69671. },
  69672. enumerable: true,
  69673. configurable: true
  69674. });
  69675. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  69676. /**
  69677. * Gets wether the color grading texture contains BGR values.
  69678. */
  69679. get: function () {
  69680. return this._colorGradingBGR;
  69681. },
  69682. /**
  69683. * Sets wether the color grading texture contains BGR values.
  69684. */
  69685. set: function (value) {
  69686. if (this._colorGradingBGR === value) {
  69687. return;
  69688. }
  69689. this._colorGradingBGR = value;
  69690. this._updateParameters();
  69691. },
  69692. enumerable: true,
  69693. configurable: true
  69694. });
  69695. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  69696. /**
  69697. * Gets the Exposure used in the effect.
  69698. */
  69699. get: function () {
  69700. return this._exposure;
  69701. },
  69702. /**
  69703. * Sets the Exposure used in the effect.
  69704. */
  69705. set: function (value) {
  69706. if (this._exposure === value) {
  69707. return;
  69708. }
  69709. this._exposure = value;
  69710. this._updateParameters();
  69711. },
  69712. enumerable: true,
  69713. configurable: true
  69714. });
  69715. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  69716. /**
  69717. * Gets wether the tone mapping effect is enabled.
  69718. */
  69719. get: function () {
  69720. return this._toneMappingEnabled;
  69721. },
  69722. /**
  69723. * Sets wether the tone mapping effect is enabled.
  69724. */
  69725. set: function (value) {
  69726. if (this._toneMappingEnabled === value) {
  69727. return;
  69728. }
  69729. this._toneMappingEnabled = value;
  69730. this._updateParameters();
  69731. },
  69732. enumerable: true,
  69733. configurable: true
  69734. });
  69735. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  69736. /**
  69737. * Gets the contrast used in the effect.
  69738. */
  69739. get: function () {
  69740. return this._contrast;
  69741. },
  69742. /**
  69743. * Sets the contrast used in the effect.
  69744. */
  69745. set: function (value) {
  69746. if (this._contrast === value) {
  69747. return;
  69748. }
  69749. this._contrast = value;
  69750. this._updateParameters();
  69751. },
  69752. enumerable: true,
  69753. configurable: true
  69754. });
  69755. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  69756. /**
  69757. * Gets the vignette blend mode allowing different kind of effect.
  69758. */
  69759. get: function () {
  69760. return this._vignetteBlendMode;
  69761. },
  69762. /**
  69763. * Sets the vignette blend mode allowing different kind of effect.
  69764. */
  69765. set: function (value) {
  69766. if (this._vignetteBlendMode === value) {
  69767. return;
  69768. }
  69769. this._vignetteBlendMode = value;
  69770. this._updateParameters();
  69771. },
  69772. enumerable: true,
  69773. configurable: true
  69774. });
  69775. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  69776. /**
  69777. * Gets wether the vignette effect is enabled.
  69778. */
  69779. get: function () {
  69780. return this._vignetteEnabled;
  69781. },
  69782. /**
  69783. * Sets wether the vignette effect is enabled.
  69784. */
  69785. set: function (value) {
  69786. if (this._vignetteEnabled === value) {
  69787. return;
  69788. }
  69789. this._vignetteEnabled = value;
  69790. this._updateParameters();
  69791. },
  69792. enumerable: true,
  69793. configurable: true
  69794. });
  69795. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  69796. /**
  69797. * Gets wether the image processing is applied through a post process or not.
  69798. */
  69799. get: function () {
  69800. return this._applyByPostProcess;
  69801. },
  69802. /**
  69803. * Sets wether the image processing is applied through a post process or not.
  69804. */
  69805. set: function (value) {
  69806. if (this._applyByPostProcess === value) {
  69807. return;
  69808. }
  69809. this._applyByPostProcess = value;
  69810. this._updateParameters();
  69811. },
  69812. enumerable: true,
  69813. configurable: true
  69814. });
  69815. /**
  69816. * Method called each time the image processing information changes requires to recompile the effect.
  69817. */
  69818. ImageProcessingConfiguration.prototype._updateParameters = function () {
  69819. this.onUpdateParameters.notifyObservers(this);
  69820. };
  69821. ImageProcessingConfiguration.prototype.getClassName = function () {
  69822. return "ImageProcessingConfiguration";
  69823. };
  69824. /**
  69825. * Prepare the list of uniforms associated with the Image Processing effects.
  69826. * @param uniformsList The list of uniforms used in the effect
  69827. * @param defines the list of defines currently in use
  69828. */
  69829. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  69830. if (defines.EXPOSURE) {
  69831. uniforms.push("exposureLinear");
  69832. }
  69833. if (defines.CONTRAST) {
  69834. uniforms.push("contrast");
  69835. }
  69836. if (defines.COLORGRADING) {
  69837. uniforms.push("colorTransformSettings");
  69838. }
  69839. if (defines.VIGNETTE) {
  69840. uniforms.push("vInverseScreenSize");
  69841. uniforms.push("vignetteSettings1");
  69842. uniforms.push("vignetteSettings2");
  69843. }
  69844. if (defines.COLORCURVES) {
  69845. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  69846. }
  69847. };
  69848. /**
  69849. * Prepare the list of samplers associated with the Image Processing effects.
  69850. * @param uniformsList The list of uniforms used in the effect
  69851. * @param defines the list of defines currently in use
  69852. */
  69853. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  69854. if (defines.COLORGRADING) {
  69855. samplersList.push("txColorTransform");
  69856. }
  69857. };
  69858. /**
  69859. * Prepare the list of defines associated to the shader.
  69860. * @param defines the list of defines to complete
  69861. */
  69862. ImageProcessingConfiguration.prototype.prepareDefines = function (defines) {
  69863. defines.VIGNETTE = this.vignetteEnabled;
  69864. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  69865. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  69866. defines.TONEMAPPING = this.toneMappingEnabled;
  69867. defines.CONTRAST = (this.contrast !== 1.0);
  69868. defines.EXPOSURE = (this.exposure !== 1.0);
  69869. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  69870. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  69871. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  69872. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  69873. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  69874. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  69875. };
  69876. /**
  69877. * Returns true if all the image processing information are ready.
  69878. */
  69879. ImageProcessingConfiguration.prototype.isReady = function () {
  69880. // Color Grading texure can not be none blocking.
  69881. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  69882. };
  69883. /**
  69884. * Binds the image processing to the shader.
  69885. * @param effect The effect to bind to
  69886. */
  69887. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  69888. if (aspectRatio === void 0) { aspectRatio = 1; }
  69889. // Color Curves
  69890. if (this._colorCurvesEnabled) {
  69891. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  69892. }
  69893. // Vignette
  69894. if (this._vignetteEnabled) {
  69895. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  69896. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  69897. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  69898. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  69899. var vignetteScaleX = vignetteScaleY * aspectRatio;
  69900. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  69901. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  69902. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  69903. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  69904. var vignettePower = -2.0 * this.vignetteWeight;
  69905. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  69906. }
  69907. // Exposure
  69908. effect.setFloat("exposureLinear", this.exposure);
  69909. // Contrast
  69910. effect.setFloat("contrast", this.contrast);
  69911. // Color transform settings
  69912. if (this.colorGradingTexture) {
  69913. effect.setTexture("txColorTransform", this.colorGradingTexture);
  69914. var textureSize = this.colorGradingTexture.getSize().height;
  69915. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  69916. 0.5 / textureSize, // textureOffset
  69917. textureSize, // textureSize
  69918. this.colorGradingTexture.level // weight
  69919. );
  69920. }
  69921. };
  69922. /**
  69923. * Clones the current image processing instance.
  69924. * @return The cloned image processing
  69925. */
  69926. ImageProcessingConfiguration.prototype.clone = function () {
  69927. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  69928. };
  69929. /**
  69930. * Serializes the current image processing instance to a json representation.
  69931. * @return a JSON representation
  69932. */
  69933. ImageProcessingConfiguration.prototype.serialize = function () {
  69934. return BABYLON.SerializationHelper.Serialize(this);
  69935. };
  69936. /**
  69937. * Parses the image processing from a json representation.
  69938. * @param source the JSON source to parse
  69939. * @return The parsed image processing
  69940. */
  69941. ImageProcessingConfiguration.Parse = function (source) {
  69942. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  69943. };
  69944. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  69945. /**
  69946. * Used to apply the vignette as a mix with the pixel color.
  69947. */
  69948. get: function () {
  69949. return this._VIGNETTEMODE_MULTIPLY;
  69950. },
  69951. enumerable: true,
  69952. configurable: true
  69953. });
  69954. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  69955. /**
  69956. * Used to apply the vignette as a replacement of the pixel color.
  69957. */
  69958. get: function () {
  69959. return this._VIGNETTEMODE_OPAQUE;
  69960. },
  69961. enumerable: true,
  69962. configurable: true
  69963. });
  69964. // Static constants associated to the image processing.
  69965. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  69966. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  69967. __decorate([
  69968. BABYLON.serializeAsColorCurves()
  69969. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  69970. __decorate([
  69971. BABYLON.serialize()
  69972. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  69973. __decorate([
  69974. BABYLON.serializeAsTexture()
  69975. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  69976. __decorate([
  69977. BABYLON.serialize()
  69978. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  69979. __decorate([
  69980. BABYLON.serialize()
  69981. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  69982. __decorate([
  69983. BABYLON.serialize()
  69984. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  69985. __decorate([
  69986. BABYLON.serialize()
  69987. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  69988. __decorate([
  69989. BABYLON.serialize()
  69990. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  69991. __decorate([
  69992. BABYLON.serialize()
  69993. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  69994. __decorate([
  69995. BABYLON.serialize()
  69996. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  69997. __decorate([
  69998. BABYLON.serialize()
  69999. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  70000. __decorate([
  70001. BABYLON.serialize()
  70002. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  70003. __decorate([
  70004. BABYLON.serialize()
  70005. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  70006. __decorate([
  70007. BABYLON.serializeAsColor4()
  70008. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  70009. __decorate([
  70010. BABYLON.serialize()
  70011. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  70012. __decorate([
  70013. BABYLON.serialize()
  70014. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  70015. __decorate([
  70016. BABYLON.serialize()
  70017. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  70018. __decorate([
  70019. BABYLON.serialize()
  70020. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  70021. return ImageProcessingConfiguration;
  70022. }());
  70023. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  70024. })(BABYLON || (BABYLON = {}));
  70025. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  70026. var BABYLON;
  70027. (function (BABYLON) {
  70028. var serializedGeometries = [];
  70029. var serializeGeometry = function (geometry, serializationGeometries) {
  70030. if (serializedGeometries[geometry.id]) {
  70031. return;
  70032. }
  70033. if (geometry.doNotSerialize) {
  70034. return;
  70035. }
  70036. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  70037. serializationGeometries.boxes.push(geometry.serialize());
  70038. }
  70039. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  70040. serializationGeometries.spheres.push(geometry.serialize());
  70041. }
  70042. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  70043. serializationGeometries.cylinders.push(geometry.serialize());
  70044. }
  70045. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  70046. serializationGeometries.toruses.push(geometry.serialize());
  70047. }
  70048. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  70049. serializationGeometries.grounds.push(geometry.serialize());
  70050. }
  70051. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  70052. serializationGeometries.planes.push(geometry.serialize());
  70053. }
  70054. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  70055. serializationGeometries.torusKnots.push(geometry.serialize());
  70056. }
  70057. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  70058. throw new Error("Unknown primitive type");
  70059. }
  70060. else {
  70061. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  70062. }
  70063. serializedGeometries[geometry.id] = true;
  70064. };
  70065. var serializeMesh = function (mesh, serializationScene) {
  70066. var serializationObject = {};
  70067. // Geometry
  70068. var geometry = mesh._geometry;
  70069. if (geometry) {
  70070. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  70071. // 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
  70072. serializeGeometry(geometry, serializationScene.geometries);
  70073. }
  70074. }
  70075. // Custom
  70076. if (mesh.serialize) {
  70077. mesh.serialize(serializationObject);
  70078. }
  70079. return serializationObject;
  70080. };
  70081. var finalizeSingleMesh = function (mesh, serializationObject) {
  70082. //only works if the mesh is already loaded
  70083. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  70084. //serialize material
  70085. if (mesh.material) {
  70086. if (mesh.material instanceof BABYLON.StandardMaterial) {
  70087. serializationObject.materials = serializationObject.materials || [];
  70088. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  70089. serializationObject.materials.push(mesh.material.serialize());
  70090. }
  70091. }
  70092. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  70093. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  70094. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  70095. serializationObject.multiMaterials.push(mesh.material.serialize());
  70096. }
  70097. }
  70098. }
  70099. //serialize geometry
  70100. var geometry = mesh._geometry;
  70101. if (geometry) {
  70102. if (!serializationObject.geometries) {
  70103. serializationObject.geometries = {};
  70104. serializationObject.geometries.boxes = [];
  70105. serializationObject.geometries.spheres = [];
  70106. serializationObject.geometries.cylinders = [];
  70107. serializationObject.geometries.toruses = [];
  70108. serializationObject.geometries.grounds = [];
  70109. serializationObject.geometries.planes = [];
  70110. serializationObject.geometries.torusKnots = [];
  70111. serializationObject.geometries.vertexData = [];
  70112. }
  70113. serializeGeometry(geometry, serializationObject.geometries);
  70114. }
  70115. // Skeletons
  70116. if (mesh.skeleton) {
  70117. serializationObject.skeletons = serializationObject.skeletons || [];
  70118. serializationObject.skeletons.push(mesh.skeleton.serialize());
  70119. }
  70120. //serialize the actual mesh
  70121. serializationObject.meshes = serializationObject.meshes || [];
  70122. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  70123. }
  70124. };
  70125. var SceneSerializer = (function () {
  70126. function SceneSerializer() {
  70127. }
  70128. SceneSerializer.ClearCache = function () {
  70129. serializedGeometries = [];
  70130. };
  70131. SceneSerializer.Serialize = function (scene) {
  70132. var serializationObject = {};
  70133. SceneSerializer.ClearCache();
  70134. // Scene
  70135. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  70136. serializationObject.autoClear = scene.autoClear;
  70137. serializationObject.clearColor = scene.clearColor.asArray();
  70138. serializationObject.ambientColor = scene.ambientColor.asArray();
  70139. serializationObject.gravity = scene.gravity.asArray();
  70140. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  70141. serializationObject.workerCollisions = scene.workerCollisions;
  70142. // Fog
  70143. if (scene.fogMode && scene.fogMode !== 0) {
  70144. serializationObject.fogMode = scene.fogMode;
  70145. serializationObject.fogColor = scene.fogColor.asArray();
  70146. serializationObject.fogStart = scene.fogStart;
  70147. serializationObject.fogEnd = scene.fogEnd;
  70148. serializationObject.fogDensity = scene.fogDensity;
  70149. }
  70150. //Physics
  70151. if (scene.isPhysicsEnabled()) {
  70152. serializationObject.physicsEnabled = true;
  70153. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  70154. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  70155. }
  70156. // Metadata
  70157. if (scene.metadata) {
  70158. serializationObject.metadata = scene.metadata;
  70159. }
  70160. // Morph targets
  70161. serializationObject.morphTargetManagers = [];
  70162. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  70163. var abstractMesh = _a[_i];
  70164. var manager = abstractMesh.morphTargetManager;
  70165. if (manager) {
  70166. serializationObject.morphTargetManagers.push(manager.serialize());
  70167. }
  70168. }
  70169. // Lights
  70170. serializationObject.lights = [];
  70171. var index;
  70172. var light;
  70173. for (index = 0; index < scene.lights.length; index++) {
  70174. light = scene.lights[index];
  70175. if (!light.doNotSerialize) {
  70176. serializationObject.lights.push(light.serialize());
  70177. }
  70178. }
  70179. // Cameras
  70180. serializationObject.cameras = [];
  70181. for (index = 0; index < scene.cameras.length; index++) {
  70182. var camera = scene.cameras[index];
  70183. if (!camera.doNotSerialize) {
  70184. serializationObject.cameras.push(camera.serialize());
  70185. }
  70186. }
  70187. if (scene.activeCamera) {
  70188. serializationObject.activeCameraID = scene.activeCamera.id;
  70189. }
  70190. // Animations
  70191. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  70192. // Materials
  70193. serializationObject.materials = [];
  70194. serializationObject.multiMaterials = [];
  70195. var material;
  70196. for (index = 0; index < scene.materials.length; index++) {
  70197. material = scene.materials[index];
  70198. if (!material.doNotSerialize) {
  70199. serializationObject.materials.push(material.serialize());
  70200. }
  70201. }
  70202. // MultiMaterials
  70203. serializationObject.multiMaterials = [];
  70204. for (index = 0; index < scene.multiMaterials.length; index++) {
  70205. var multiMaterial = scene.multiMaterials[index];
  70206. serializationObject.multiMaterials.push(multiMaterial.serialize());
  70207. }
  70208. // Skeletons
  70209. serializationObject.skeletons = [];
  70210. for (index = 0; index < scene.skeletons.length; index++) {
  70211. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  70212. }
  70213. // Geometries
  70214. serializationObject.geometries = {};
  70215. serializationObject.geometries.boxes = [];
  70216. serializationObject.geometries.spheres = [];
  70217. serializationObject.geometries.cylinders = [];
  70218. serializationObject.geometries.toruses = [];
  70219. serializationObject.geometries.grounds = [];
  70220. serializationObject.geometries.planes = [];
  70221. serializationObject.geometries.torusKnots = [];
  70222. serializationObject.geometries.vertexData = [];
  70223. serializedGeometries = [];
  70224. var geometries = scene.getGeometries();
  70225. for (index = 0; index < geometries.length; index++) {
  70226. var geometry = geometries[index];
  70227. if (geometry.isReady()) {
  70228. serializeGeometry(geometry, serializationObject.geometries);
  70229. }
  70230. }
  70231. // Meshes
  70232. serializationObject.meshes = [];
  70233. for (index = 0; index < scene.meshes.length; index++) {
  70234. var abstractMesh = scene.meshes[index];
  70235. if (abstractMesh instanceof BABYLON.Mesh) {
  70236. var mesh = abstractMesh;
  70237. if (!mesh.doNotSerialize) {
  70238. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  70239. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  70240. }
  70241. }
  70242. }
  70243. }
  70244. // Particles Systems
  70245. serializationObject.particleSystems = [];
  70246. for (index = 0; index < scene.particleSystems.length; index++) {
  70247. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  70248. }
  70249. // Lens flares
  70250. serializationObject.lensFlareSystems = [];
  70251. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  70252. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  70253. }
  70254. // Shadows
  70255. serializationObject.shadowGenerators = [];
  70256. for (index = 0; index < scene.lights.length; index++) {
  70257. light = scene.lights[index];
  70258. var shadowGenerator = light.getShadowGenerator();
  70259. if (shadowGenerator) {
  70260. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  70261. }
  70262. }
  70263. // Action Manager
  70264. if (scene.actionManager) {
  70265. serializationObject.actions = scene.actionManager.serialize("scene");
  70266. }
  70267. // Audio
  70268. serializationObject.sounds = [];
  70269. for (index = 0; index < scene.soundTracks.length; index++) {
  70270. var soundtrack = scene.soundTracks[index];
  70271. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  70272. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  70273. }
  70274. }
  70275. return serializationObject;
  70276. };
  70277. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  70278. if (withParents === void 0) { withParents = false; }
  70279. if (withChildren === void 0) { withChildren = false; }
  70280. var serializationObject = {};
  70281. SceneSerializer.ClearCache();
  70282. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  70283. if (withParents || withChildren) {
  70284. //deliberate for loop! not for each, appended should be processed as well.
  70285. for (var i = 0; i < toSerialize.length; ++i) {
  70286. if (withChildren) {
  70287. toSerialize[i].getDescendants().forEach(function (node) {
  70288. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  70289. toSerialize.push(node);
  70290. }
  70291. });
  70292. }
  70293. //make sure the array doesn't contain the object already
  70294. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  70295. toSerialize.push(toSerialize[i].parent);
  70296. }
  70297. }
  70298. }
  70299. toSerialize.forEach(function (mesh) {
  70300. finalizeSingleMesh(mesh, serializationObject);
  70301. });
  70302. return serializationObject;
  70303. };
  70304. return SceneSerializer;
  70305. }());
  70306. BABYLON.SceneSerializer = SceneSerializer;
  70307. })(BABYLON || (BABYLON = {}));
  70308. //# sourceMappingURL=babylon.sceneSerializer.js.map
  70309. var BABYLON;
  70310. (function (BABYLON) {
  70311. var ReflectionProbe = (function () {
  70312. function ReflectionProbe(name, size, scene, generateMipMaps) {
  70313. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70314. var _this = this;
  70315. this.name = name;
  70316. this._viewMatrix = BABYLON.Matrix.Identity();
  70317. this._target = BABYLON.Vector3.Zero();
  70318. this._add = BABYLON.Vector3.Zero();
  70319. this.invertYAxis = false;
  70320. this.position = BABYLON.Vector3.Zero();
  70321. this._scene = scene;
  70322. this._scene.reflectionProbes.push(this);
  70323. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  70324. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  70325. switch (faceIndex) {
  70326. case 0:
  70327. _this._add.copyFromFloats(1, 0, 0);
  70328. break;
  70329. case 1:
  70330. _this._add.copyFromFloats(-1, 0, 0);
  70331. break;
  70332. case 2:
  70333. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  70334. break;
  70335. case 3:
  70336. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  70337. break;
  70338. case 4:
  70339. _this._add.copyFromFloats(0, 0, 1);
  70340. break;
  70341. case 5:
  70342. _this._add.copyFromFloats(0, 0, -1);
  70343. break;
  70344. }
  70345. if (_this._attachedMesh) {
  70346. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  70347. }
  70348. _this.position.addToRef(_this._add, _this._target);
  70349. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  70350. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  70351. });
  70352. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  70353. scene.updateTransformMatrix(true);
  70354. });
  70355. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  70356. }
  70357. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  70358. get: function () {
  70359. return this._renderTargetTexture.samples;
  70360. },
  70361. set: function (value) {
  70362. this._renderTargetTexture.samples = value;
  70363. },
  70364. enumerable: true,
  70365. configurable: true
  70366. });
  70367. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  70368. get: function () {
  70369. return this._renderTargetTexture.refreshRate;
  70370. },
  70371. set: function (value) {
  70372. this._renderTargetTexture.refreshRate = value;
  70373. },
  70374. enumerable: true,
  70375. configurable: true
  70376. });
  70377. ReflectionProbe.prototype.getScene = function () {
  70378. return this._scene;
  70379. };
  70380. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  70381. get: function () {
  70382. return this._renderTargetTexture;
  70383. },
  70384. enumerable: true,
  70385. configurable: true
  70386. });
  70387. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  70388. get: function () {
  70389. return this._renderTargetTexture.renderList;
  70390. },
  70391. enumerable: true,
  70392. configurable: true
  70393. });
  70394. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  70395. this._attachedMesh = mesh;
  70396. };
  70397. /**
  70398. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  70399. *
  70400. * @param renderingGroupId The rendering group id corresponding to its index
  70401. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  70402. */
  70403. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  70404. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  70405. };
  70406. ReflectionProbe.prototype.dispose = function () {
  70407. var index = this._scene.reflectionProbes.indexOf(this);
  70408. if (index !== -1) {
  70409. // Remove from the scene if found
  70410. this._scene.reflectionProbes.splice(index, 1);
  70411. }
  70412. if (this._renderTargetTexture) {
  70413. this._renderTargetTexture.dispose();
  70414. this._renderTargetTexture = null;
  70415. }
  70416. };
  70417. return ReflectionProbe;
  70418. }());
  70419. BABYLON.ReflectionProbe = ReflectionProbe;
  70420. })(BABYLON || (BABYLON = {}));
  70421. //# sourceMappingURL=babylon.reflectionProbe.js.map
  70422. var BABYLON;
  70423. (function (BABYLON) {
  70424. var Layer = (function () {
  70425. function Layer(name, imgUrl, scene, isBackground, color) {
  70426. this.name = name;
  70427. this.scale = new BABYLON.Vector2(1, 1);
  70428. this.offset = new BABYLON.Vector2(0, 0);
  70429. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  70430. this.layerMask = 0x0FFFFFFF;
  70431. this._vertexBuffers = {};
  70432. // Events
  70433. /**
  70434. * An event triggered when the layer is disposed.
  70435. * @type {BABYLON.Observable}
  70436. */
  70437. this.onDisposeObservable = new BABYLON.Observable();
  70438. /**
  70439. * An event triggered before rendering the scene
  70440. * @type {BABYLON.Observable}
  70441. */
  70442. this.onBeforeRenderObservable = new BABYLON.Observable();
  70443. /**
  70444. * An event triggered after rendering the scene
  70445. * @type {BABYLON.Observable}
  70446. */
  70447. this.onAfterRenderObservable = new BABYLON.Observable();
  70448. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  70449. this.isBackground = isBackground === undefined ? true : isBackground;
  70450. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  70451. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  70452. this._scene.layers.push(this);
  70453. var engine = this._scene.getEngine();
  70454. // VBO
  70455. var vertices = [];
  70456. vertices.push(1, 1);
  70457. vertices.push(-1, 1);
  70458. vertices.push(-1, -1);
  70459. vertices.push(1, -1);
  70460. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70461. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  70462. this._createIndexBuffer();
  70463. // Effects
  70464. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  70465. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  70466. }
  70467. Object.defineProperty(Layer.prototype, "onDispose", {
  70468. set: function (callback) {
  70469. if (this._onDisposeObserver) {
  70470. this.onDisposeObservable.remove(this._onDisposeObserver);
  70471. }
  70472. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  70473. },
  70474. enumerable: true,
  70475. configurable: true
  70476. });
  70477. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  70478. set: function (callback) {
  70479. if (this._onBeforeRenderObserver) {
  70480. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  70481. }
  70482. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  70483. },
  70484. enumerable: true,
  70485. configurable: true
  70486. });
  70487. Object.defineProperty(Layer.prototype, "onAfterRender", {
  70488. set: function (callback) {
  70489. if (this._onAfterRenderObserver) {
  70490. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  70491. }
  70492. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  70493. },
  70494. enumerable: true,
  70495. configurable: true
  70496. });
  70497. Layer.prototype._createIndexBuffer = function () {
  70498. var engine = this._scene.getEngine();
  70499. // Indices
  70500. var indices = [];
  70501. indices.push(0);
  70502. indices.push(1);
  70503. indices.push(2);
  70504. indices.push(0);
  70505. indices.push(2);
  70506. indices.push(3);
  70507. this._indexBuffer = engine.createIndexBuffer(indices);
  70508. };
  70509. Layer.prototype._rebuild = function () {
  70510. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  70511. this._createIndexBuffer();
  70512. };
  70513. Layer.prototype.render = function () {
  70514. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  70515. // Check
  70516. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  70517. return;
  70518. var engine = this._scene.getEngine();
  70519. this.onBeforeRenderObservable.notifyObservers(this);
  70520. // Render
  70521. engine.enableEffect(currentEffect);
  70522. engine.setState(false);
  70523. // Texture
  70524. currentEffect.setTexture("textureSampler", this.texture);
  70525. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  70526. // Color
  70527. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  70528. // Scale / offset
  70529. currentEffect.setVector2("offset", this.offset);
  70530. currentEffect.setVector2("scale", this.scale);
  70531. // VBOs
  70532. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  70533. // Draw order
  70534. if (!this.alphaTest) {
  70535. engine.setAlphaMode(this.alphaBlendingMode);
  70536. engine.draw(true, 0, 6);
  70537. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  70538. }
  70539. else {
  70540. engine.draw(true, 0, 6);
  70541. }
  70542. this.onAfterRenderObservable.notifyObservers(this);
  70543. };
  70544. Layer.prototype.dispose = function () {
  70545. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70546. if (vertexBuffer) {
  70547. vertexBuffer.dispose();
  70548. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70549. }
  70550. if (this._indexBuffer) {
  70551. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  70552. this._indexBuffer = null;
  70553. }
  70554. if (this.texture) {
  70555. this.texture.dispose();
  70556. this.texture = null;
  70557. }
  70558. // Remove from scene
  70559. var index = this._scene.layers.indexOf(this);
  70560. this._scene.layers.splice(index, 1);
  70561. // Callback
  70562. this.onDisposeObservable.notifyObservers(this);
  70563. this.onDisposeObservable.clear();
  70564. this.onAfterRenderObservable.clear();
  70565. this.onBeforeRenderObservable.clear();
  70566. };
  70567. return Layer;
  70568. }());
  70569. BABYLON.Layer = Layer;
  70570. })(BABYLON || (BABYLON = {}));
  70571. //# sourceMappingURL=babylon.layer.js.map
  70572. var BABYLON;
  70573. (function (BABYLON) {
  70574. var TextureTools = (function () {
  70575. function TextureTools() {
  70576. }
  70577. /**
  70578. * Uses the GPU to create a copy texture rescaled at a given size
  70579. * @param texture Texture to copy from
  70580. * @param width Desired width
  70581. * @param height Desired height
  70582. * @return Generated texture
  70583. */
  70584. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  70585. if (useBilinearMode === void 0) { useBilinearMode = true; }
  70586. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  70587. var scene = texture.getScene();
  70588. var engine = scene.getEngine();
  70589. rtt.wrapU = texture.wrapU;
  70590. rtt.wrapV = texture.wrapV;
  70591. rtt.uOffset = texture.uOffset;
  70592. rtt.vOffset = texture.vOffset;
  70593. rtt.uScale = texture.uScale;
  70594. rtt.vScale = texture.vScale;
  70595. rtt.uAng = texture.uAng;
  70596. rtt.vAng = texture.vAng;
  70597. rtt.wAng = texture.wAng;
  70598. rtt.coordinatesIndex = texture.coordinatesIndex;
  70599. rtt.level = texture.level;
  70600. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  70601. rtt._texture.isReady = false;
  70602. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70603. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70604. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70605. passPostProcess.getEffect().executeWhenCompiled(function () {
  70606. passPostProcess.onApply = function (effect) {
  70607. effect.setTexture("textureSampler", texture);
  70608. };
  70609. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  70610. engine.unBindFramebuffer(rtt.getInternalTexture());
  70611. rtt.disposeFramebufferObjects();
  70612. passPostProcess.dispose();
  70613. rtt._texture.isReady = true;
  70614. });
  70615. return rtt;
  70616. };
  70617. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  70618. if (!scene._environmentBRDFTexture) {
  70619. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70620. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70621. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70622. scene._environmentBRDFTexture = texture;
  70623. }
  70624. return scene._environmentBRDFTexture;
  70625. };
  70626. 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=";
  70627. return TextureTools;
  70628. }());
  70629. BABYLON.TextureTools = TextureTools;
  70630. })(BABYLON || (BABYLON = {}));
  70631. //# sourceMappingURL=babylon.textureTools.js.map
  70632. var BABYLON;
  70633. (function (BABYLON) {
  70634. var FramingBehavior = (function () {
  70635. function FramingBehavior() {
  70636. this._mode = FramingBehavior.FitFrustumSidesMode;
  70637. this._radiusScale = 1.0;
  70638. this._positionScale = 0.5;
  70639. this._defaultElevation = 0.3;
  70640. this._elevationReturnTime = 1500;
  70641. this._elevationReturnWaitTime = 1000;
  70642. this._zoomStopsAnimation = false;
  70643. this._framingTime = 1500;
  70644. this._isPointerDown = false;
  70645. this._lastFrameTime = null;
  70646. this._lastInteractionTime = -Infinity;
  70647. // Framing control
  70648. this._animatables = new Array();
  70649. this._betaIsAnimating = false;
  70650. this._lastFrameRadius = 0;
  70651. }
  70652. Object.defineProperty(FramingBehavior.prototype, "name", {
  70653. get: function () {
  70654. return "Framing";
  70655. },
  70656. enumerable: true,
  70657. configurable: true
  70658. });
  70659. Object.defineProperty(FramingBehavior.prototype, "mode", {
  70660. /**
  70661. * Gets current mode used by the behavior.
  70662. */
  70663. get: function () {
  70664. return this._mode;
  70665. },
  70666. /**
  70667. * Sets the current mode used by the behavior
  70668. */
  70669. set: function (mode) {
  70670. this._mode = mode;
  70671. },
  70672. enumerable: true,
  70673. configurable: true
  70674. });
  70675. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  70676. /**
  70677. * Gets the scale applied to the radius
  70678. */
  70679. get: function () {
  70680. return this._radiusScale;
  70681. },
  70682. /**
  70683. * Sets the scale applied to the radius (1 by default)
  70684. */
  70685. set: function (radius) {
  70686. this._radiusScale = radius;
  70687. },
  70688. enumerable: true,
  70689. configurable: true
  70690. });
  70691. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  70692. /**
  70693. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  70694. */
  70695. get: function () {
  70696. return this._positionScale;
  70697. },
  70698. /**
  70699. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  70700. */
  70701. set: function (scale) {
  70702. this._positionScale = scale;
  70703. },
  70704. enumerable: true,
  70705. configurable: true
  70706. });
  70707. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  70708. /**
  70709. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  70710. * behaviour is triggered, in radians.
  70711. */
  70712. get: function () {
  70713. return this._defaultElevation;
  70714. },
  70715. /**
  70716. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  70717. * behaviour is triggered, in radians.
  70718. */
  70719. set: function (elevation) {
  70720. this._defaultElevation = elevation;
  70721. },
  70722. enumerable: true,
  70723. configurable: true
  70724. });
  70725. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  70726. /**
  70727. * Gets the time (in milliseconds) taken to return to the default beta position.
  70728. * Negative value indicates camera should not return to default.
  70729. */
  70730. get: function () {
  70731. return this._elevationReturnTime;
  70732. },
  70733. /**
  70734. * Sets the time (in milliseconds) taken to return to the default beta position.
  70735. * Negative value indicates camera should not return to default.
  70736. */
  70737. set: function (speed) {
  70738. this._elevationReturnTime = speed;
  70739. },
  70740. enumerable: true,
  70741. configurable: true
  70742. });
  70743. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  70744. /**
  70745. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  70746. */
  70747. get: function () {
  70748. return this._elevationReturnWaitTime;
  70749. },
  70750. /**
  70751. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  70752. */
  70753. set: function (time) {
  70754. this._elevationReturnWaitTime = time;
  70755. },
  70756. enumerable: true,
  70757. configurable: true
  70758. });
  70759. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  70760. /**
  70761. * Gets the flag that indicates if user zooming should stop animation.
  70762. */
  70763. get: function () {
  70764. return this._zoomStopsAnimation;
  70765. },
  70766. /**
  70767. * Sets the flag that indicates if user zooming should stop animation.
  70768. */
  70769. set: function (flag) {
  70770. this._zoomStopsAnimation = flag;
  70771. },
  70772. enumerable: true,
  70773. configurable: true
  70774. });
  70775. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  70776. /**
  70777. * Gets the transition time when framing the mesh, in milliseconds
  70778. */
  70779. get: function () {
  70780. return this._framingTime;
  70781. },
  70782. /**
  70783. * Sets the transition time when framing the mesh, in milliseconds
  70784. */
  70785. set: function (time) {
  70786. this._framingTime = time;
  70787. },
  70788. enumerable: true,
  70789. configurable: true
  70790. });
  70791. FramingBehavior.prototype.attach = function (camera) {
  70792. var _this = this;
  70793. this._attachedCamera = camera;
  70794. var scene = this._attachedCamera.getScene();
  70795. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  70796. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  70797. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  70798. _this._isPointerDown = true;
  70799. return;
  70800. }
  70801. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  70802. _this._isPointerDown = false;
  70803. }
  70804. });
  70805. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  70806. if (mesh) {
  70807. _this.zoomOnMesh(mesh);
  70808. }
  70809. });
  70810. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  70811. // Stop the animation if there is user interaction and the animation should stop for this interaction
  70812. _this._applyUserInteraction();
  70813. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  70814. // back to the default position after a given timeout
  70815. _this._maintainCameraAboveGround();
  70816. });
  70817. };
  70818. FramingBehavior.prototype.detach = function () {
  70819. var scene = this._attachedCamera.getScene();
  70820. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  70821. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  70822. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  70823. this._attachedCamera = null;
  70824. };
  70825. /**
  70826. * Targets the given mesh and updates zoom level accordingly.
  70827. * @param mesh The mesh to target.
  70828. * @param radius Optional. If a cached radius position already exists, overrides default.
  70829. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  70830. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  70831. * @param onAnimationEnd Callback triggered at the end of the framing animation
  70832. */
  70833. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  70834. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  70835. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  70836. mesh.computeWorldMatrix(true);
  70837. var boundingBox = mesh.getBoundingInfo().boundingBox;
  70838. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  70839. };
  70840. /**
  70841. * Targets the given mesh and updates zoom level accordingly.
  70842. * @param mesh The mesh to target.
  70843. * @param radius Optional. If a cached radius position already exists, overrides default.
  70844. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  70845. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  70846. * @param onAnimationEnd Callback triggered at the end of the framing animation
  70847. */
  70848. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  70849. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  70850. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  70851. var zoomTarget;
  70852. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  70853. var bottom = minimumWorld.y;
  70854. var top = maximumWorld.y;
  70855. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  70856. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  70857. if (focusOnOriginXZ) {
  70858. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  70859. }
  70860. else {
  70861. var centerWorld = minimumWorld.add(radiusWorld);
  70862. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  70863. }
  70864. if (!this._vectorTransition) {
  70865. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  70866. }
  70867. this._betaIsAnimating = true;
  70868. this._animatables.push(BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime));
  70869. // sets the radius and lower radius bounds
  70870. // Small delta ensures camera is not always at lower zoom limit.
  70871. var delta = 0.1;
  70872. var radius = 0;
  70873. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  70874. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  70875. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  70876. radius = position;
  70877. }
  70878. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  70879. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  70880. if (this._attachedCamera.lowerRadiusLimit === null) {
  70881. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  70882. }
  70883. }
  70884. // transition to new radius
  70885. if (!this._radiusTransition) {
  70886. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  70887. }
  70888. this._animatables.push(BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, onAnimationEnd));
  70889. };
  70890. /**
  70891. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  70892. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  70893. * frustum width.
  70894. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  70895. * to fully enclose the mesh in the viewing frustum.
  70896. */
  70897. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  70898. var size = maximumWorld.subtract(minimumWorld);
  70899. var boxVectorGlobalDiagonal = size.length();
  70900. var frustumSlope = this._getFrustumSlope();
  70901. // Formula for setting distance
  70902. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  70903. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  70904. // Horizon distance
  70905. var radius = radiusWithoutFraming * this._radiusScale;
  70906. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  70907. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  70908. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  70909. var camera = this._attachedCamera;
  70910. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  70911. // Don't exceed the requested limit
  70912. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  70913. }
  70914. // Don't exceed the upper radius limit
  70915. if (camera.upperRadiusLimit) {
  70916. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  70917. }
  70918. return distance;
  70919. };
  70920. /**
  70921. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  70922. * is automatically returned to its default position (expected to be above ground plane).
  70923. */
  70924. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  70925. var _this = this;
  70926. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  70927. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  70928. var limitBeta = Math.PI * 0.5;
  70929. // Bring the camera back up if below the ground plane
  70930. if (!this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  70931. this._betaIsAnimating = true;
  70932. //Transition to new position
  70933. this.stopAllAnimations();
  70934. if (!this._betaTransition) {
  70935. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  70936. }
  70937. this._animatables.push(BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  70938. _this._clearAnimationLocks();
  70939. _this.stopAllAnimations();
  70940. }));
  70941. }
  70942. };
  70943. /**
  70944. * Returns the frustum slope based on the canvas ratio and camera FOV
  70945. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  70946. */
  70947. FramingBehavior.prototype._getFrustumSlope = function () {
  70948. // Calculate the viewport ratio
  70949. // Aspect Ratio is Height/Width.
  70950. var camera = this._attachedCamera;
  70951. var engine = camera.getScene().getEngine();
  70952. var aspectRatio = engine.getAspectRatio(camera);
  70953. // Camera FOV is the vertical field of view (top-bottom) in radians.
  70954. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  70955. var frustumSlopeY = Math.tan(camera.fov / 2);
  70956. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  70957. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  70958. // along the forward vector.
  70959. var frustumSlopeX = frustumSlopeY * aspectRatio;
  70960. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  70961. };
  70962. /**
  70963. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  70964. */
  70965. FramingBehavior.prototype._clearAnimationLocks = function () {
  70966. this._betaIsAnimating = false;
  70967. };
  70968. /**
  70969. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  70970. */
  70971. FramingBehavior.prototype._applyUserInteraction = function () {
  70972. if (this.isUserIsMoving) {
  70973. this._lastInteractionTime = BABYLON.Tools.Now;
  70974. this.stopAllAnimations();
  70975. this._clearAnimationLocks();
  70976. }
  70977. };
  70978. /**
  70979. * Stops and removes all animations that have been applied to the camera
  70980. */
  70981. FramingBehavior.prototype.stopAllAnimations = function () {
  70982. this._attachedCamera.animations = [];
  70983. while (this._animatables.length) {
  70984. if (this._animatables[0]) {
  70985. this._animatables[0].onAnimationEnd = null;
  70986. this._animatables[0].stop();
  70987. }
  70988. this._animatables.shift();
  70989. }
  70990. };
  70991. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  70992. /**
  70993. * Gets a value indicating if the user is moving the camera
  70994. */
  70995. get: function () {
  70996. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  70997. this._attachedCamera.inertialBetaOffset !== 0 ||
  70998. this._attachedCamera.inertialRadiusOffset !== 0 ||
  70999. this._attachedCamera.inertialPanningX !== 0 ||
  71000. this._attachedCamera.inertialPanningY !== 0 ||
  71001. this._isPointerDown;
  71002. },
  71003. enumerable: true,
  71004. configurable: true
  71005. });
  71006. /**
  71007. * The easing function used by animations
  71008. */
  71009. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  71010. /**
  71011. * The easing mode used by animations
  71012. */
  71013. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  71014. // Statics
  71015. /**
  71016. * The camera can move all the way towards the mesh.
  71017. */
  71018. FramingBehavior.IgnoreBoundsSizeMode = 0;
  71019. /**
  71020. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  71021. */
  71022. FramingBehavior.FitFrustumSidesMode = 1;
  71023. return FramingBehavior;
  71024. }());
  71025. BABYLON.FramingBehavior = FramingBehavior;
  71026. })(BABYLON || (BABYLON = {}));
  71027. //# sourceMappingURL=babylon.framingBehavior.js.map
  71028. var BABYLON;
  71029. (function (BABYLON) {
  71030. /**
  71031. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  71032. */
  71033. var BouncingBehavior = (function () {
  71034. function BouncingBehavior() {
  71035. /**
  71036. * The duration of the animation, in milliseconds
  71037. */
  71038. this.transitionDuration = 450;
  71039. /**
  71040. * Length of the distance animated by the transition when lower radius is reached
  71041. */
  71042. this.lowerRadiusTransitionRange = 2;
  71043. /**
  71044. * Length of the distance animated by the transition when upper radius is reached
  71045. */
  71046. this.upperRadiusTransitionRange = -2;
  71047. this._autoTransitionRange = false;
  71048. // Animations
  71049. this._radiusIsAnimating = false;
  71050. this._radiusBounceTransition = null;
  71051. this._animatables = new Array();
  71052. }
  71053. Object.defineProperty(BouncingBehavior.prototype, "name", {
  71054. get: function () {
  71055. return "Bouncing";
  71056. },
  71057. enumerable: true,
  71058. configurable: true
  71059. });
  71060. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  71061. /**
  71062. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  71063. */
  71064. get: function () {
  71065. return this._autoTransitionRange;
  71066. },
  71067. /**
  71068. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  71069. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  71070. */
  71071. set: function (value) {
  71072. var _this = this;
  71073. if (this._autoTransitionRange === value) {
  71074. return;
  71075. }
  71076. this._autoTransitionRange = value;
  71077. var camera = this._attachedCamera;
  71078. if (value) {
  71079. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  71080. if (!mesh) {
  71081. return;
  71082. }
  71083. mesh.computeWorldMatrix(true);
  71084. var diagonal = mesh.getBoundingInfo().diagonalLength;
  71085. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  71086. _this.upperRadiusTransitionRange = diagonal * 0.05;
  71087. });
  71088. }
  71089. else if (this._onMeshTargetChangedObserver) {
  71090. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  71091. }
  71092. },
  71093. enumerable: true,
  71094. configurable: true
  71095. });
  71096. BouncingBehavior.prototype.attach = function (camera) {
  71097. var _this = this;
  71098. this._attachedCamera = camera;
  71099. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  71100. // Add the bounce animation to the lower radius limit
  71101. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  71102. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  71103. }
  71104. // Add the bounce animation to the upper radius limit
  71105. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  71106. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  71107. }
  71108. });
  71109. };
  71110. BouncingBehavior.prototype.detach = function () {
  71111. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  71112. if (this._onMeshTargetChangedObserver) {
  71113. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  71114. }
  71115. this._attachedCamera = null;
  71116. };
  71117. /**
  71118. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  71119. * @param radiusLimit The limit to check against.
  71120. * @return Bool to indicate if at limit.
  71121. */
  71122. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  71123. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  71124. return true;
  71125. }
  71126. return false;
  71127. };
  71128. /**
  71129. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  71130. * @param radiusDelta The delta by which to animate to. Can be negative.
  71131. */
  71132. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  71133. var _this = this;
  71134. if (!this._radiusBounceTransition) {
  71135. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  71136. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  71137. }
  71138. // Prevent zoom until bounce has completed
  71139. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  71140. this._attachedCamera.wheelPrecision = Infinity;
  71141. this._attachedCamera.inertialRadiusOffset = 0;
  71142. // Animate to the radius limit
  71143. this.stopAllAnimations();
  71144. this._radiusIsAnimating = true;
  71145. 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(); }));
  71146. };
  71147. /**
  71148. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  71149. */
  71150. BouncingBehavior.prototype._clearAnimationLocks = function () {
  71151. this._radiusIsAnimating = false;
  71152. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  71153. };
  71154. /**
  71155. * Stops and removes all animations that have been applied to the camera
  71156. */
  71157. BouncingBehavior.prototype.stopAllAnimations = function () {
  71158. this._attachedCamera.animations = [];
  71159. while (this._animatables.length) {
  71160. this._animatables[0].onAnimationEnd = null;
  71161. this._animatables[0].stop();
  71162. this._animatables.shift();
  71163. }
  71164. };
  71165. /**
  71166. * The easing function used by animations
  71167. */
  71168. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  71169. /**
  71170. * The easing mode used by animations
  71171. */
  71172. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  71173. return BouncingBehavior;
  71174. }());
  71175. BABYLON.BouncingBehavior = BouncingBehavior;
  71176. })(BABYLON || (BABYLON = {}));
  71177. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  71178. var BABYLON;
  71179. (function (BABYLON) {
  71180. var AutoRotationBehavior = (function () {
  71181. function AutoRotationBehavior() {
  71182. this._zoomStopsAnimation = false;
  71183. this._idleRotationSpeed = 0.05;
  71184. this._idleRotationWaitTime = 2000;
  71185. this._idleRotationSpinupTime = 2000;
  71186. this._isPointerDown = false;
  71187. this._lastFrameTime = null;
  71188. this._lastInteractionTime = -Infinity;
  71189. this._cameraRotationSpeed = 0;
  71190. this._lastFrameRadius = 0;
  71191. }
  71192. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  71193. get: function () {
  71194. return "AutoRotation";
  71195. },
  71196. enumerable: true,
  71197. configurable: true
  71198. });
  71199. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  71200. /**
  71201. * Gets the flag that indicates if user zooming should stop animation.
  71202. */
  71203. get: function () {
  71204. return this._zoomStopsAnimation;
  71205. },
  71206. /**
  71207. * Sets the flag that indicates if user zooming should stop animation.
  71208. */
  71209. set: function (flag) {
  71210. this._zoomStopsAnimation = flag;
  71211. },
  71212. enumerable: true,
  71213. configurable: true
  71214. });
  71215. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  71216. /**
  71217. * Gets the default speed at which the camera rotates around the model.
  71218. */
  71219. get: function () {
  71220. return this._idleRotationSpeed;
  71221. },
  71222. /**
  71223. * Sets the default speed at which the camera rotates around the model.
  71224. */
  71225. set: function (speed) {
  71226. this._idleRotationSpeed = speed;
  71227. },
  71228. enumerable: true,
  71229. configurable: true
  71230. });
  71231. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  71232. /**
  71233. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  71234. */
  71235. get: function () {
  71236. return this._idleRotationWaitTime;
  71237. },
  71238. /**
  71239. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  71240. */
  71241. set: function (time) {
  71242. this._idleRotationWaitTime = time;
  71243. },
  71244. enumerable: true,
  71245. configurable: true
  71246. });
  71247. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  71248. /**
  71249. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  71250. */
  71251. get: function () {
  71252. return this._idleRotationSpinupTime;
  71253. },
  71254. /**
  71255. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  71256. */
  71257. set: function (time) {
  71258. this._idleRotationSpinupTime = time;
  71259. },
  71260. enumerable: true,
  71261. configurable: true
  71262. });
  71263. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  71264. /**
  71265. * Gets a value indicating if the camera is currently rotating because of this behavior
  71266. */
  71267. get: function () {
  71268. return Math.abs(this._cameraRotationSpeed) > 0;
  71269. },
  71270. enumerable: true,
  71271. configurable: true
  71272. });
  71273. AutoRotationBehavior.prototype.attach = function (camera) {
  71274. var _this = this;
  71275. this._attachedCamera = camera;
  71276. var scene = this._attachedCamera.getScene();
  71277. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  71278. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  71279. _this._isPointerDown = true;
  71280. return;
  71281. }
  71282. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  71283. _this._isPointerDown = false;
  71284. }
  71285. });
  71286. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  71287. var now = BABYLON.Tools.Now;
  71288. var dt = 0;
  71289. if (_this._lastFrameTime != null) {
  71290. dt = now - _this._lastFrameTime;
  71291. }
  71292. _this._lastFrameTime = now;
  71293. // Stop the animation if there is user interaction and the animation should stop for this interaction
  71294. _this._applyUserInteraction();
  71295. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  71296. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  71297. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  71298. // Step camera rotation by rotation speed
  71299. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  71300. });
  71301. };
  71302. AutoRotationBehavior.prototype.detach = function () {
  71303. var scene = this._attachedCamera.getScene();
  71304. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  71305. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  71306. this._attachedCamera = null;
  71307. };
  71308. /**
  71309. * Returns true if user is scrolling.
  71310. * @return true if user is scrolling.
  71311. */
  71312. AutoRotationBehavior.prototype._userIsZooming = function () {
  71313. return this._attachedCamera.inertialRadiusOffset !== 0;
  71314. };
  71315. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  71316. var zoomHasHitLimit = false;
  71317. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  71318. zoomHasHitLimit = true;
  71319. }
  71320. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  71321. this._lastFrameRadius = this._attachedCamera.radius;
  71322. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  71323. };
  71324. /**
  71325. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  71326. */
  71327. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  71328. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  71329. this._lastInteractionTime = BABYLON.Tools.Now;
  71330. }
  71331. };
  71332. // Tools
  71333. AutoRotationBehavior.prototype._userIsMoving = function () {
  71334. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  71335. this._attachedCamera.inertialBetaOffset !== 0 ||
  71336. this._attachedCamera.inertialRadiusOffset !== 0 ||
  71337. this._attachedCamera.inertialPanningX !== 0 ||
  71338. this._attachedCamera.inertialPanningY !== 0 ||
  71339. this._isPointerDown;
  71340. };
  71341. return AutoRotationBehavior;
  71342. }());
  71343. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  71344. })(BABYLON || (BABYLON = {}));
  71345. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  71346. 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 vec4 cellInfo;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 textureInfos;\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\nvec2 uvScale=textureInfos.xy;\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y- cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*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}"};
  71347. 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};"};
  71348. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  71349. module.exports = BABYLON;
  71350. };