babylon.max.js 3.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510
  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 = new Array();
  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 = new Array();
  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 = new Array();
  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 = new Array();
  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. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  4182. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  4183. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  4184. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  4185. frustumPlane.d = transform.m[15] + transform.m[14];
  4186. frustumPlane.normalize();
  4187. };
  4188. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  4189. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  4190. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  4191. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  4192. frustumPlane.d = transform.m[15] - transform.m[14];
  4193. frustumPlane.normalize();
  4194. };
  4195. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  4196. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  4197. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  4198. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  4199. frustumPlane.d = transform.m[15] + transform.m[12];
  4200. frustumPlane.normalize();
  4201. };
  4202. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  4203. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  4204. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  4205. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  4206. frustumPlane.d = transform.m[15] - transform.m[12];
  4207. frustumPlane.normalize();
  4208. };
  4209. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  4210. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  4211. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  4212. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  4213. frustumPlane.d = transform.m[15] - transform.m[13];
  4214. frustumPlane.normalize();
  4215. };
  4216. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  4217. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  4218. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  4219. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  4220. frustumPlane.d = transform.m[15] + transform.m[13];
  4221. frustumPlane.normalize();
  4222. };
  4223. /**
  4224. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4225. */
  4226. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4227. // Near
  4228. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  4229. // Far
  4230. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  4231. // Left
  4232. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  4233. // Right
  4234. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  4235. // Top
  4236. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  4237. // Bottom
  4238. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  4239. };
  4240. return Frustum;
  4241. }());
  4242. BABYLON.Frustum = Frustum;
  4243. var Space;
  4244. (function (Space) {
  4245. Space[Space["LOCAL"] = 0] = "LOCAL";
  4246. Space[Space["WORLD"] = 1] = "WORLD";
  4247. Space[Space["BONE"] = 2] = "BONE";
  4248. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4249. var Axis = (function () {
  4250. function Axis() {
  4251. }
  4252. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4253. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4254. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4255. return Axis;
  4256. }());
  4257. BABYLON.Axis = Axis;
  4258. ;
  4259. var BezierCurve = (function () {
  4260. function BezierCurve() {
  4261. }
  4262. /**
  4263. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4264. */
  4265. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4266. // Extract X (which is equal to time here)
  4267. var f0 = 1 - 3 * x2 + 3 * x1;
  4268. var f1 = 3 * x2 - 6 * x1;
  4269. var f2 = 3 * x1;
  4270. var refinedT = t;
  4271. for (var i = 0; i < 5; i++) {
  4272. var refinedT2 = refinedT * refinedT;
  4273. var refinedT3 = refinedT2 * refinedT;
  4274. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4275. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4276. refinedT -= (x - t) * slope;
  4277. refinedT = Math.min(1, Math.max(0, refinedT));
  4278. }
  4279. // Resolve cubic bezier for the given x
  4280. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4281. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4282. Math.pow(refinedT, 3);
  4283. };
  4284. return BezierCurve;
  4285. }());
  4286. BABYLON.BezierCurve = BezierCurve;
  4287. var Orientation;
  4288. (function (Orientation) {
  4289. Orientation[Orientation["CW"] = 0] = "CW";
  4290. Orientation[Orientation["CCW"] = 1] = "CCW";
  4291. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4292. var Angle = (function () {
  4293. /**
  4294. * Creates an Angle object of "radians" radians (float).
  4295. */
  4296. function Angle(radians) {
  4297. var _this = this;
  4298. /**
  4299. * Returns the Angle value in degrees (float).
  4300. */
  4301. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4302. /**
  4303. * Returns the Angle value in radians (float).
  4304. */
  4305. this.radians = function () { return _this._radians; };
  4306. this._radians = radians;
  4307. if (this._radians < 0.0)
  4308. this._radians += (2.0 * Math.PI);
  4309. }
  4310. /**
  4311. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4312. */
  4313. Angle.BetweenTwoPoints = function (a, b) {
  4314. var delta = b.subtract(a);
  4315. var theta = Math.atan2(delta.y, delta.x);
  4316. return new Angle(theta);
  4317. };
  4318. /**
  4319. * Returns a new Angle object from the passed float in radians.
  4320. */
  4321. Angle.FromRadians = function (radians) {
  4322. return new Angle(radians);
  4323. };
  4324. /**
  4325. * Returns a new Angle object from the passed float in degrees.
  4326. */
  4327. Angle.FromDegrees = function (degrees) {
  4328. return new Angle(degrees * Math.PI / 180.0);
  4329. };
  4330. return Angle;
  4331. }());
  4332. BABYLON.Angle = Angle;
  4333. var Arc2 = (function () {
  4334. /**
  4335. * Creates an Arc object from the three passed points : start, middle and end.
  4336. */
  4337. function Arc2(startPoint, midPoint, endPoint) {
  4338. this.startPoint = startPoint;
  4339. this.midPoint = midPoint;
  4340. this.endPoint = endPoint;
  4341. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4342. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4343. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4344. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4345. 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);
  4346. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4347. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4348. var a1 = this.startAngle.degrees();
  4349. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4350. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4351. // angles correction
  4352. if (a2 - a1 > +180.0)
  4353. a2 -= 360.0;
  4354. if (a2 - a1 < -180.0)
  4355. a2 += 360.0;
  4356. if (a3 - a2 > +180.0)
  4357. a3 -= 360.0;
  4358. if (a3 - a2 < -180.0)
  4359. a3 += 360.0;
  4360. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4361. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4362. }
  4363. return Arc2;
  4364. }());
  4365. BABYLON.Arc2 = Arc2;
  4366. var Path2 = (function () {
  4367. /**
  4368. * Creates a Path2 object from the starting 2D coordinates x and y.
  4369. */
  4370. function Path2(x, y) {
  4371. this._points = new Array();
  4372. this._length = 0.0;
  4373. this.closed = false;
  4374. this._points.push(new Vector2(x, y));
  4375. }
  4376. /**
  4377. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4378. * Returns the updated Path2.
  4379. */
  4380. Path2.prototype.addLineTo = function (x, y) {
  4381. if (closed) {
  4382. //Tools.Error("cannot add lines to closed paths");
  4383. return this;
  4384. }
  4385. var newPoint = new Vector2(x, y);
  4386. var previousPoint = this._points[this._points.length - 1];
  4387. this._points.push(newPoint);
  4388. this._length += newPoint.subtract(previousPoint).length();
  4389. return this;
  4390. };
  4391. /**
  4392. * 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.
  4393. * Returns the updated Path2.
  4394. */
  4395. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4396. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4397. if (closed) {
  4398. //Tools.Error("cannot add arcs to closed paths");
  4399. return this;
  4400. }
  4401. var startPoint = this._points[this._points.length - 1];
  4402. var midPoint = new Vector2(midX, midY);
  4403. var endPoint = new Vector2(endX, endY);
  4404. var arc = new Arc2(startPoint, midPoint, endPoint);
  4405. var increment = arc.angle.radians() / numberOfSegments;
  4406. if (arc.orientation === Orientation.CW)
  4407. increment *= -1;
  4408. var currentAngle = arc.startAngle.radians() + increment;
  4409. for (var i = 0; i < numberOfSegments; i++) {
  4410. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4411. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4412. this.addLineTo(x, y);
  4413. currentAngle += increment;
  4414. }
  4415. return this;
  4416. };
  4417. /**
  4418. * Closes the Path2.
  4419. * Returns the Path2.
  4420. */
  4421. Path2.prototype.close = function () {
  4422. this.closed = true;
  4423. return this;
  4424. };
  4425. /**
  4426. * Returns the Path2 total length (float).
  4427. */
  4428. Path2.prototype.length = function () {
  4429. var result = this._length;
  4430. if (!this.closed) {
  4431. var lastPoint = this._points[this._points.length - 1];
  4432. var firstPoint = this._points[0];
  4433. result += (firstPoint.subtract(lastPoint).length());
  4434. }
  4435. return result;
  4436. };
  4437. /**
  4438. * Returns the Path2 internal array of points.
  4439. */
  4440. Path2.prototype.getPoints = function () {
  4441. return this._points;
  4442. };
  4443. /**
  4444. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4445. */
  4446. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4447. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4448. //Tools.Error("normalized length position should be between 0 and 1.");
  4449. return Vector2.Zero();
  4450. }
  4451. var lengthPosition = normalizedLengthPosition * this.length();
  4452. var previousOffset = 0;
  4453. for (var i = 0; i < this._points.length; i++) {
  4454. var j = (i + 1) % this._points.length;
  4455. var a = this._points[i];
  4456. var b = this._points[j];
  4457. var bToA = b.subtract(a);
  4458. var nextOffset = (bToA.length() + previousOffset);
  4459. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4460. var dir = bToA.normalize();
  4461. var localOffset = lengthPosition - previousOffset;
  4462. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4463. }
  4464. previousOffset = nextOffset;
  4465. }
  4466. //Tools.Error("internal error");
  4467. return Vector2.Zero();
  4468. };
  4469. /**
  4470. * Returns a new Path2 starting at the coordinates (x, y).
  4471. */
  4472. Path2.StartingAt = function (x, y) {
  4473. return new Path2(x, y);
  4474. };
  4475. return Path2;
  4476. }());
  4477. BABYLON.Path2 = Path2;
  4478. var Path3D = (function () {
  4479. /**
  4480. * new Path3D(path, normal, raw)
  4481. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4482. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4483. * path : an array of Vector3, the curve axis of the Path3D
  4484. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4485. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4486. */
  4487. function Path3D(path, firstNormal, raw) {
  4488. this.path = path;
  4489. this._curve = new Array();
  4490. this._distances = new Array();
  4491. this._tangents = new Array();
  4492. this._normals = new Array();
  4493. this._binormals = new Array();
  4494. for (var p = 0; p < path.length; p++) {
  4495. this._curve[p] = path[p].clone(); // hard copy
  4496. }
  4497. this._raw = raw || false;
  4498. this._compute(firstNormal);
  4499. }
  4500. /**
  4501. * Returns the Path3D array of successive Vector3 designing its curve.
  4502. */
  4503. Path3D.prototype.getCurve = function () {
  4504. return this._curve;
  4505. };
  4506. /**
  4507. * Returns an array populated with tangent vectors on each Path3D curve point.
  4508. */
  4509. Path3D.prototype.getTangents = function () {
  4510. return this._tangents;
  4511. };
  4512. /**
  4513. * Returns an array populated with normal vectors on each Path3D curve point.
  4514. */
  4515. Path3D.prototype.getNormals = function () {
  4516. return this._normals;
  4517. };
  4518. /**
  4519. * Returns an array populated with binormal vectors on each Path3D curve point.
  4520. */
  4521. Path3D.prototype.getBinormals = function () {
  4522. return this._binormals;
  4523. };
  4524. /**
  4525. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4526. */
  4527. Path3D.prototype.getDistances = function () {
  4528. return this._distances;
  4529. };
  4530. /**
  4531. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4532. * Returns the same object updated.
  4533. */
  4534. Path3D.prototype.update = function (path, firstNormal) {
  4535. for (var p = 0; p < path.length; p++) {
  4536. this._curve[p].x = path[p].x;
  4537. this._curve[p].y = path[p].y;
  4538. this._curve[p].z = path[p].z;
  4539. }
  4540. this._compute(firstNormal);
  4541. return this;
  4542. };
  4543. // private function compute() : computes tangents, normals and binormals
  4544. Path3D.prototype._compute = function (firstNormal) {
  4545. var l = this._curve.length;
  4546. // first and last tangents
  4547. this._tangents[0] = this._getFirstNonNullVector(0);
  4548. if (!this._raw) {
  4549. this._tangents[0].normalize();
  4550. }
  4551. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4552. if (!this._raw) {
  4553. this._tangents[l - 1].normalize();
  4554. }
  4555. // normals and binormals at first point : arbitrary vector with _normalVector()
  4556. var tg0 = this._tangents[0];
  4557. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4558. this._normals[0] = pp0;
  4559. if (!this._raw) {
  4560. this._normals[0].normalize();
  4561. }
  4562. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4563. if (!this._raw) {
  4564. this._binormals[0].normalize();
  4565. }
  4566. this._distances[0] = 0.0;
  4567. // normals and binormals : next points
  4568. var prev; // previous vector (segment)
  4569. var cur; // current vector (segment)
  4570. var curTang; // current tangent
  4571. // previous normal
  4572. var prevBinor; // previous binormal
  4573. for (var i = 1; i < l; i++) {
  4574. // tangents
  4575. prev = this._getLastNonNullVector(i);
  4576. if (i < l - 1) {
  4577. cur = this._getFirstNonNullVector(i);
  4578. this._tangents[i] = prev.add(cur);
  4579. this._tangents[i].normalize();
  4580. }
  4581. this._distances[i] = this._distances[i - 1] + prev.length();
  4582. // normals and binormals
  4583. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4584. curTang = this._tangents[i];
  4585. prevBinor = this._binormals[i - 1];
  4586. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4587. if (!this._raw) {
  4588. this._normals[i].normalize();
  4589. }
  4590. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4591. if (!this._raw) {
  4592. this._binormals[i].normalize();
  4593. }
  4594. }
  4595. };
  4596. // private function getFirstNonNullVector(index)
  4597. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4598. Path3D.prototype._getFirstNonNullVector = function (index) {
  4599. var i = 1;
  4600. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4601. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4602. i++;
  4603. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4604. }
  4605. return nNVector;
  4606. };
  4607. // private function getLastNonNullVector(index)
  4608. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4609. Path3D.prototype._getLastNonNullVector = function (index) {
  4610. var i = 1;
  4611. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4612. while (nLVector.length() === 0 && index > i + 1) {
  4613. i++;
  4614. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4615. }
  4616. return nLVector;
  4617. };
  4618. // private function normalVector(v0, vt, va) :
  4619. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4620. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4621. Path3D.prototype._normalVector = function (v0, vt, va) {
  4622. var normal0;
  4623. var tgl = vt.length();
  4624. if (tgl === 0.0) {
  4625. tgl = 1.0;
  4626. }
  4627. if (va === undefined || va === null) {
  4628. var point;
  4629. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4630. point = new Vector3(0.0, -1.0, 0.0);
  4631. }
  4632. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4633. point = new Vector3(1.0, 0.0, 0.0);
  4634. }
  4635. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4636. point = new Vector3(0.0, 0.0, 1.0);
  4637. }
  4638. normal0 = Vector3.Cross(vt, point);
  4639. }
  4640. else {
  4641. normal0 = Vector3.Cross(vt, va);
  4642. Vector3.CrossToRef(normal0, vt, normal0);
  4643. }
  4644. normal0.normalize();
  4645. return normal0;
  4646. };
  4647. return Path3D;
  4648. }());
  4649. BABYLON.Path3D = Path3D;
  4650. var Curve3 = (function () {
  4651. /**
  4652. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4653. * A Curve3 is designed from a series of successive Vector3.
  4654. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4655. */
  4656. function Curve3(points) {
  4657. this._length = 0.0;
  4658. this._points = points;
  4659. this._length = this._computeLength(points);
  4660. }
  4661. /**
  4662. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4663. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4664. * @param v1 (Vector3) the control point
  4665. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4666. * @param nbPoints (integer) the wanted number of points in the curve
  4667. */
  4668. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4669. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4670. var bez = new Array();
  4671. var equation = function (t, val0, val1, val2) {
  4672. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4673. return res;
  4674. };
  4675. for (var i = 0; i <= nbPoints; i++) {
  4676. 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)));
  4677. }
  4678. return new Curve3(bez);
  4679. };
  4680. /**
  4681. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4682. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4683. * @param v1 (Vector3) the first control point
  4684. * @param v2 (Vector3) the second control point
  4685. * @param v3 (Vector3) the end point of the Cubic Bezier
  4686. * @param nbPoints (integer) the wanted number of points in the curve
  4687. */
  4688. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4689. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4690. var bez = new Array();
  4691. var equation = function (t, val0, val1, val2, val3) {
  4692. 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;
  4693. return res;
  4694. };
  4695. for (var i = 0; i <= nbPoints; i++) {
  4696. 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)));
  4697. }
  4698. return new Curve3(bez);
  4699. };
  4700. /**
  4701. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4702. * @param p1 (Vector3) the origin point of the Hermite Spline
  4703. * @param t1 (Vector3) the tangent vector at the origin point
  4704. * @param p2 (Vector3) the end point of the Hermite Spline
  4705. * @param t2 (Vector3) the tangent vector at the end point
  4706. * @param nbPoints (integer) the wanted number of points in the curve
  4707. */
  4708. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4709. var hermite = new Array();
  4710. var step = 1.0 / nbPoints;
  4711. for (var i = 0; i <= nbPoints; i++) {
  4712. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4713. }
  4714. return new Curve3(hermite);
  4715. };
  4716. /**
  4717. * Returns a Curve3 object along a CatmullRom Spline curve :
  4718. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4719. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4720. */
  4721. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4722. var totalPoints = new Array();
  4723. totalPoints.push(points[0].clone());
  4724. Array.prototype.push.apply(totalPoints, points);
  4725. totalPoints.push(points[points.length - 1].clone());
  4726. var catmullRom = new Array();
  4727. var step = 1.0 / nbPoints;
  4728. for (var i = 0; i < totalPoints.length - 3; i++) {
  4729. var amount = 0.0;
  4730. for (var c = 0; c < nbPoints; c++) {
  4731. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4732. amount += step;
  4733. }
  4734. }
  4735. i--;
  4736. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4737. return new Curve3(catmullRom);
  4738. };
  4739. /**
  4740. * Returns the Curve3 stored array of successive Vector3
  4741. */
  4742. Curve3.prototype.getPoints = function () {
  4743. return this._points;
  4744. };
  4745. /**
  4746. * Returns the computed length (float) of the curve.
  4747. */
  4748. Curve3.prototype.length = function () {
  4749. return this._length;
  4750. };
  4751. /**
  4752. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4753. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4754. * curveA and curveB keep unchanged.
  4755. */
  4756. Curve3.prototype.continue = function (curve) {
  4757. var lastPoint = this._points[this._points.length - 1];
  4758. var continuedPoints = this._points.slice();
  4759. var curvePoints = curve.getPoints();
  4760. for (var i = 1; i < curvePoints.length; i++) {
  4761. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4762. }
  4763. var continuedCurve = new Curve3(continuedPoints);
  4764. return continuedCurve;
  4765. };
  4766. Curve3.prototype._computeLength = function (path) {
  4767. var l = 0;
  4768. for (var i = 1; i < path.length; i++) {
  4769. l += (path[i].subtract(path[i - 1])).length();
  4770. }
  4771. return l;
  4772. };
  4773. return Curve3;
  4774. }());
  4775. BABYLON.Curve3 = Curve3;
  4776. // Vertex formats
  4777. var PositionNormalVertex = (function () {
  4778. function PositionNormalVertex(position, normal) {
  4779. if (position === void 0) { position = Vector3.Zero(); }
  4780. if (normal === void 0) { normal = Vector3.Up(); }
  4781. this.position = position;
  4782. this.normal = normal;
  4783. }
  4784. PositionNormalVertex.prototype.clone = function () {
  4785. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4786. };
  4787. return PositionNormalVertex;
  4788. }());
  4789. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4790. var PositionNormalTextureVertex = (function () {
  4791. function PositionNormalTextureVertex(position, normal, uv) {
  4792. if (position === void 0) { position = Vector3.Zero(); }
  4793. if (normal === void 0) { normal = Vector3.Up(); }
  4794. if (uv === void 0) { uv = Vector2.Zero(); }
  4795. this.position = position;
  4796. this.normal = normal;
  4797. this.uv = uv;
  4798. }
  4799. PositionNormalTextureVertex.prototype.clone = function () {
  4800. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4801. };
  4802. return PositionNormalTextureVertex;
  4803. }());
  4804. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4805. // Temporary pre-allocated objects for engine internal use
  4806. // usage in any internal function :
  4807. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4808. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4809. var Tmp = (function () {
  4810. function Tmp() {
  4811. }
  4812. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4813. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4814. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4815. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4816. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4817. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4818. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4819. Matrix.Zero(), Matrix.Zero(),
  4820. Matrix.Zero(), Matrix.Zero(),
  4821. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4822. return Tmp;
  4823. }());
  4824. BABYLON.Tmp = Tmp;
  4825. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4826. var MathTmp = (function () {
  4827. function MathTmp() {
  4828. }
  4829. MathTmp.Vector3 = [Vector3.Zero()];
  4830. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4831. MathTmp.Quaternion = [Quaternion.Zero()];
  4832. return MathTmp;
  4833. }());
  4834. })(BABYLON || (BABYLON = {}));
  4835. //# sourceMappingURL=babylon.math.js.map
  4836. var BABYLON;
  4837. (function (BABYLON) {
  4838. var Scalar = (function () {
  4839. function Scalar() {
  4840. }
  4841. /**
  4842. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4843. */
  4844. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4845. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4846. var num = a - b;
  4847. return -epsilon <= num && num <= epsilon;
  4848. };
  4849. /**
  4850. * Returns a string : the upper case translation of the number i to hexadecimal.
  4851. */
  4852. Scalar.ToHex = function (i) {
  4853. var str = i.toString(16);
  4854. if (i <= 15) {
  4855. return ("0" + str).toUpperCase();
  4856. }
  4857. return str.toUpperCase();
  4858. };
  4859. /**
  4860. * Returns -1 if value is negative and +1 is value is positive.
  4861. * Returns the value itself if it's equal to zero.
  4862. */
  4863. Scalar.Sign = function (value) {
  4864. value = +value; // convert to a number
  4865. if (value === 0 || isNaN(value))
  4866. return value;
  4867. return value > 0 ? 1 : -1;
  4868. };
  4869. /**
  4870. * Returns the value itself if it's between min and max.
  4871. * Returns min if the value is lower than min.
  4872. * Returns max if the value is greater than max.
  4873. */
  4874. Scalar.Clamp = function (value, min, max) {
  4875. if (min === void 0) { min = 0; }
  4876. if (max === void 0) { max = 1; }
  4877. return Math.min(max, Math.max(min, value));
  4878. };
  4879. /**
  4880. * Returns the log2 of value.
  4881. */
  4882. Scalar.Log2 = function (value) {
  4883. return Math.log(value) * Math.LOG2E;
  4884. };
  4885. /**
  4886. * Loops the value, so that it is never larger than length and never smaller than 0.
  4887. *
  4888. * This is similar to the modulo operator but it works with floating point numbers.
  4889. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4890. * With t = 5 and length = 2.5, the result would be 0.0.
  4891. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4892. */
  4893. Scalar.Repeat = function (value, length) {
  4894. return value - Math.floor(value / length) * length;
  4895. };
  4896. /**
  4897. * Normalize the value between 0.0 and 1.0 using min and max values
  4898. */
  4899. Scalar.Normalize = function (value, min, max) {
  4900. return (value - min) / (max - min);
  4901. };
  4902. /**
  4903. * Denormalize the value from 0.0 and 1.0 using min and max values
  4904. */
  4905. Scalar.Denormalize = function (normalized, min, max) {
  4906. return (normalized * (max - min) + min);
  4907. };
  4908. /**
  4909. * Calculates the shortest difference between two given angles given in degrees.
  4910. */
  4911. Scalar.DeltaAngle = function (current, target) {
  4912. var num = Scalar.Repeat(target - current, 360.0);
  4913. if (num > 180.0) {
  4914. num -= 360.0;
  4915. }
  4916. return num;
  4917. };
  4918. /**
  4919. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4920. *
  4921. * The returned value will move back and forth between 0 and length
  4922. */
  4923. Scalar.PingPong = function (tx, length) {
  4924. var t = Scalar.Repeat(tx, length * 2.0);
  4925. return length - Math.abs(t - length);
  4926. };
  4927. /**
  4928. * Interpolates between min and max with smoothing at the limits.
  4929. *
  4930. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  4931. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  4932. */
  4933. Scalar.SmoothStep = function (from, to, tx) {
  4934. var t = Scalar.Clamp(tx);
  4935. t = -2.0 * t * t * t + 3.0 * t * t;
  4936. return to * t + from * (1.0 - t);
  4937. };
  4938. /**
  4939. * Moves a value current towards target.
  4940. *
  4941. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  4942. * Negative values of maxDelta pushes the value away from target.
  4943. */
  4944. Scalar.MoveTowards = function (current, target, maxDelta) {
  4945. var result = 0;
  4946. if (Math.abs(target - current) <= maxDelta) {
  4947. result = target;
  4948. }
  4949. else {
  4950. result = current + Scalar.Sign(target - current) * maxDelta;
  4951. }
  4952. return result;
  4953. };
  4954. /**
  4955. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4956. *
  4957. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  4958. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  4959. */
  4960. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  4961. var num = Scalar.DeltaAngle(current, target);
  4962. var result = 0;
  4963. if (-maxDelta < num && num < maxDelta) {
  4964. result = target;
  4965. }
  4966. else {
  4967. target = current + num;
  4968. result = Scalar.MoveTowards(current, target, maxDelta);
  4969. }
  4970. return result;
  4971. };
  4972. /**
  4973. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  4974. */
  4975. Scalar.Lerp = function (start, end, amount) {
  4976. return start + ((end - start) * amount);
  4977. };
  4978. /**
  4979. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4980. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  4981. */
  4982. Scalar.LerpAngle = function (start, end, amount) {
  4983. var num = Scalar.Repeat(end - start, 360.0);
  4984. if (num > 180.0) {
  4985. num -= 360.0;
  4986. }
  4987. return start + num * Scalar.Clamp(amount);
  4988. };
  4989. /**
  4990. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  4991. */
  4992. Scalar.InverseLerp = function (a, b, value) {
  4993. var result = 0;
  4994. if (a != b) {
  4995. result = Scalar.Clamp((value - a) / (b - a));
  4996. }
  4997. else {
  4998. result = 0.0;
  4999. }
  5000. return result;
  5001. };
  5002. /**
  5003. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5004. */
  5005. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5006. var squared = amount * amount;
  5007. var cubed = amount * squared;
  5008. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5009. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5010. var part3 = (cubed - (2.0 * squared)) + amount;
  5011. var part4 = cubed - squared;
  5012. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5013. };
  5014. /**
  5015. * Returns a random float number between and min and max values
  5016. */
  5017. Scalar.RandomRange = function (min, max) {
  5018. if (min === max)
  5019. return min;
  5020. return ((Math.random() * (max - min)) + min);
  5021. };
  5022. /**
  5023. * This function returns percentage of a number in a given range.
  5024. *
  5025. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5026. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5027. */
  5028. Scalar.RangeToPercent = function (number, min, max) {
  5029. return ((number - min) / (max - min));
  5030. };
  5031. /**
  5032. * This function returns number that corresponds to the percentage in a given range.
  5033. *
  5034. * PercentToRange(0.34,0,100) will return 34.
  5035. */
  5036. Scalar.PercentToRange = function (percent, min, max) {
  5037. return ((max - min) * percent + min);
  5038. };
  5039. return Scalar;
  5040. }());
  5041. BABYLON.Scalar = Scalar;
  5042. })(BABYLON || (BABYLON = {}));
  5043. //# sourceMappingURL=babylon.math.scalar.js.map
  5044. //# sourceMappingURL=babylon.mixins.js.map
  5045. var BABYLON;
  5046. (function (BABYLON) {
  5047. var __decoratorInitialStore = {};
  5048. var __mergedStore = {};
  5049. var _copySource = function (creationFunction, source, instanciate) {
  5050. var destination = creationFunction();
  5051. // Tags
  5052. if (BABYLON.Tags) {
  5053. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5054. }
  5055. var classStore = getMergedStore(destination);
  5056. // Properties
  5057. for (var property in classStore) {
  5058. var propertyDescriptor = classStore[property];
  5059. var sourceProperty = source[property];
  5060. var propertyType = propertyDescriptor.type;
  5061. if (sourceProperty !== undefined && sourceProperty !== null) {
  5062. switch (propertyType) {
  5063. case 0: // Value
  5064. case 6:// Mesh reference
  5065. destination[property] = sourceProperty;
  5066. break;
  5067. case 1: // Texture
  5068. case 2: // Color3
  5069. case 3: // FresnelParameters
  5070. case 4: // Vector2
  5071. case 5: // Vector3
  5072. case 7:// Color Curves
  5073. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5074. break;
  5075. }
  5076. }
  5077. }
  5078. return destination;
  5079. };
  5080. function getDirectStore(target) {
  5081. var classKey = target.getClassName();
  5082. if (!__decoratorInitialStore[classKey]) {
  5083. __decoratorInitialStore[classKey] = {};
  5084. }
  5085. return __decoratorInitialStore[classKey];
  5086. }
  5087. /**
  5088. * Return the list of properties flagged as serializable
  5089. * @param target: host object
  5090. */
  5091. function getMergedStore(target) {
  5092. var classKey = target.getClassName();
  5093. if (__mergedStore[classKey]) {
  5094. return __mergedStore[classKey];
  5095. }
  5096. __mergedStore[classKey] = {};
  5097. var store = __mergedStore[classKey];
  5098. var currentTarget = target;
  5099. var currentKey = classKey;
  5100. while (currentKey) {
  5101. var initialStore = __decoratorInitialStore[currentKey];
  5102. for (var property in initialStore) {
  5103. store[property] = initialStore[property];
  5104. }
  5105. var parent_1 = void 0;
  5106. var done = false;
  5107. do {
  5108. parent_1 = Object.getPrototypeOf(currentTarget);
  5109. if (!parent_1.getClassName) {
  5110. done = true;
  5111. break;
  5112. }
  5113. if (parent_1.getClassName() !== currentKey) {
  5114. break;
  5115. }
  5116. currentTarget = parent_1;
  5117. } while (parent_1);
  5118. if (done) {
  5119. break;
  5120. }
  5121. currentKey = parent_1.getClassName();
  5122. currentTarget = parent_1;
  5123. }
  5124. return store;
  5125. }
  5126. function generateSerializableMember(type, sourceName) {
  5127. return function (target, propertyKey) {
  5128. var classStore = getDirectStore(target);
  5129. if (!classStore[propertyKey]) {
  5130. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5131. }
  5132. };
  5133. }
  5134. function generateExpandMember(setCallback, targetKey) {
  5135. return function (target, propertyKey) {
  5136. var key = targetKey || ("_" + propertyKey);
  5137. Object.defineProperty(target, propertyKey, {
  5138. get: function () {
  5139. return this[key];
  5140. },
  5141. set: function (value) {
  5142. if (this[key] === value) {
  5143. return;
  5144. }
  5145. this[key] = value;
  5146. target[setCallback].apply(this);
  5147. },
  5148. enumerable: true,
  5149. configurable: true
  5150. });
  5151. };
  5152. }
  5153. function expandToProperty(callback, targetKey) {
  5154. return generateExpandMember(callback, targetKey);
  5155. }
  5156. BABYLON.expandToProperty = expandToProperty;
  5157. function serialize(sourceName) {
  5158. return generateSerializableMember(0, sourceName); // value member
  5159. }
  5160. BABYLON.serialize = serialize;
  5161. function serializeAsTexture(sourceName) {
  5162. return generateSerializableMember(1, sourceName); // texture member
  5163. }
  5164. BABYLON.serializeAsTexture = serializeAsTexture;
  5165. function serializeAsColor3(sourceName) {
  5166. return generateSerializableMember(2, sourceName); // color3 member
  5167. }
  5168. BABYLON.serializeAsColor3 = serializeAsColor3;
  5169. function serializeAsFresnelParameters(sourceName) {
  5170. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5171. }
  5172. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5173. function serializeAsVector2(sourceName) {
  5174. return generateSerializableMember(4, sourceName); // vector2 member
  5175. }
  5176. BABYLON.serializeAsVector2 = serializeAsVector2;
  5177. function serializeAsVector3(sourceName) {
  5178. return generateSerializableMember(5, sourceName); // vector3 member
  5179. }
  5180. BABYLON.serializeAsVector3 = serializeAsVector3;
  5181. function serializeAsMeshReference(sourceName) {
  5182. return generateSerializableMember(6, sourceName); // mesh reference member
  5183. }
  5184. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5185. function serializeAsColorCurves(sourceName) {
  5186. return generateSerializableMember(7, sourceName); // color curves
  5187. }
  5188. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5189. function serializeAsColor4(sourceName) {
  5190. return generateSerializableMember(8, sourceName); // color 4
  5191. }
  5192. BABYLON.serializeAsColor4 = serializeAsColor4;
  5193. function serializeAsImageProcessingConfiguration(sourceName) {
  5194. return generateSerializableMember(9, sourceName); // image processing
  5195. }
  5196. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5197. var SerializationHelper = (function () {
  5198. function SerializationHelper() {
  5199. }
  5200. SerializationHelper.Serialize = function (entity, serializationObject) {
  5201. if (!serializationObject) {
  5202. serializationObject = {};
  5203. }
  5204. // Tags
  5205. if (BABYLON.Tags) {
  5206. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5207. }
  5208. var serializedProperties = getMergedStore(entity);
  5209. // Properties
  5210. for (var property in serializedProperties) {
  5211. var propertyDescriptor = serializedProperties[property];
  5212. var targetPropertyName = propertyDescriptor.sourceName || property;
  5213. var propertyType = propertyDescriptor.type;
  5214. var sourceProperty = entity[property];
  5215. if (sourceProperty !== undefined && sourceProperty !== null) {
  5216. switch (propertyType) {
  5217. case 0:// Value
  5218. serializationObject[targetPropertyName] = sourceProperty;
  5219. break;
  5220. case 1:// Texture
  5221. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5222. break;
  5223. case 2:// Color3
  5224. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5225. break;
  5226. case 3:// FresnelParameters
  5227. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5228. break;
  5229. case 4:// Vector2
  5230. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5231. break;
  5232. case 5:// Vector3
  5233. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5234. break;
  5235. case 6:// Mesh reference
  5236. serializationObject[targetPropertyName] = sourceProperty.id;
  5237. break;
  5238. case 7:// Color Curves
  5239. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5240. break;
  5241. case 8:// Color 4
  5242. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5243. break;
  5244. case 9:// Image Processing
  5245. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5246. break;
  5247. }
  5248. }
  5249. }
  5250. return serializationObject;
  5251. };
  5252. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5253. var destination = creationFunction();
  5254. // Tags
  5255. if (BABYLON.Tags) {
  5256. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5257. }
  5258. var classStore = getMergedStore(destination);
  5259. // Properties
  5260. for (var property in classStore) {
  5261. var propertyDescriptor = classStore[property];
  5262. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5263. var propertyType = propertyDescriptor.type;
  5264. if (sourceProperty !== undefined && sourceProperty !== null) {
  5265. var dest = destination;
  5266. switch (propertyType) {
  5267. case 0:// Value
  5268. dest[property] = sourceProperty;
  5269. break;
  5270. case 1:// Texture
  5271. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5272. break;
  5273. case 2:// Color3
  5274. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  5275. break;
  5276. case 3:// FresnelParameters
  5277. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5278. break;
  5279. case 4:// Vector2
  5280. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5281. break;
  5282. case 5:// Vector3
  5283. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5284. break;
  5285. case 6:// Mesh reference
  5286. dest[property] = scene.getLastMeshByID(sourceProperty);
  5287. break;
  5288. case 7:// Color Curves
  5289. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5290. break;
  5291. case 8:// Color 4
  5292. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  5293. break;
  5294. case 9:// Image Processing
  5295. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5296. break;
  5297. }
  5298. }
  5299. }
  5300. return destination;
  5301. };
  5302. SerializationHelper.Clone = function (creationFunction, source) {
  5303. return _copySource(creationFunction, source, false);
  5304. };
  5305. SerializationHelper.Instanciate = function (creationFunction, source) {
  5306. return _copySource(creationFunction, source, true);
  5307. };
  5308. return SerializationHelper;
  5309. }());
  5310. BABYLON.SerializationHelper = SerializationHelper;
  5311. })(BABYLON || (BABYLON = {}));
  5312. //# sourceMappingURL=babylon.decorators.js.map
  5313. var BABYLON;
  5314. (function (BABYLON) {
  5315. /**
  5316. * A class serves as a medium between the observable and its observers
  5317. */
  5318. var EventState = (function () {
  5319. /**
  5320. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5321. */
  5322. function EventState(mask, skipNextObservers) {
  5323. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5324. this.initalize(mask, skipNextObservers);
  5325. }
  5326. EventState.prototype.initalize = function (mask, skipNextObservers) {
  5327. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5328. this.mask = mask;
  5329. this.skipNextObservers = skipNextObservers;
  5330. return this;
  5331. };
  5332. return EventState;
  5333. }());
  5334. BABYLON.EventState = EventState;
  5335. /**
  5336. * Represent an Observer registered to a given Observable object.
  5337. */
  5338. var Observer = (function () {
  5339. function Observer(callback, mask, scope) {
  5340. if (scope === void 0) { scope = null; }
  5341. this.callback = callback;
  5342. this.mask = mask;
  5343. this.scope = scope;
  5344. }
  5345. return Observer;
  5346. }());
  5347. BABYLON.Observer = Observer;
  5348. /**
  5349. * Represent a list of observers registered to multiple Observables object.
  5350. */
  5351. var MultiObserver = (function () {
  5352. function MultiObserver() {
  5353. }
  5354. MultiObserver.prototype.dispose = function () {
  5355. for (var index = 0; index < this._observers.length; index++) {
  5356. this._observables[index].remove(this._observers[index]);
  5357. }
  5358. this._observers = null;
  5359. this._observables = null;
  5360. };
  5361. MultiObserver.Watch = function (observables, callback, mask, scope) {
  5362. if (mask === void 0) { mask = -1; }
  5363. if (scope === void 0) { scope = null; }
  5364. var result = new MultiObserver();
  5365. result._observers = new Array();
  5366. result._observables = observables;
  5367. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  5368. var observable = observables_1[_i];
  5369. result._observers.push(observable.add(callback, mask, false, scope));
  5370. }
  5371. return result;
  5372. };
  5373. return MultiObserver;
  5374. }());
  5375. BABYLON.MultiObserver = MultiObserver;
  5376. /**
  5377. * The Observable class is a simple implementation of the Observable pattern.
  5378. * 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.
  5379. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5380. * 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).
  5381. * 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.
  5382. */
  5383. var Observable = (function () {
  5384. function Observable(onObserverAdded) {
  5385. this._observers = new Array();
  5386. this._eventState = new EventState(0);
  5387. this._onObserverAdded = onObserverAdded;
  5388. }
  5389. /**
  5390. * Create a new Observer with the specified callback
  5391. * @param callback the callback that will be executed for that Observer
  5392. * @param mask the mask used to filter observers
  5393. * @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.
  5394. * @param scope optional scope for the callback to be called from
  5395. */
  5396. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  5397. if (mask === void 0) { mask = -1; }
  5398. if (insertFirst === void 0) { insertFirst = false; }
  5399. if (scope === void 0) { scope = null; }
  5400. if (!callback) {
  5401. return null;
  5402. }
  5403. var observer = new Observer(callback, mask, scope);
  5404. if (insertFirst) {
  5405. this._observers.unshift(observer);
  5406. }
  5407. else {
  5408. this._observers.push(observer);
  5409. }
  5410. if (this._onObserverAdded) {
  5411. this._onObserverAdded(observer);
  5412. }
  5413. return observer;
  5414. };
  5415. /**
  5416. * Remove an Observer from the Observable object
  5417. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5418. */
  5419. Observable.prototype.remove = function (observer) {
  5420. var index = this._observers.indexOf(observer);
  5421. if (index !== -1) {
  5422. this._observers.splice(index, 1);
  5423. return true;
  5424. }
  5425. return false;
  5426. };
  5427. /**
  5428. * Remove a callback from the Observable object
  5429. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5430. */
  5431. Observable.prototype.removeCallback = function (callback) {
  5432. for (var index = 0; index < this._observers.length; index++) {
  5433. if (this._observers[index].callback === callback) {
  5434. this._observers.splice(index, 1);
  5435. return true;
  5436. }
  5437. }
  5438. return false;
  5439. };
  5440. /**
  5441. * Notify all Observers by calling their respective callback with the given data
  5442. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5443. * @param eventData
  5444. * @param mask
  5445. */
  5446. Observable.prototype.notifyObservers = function (eventData, mask) {
  5447. if (mask === void 0) { mask = -1; }
  5448. var state = this._eventState;
  5449. state.mask = mask;
  5450. state.skipNextObservers = false;
  5451. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5452. var obs = _a[_i];
  5453. if (obs.mask & mask) {
  5454. if (obs.scope) {
  5455. obs.callback.apply(obs.scope, [eventData, state]);
  5456. }
  5457. else {
  5458. obs.callback(eventData, state);
  5459. }
  5460. }
  5461. if (state.skipNextObservers) {
  5462. return false;
  5463. }
  5464. }
  5465. return true;
  5466. };
  5467. /**
  5468. * Notify a specific observer
  5469. * @param eventData
  5470. * @param mask
  5471. */
  5472. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  5473. if (mask === void 0) { mask = -1; }
  5474. var state = this._eventState;
  5475. state.mask = mask;
  5476. state.skipNextObservers = false;
  5477. observer.callback(eventData, state);
  5478. };
  5479. /**
  5480. * return true is the Observable has at least one Observer registered
  5481. */
  5482. Observable.prototype.hasObservers = function () {
  5483. return this._observers.length > 0;
  5484. };
  5485. /**
  5486. * Clear the list of observers
  5487. */
  5488. Observable.prototype.clear = function () {
  5489. this._observers = new Array();
  5490. this._onObserverAdded = null;
  5491. };
  5492. /**
  5493. * Clone the current observable
  5494. */
  5495. Observable.prototype.clone = function () {
  5496. var result = new Observable();
  5497. result._observers = this._observers.slice(0);
  5498. return result;
  5499. };
  5500. /**
  5501. * Does this observable handles observer registered with a given mask
  5502. * @param {number} trigger - the mask to be tested
  5503. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5504. **/
  5505. Observable.prototype.hasSpecificMask = function (mask) {
  5506. if (mask === void 0) { mask = -1; }
  5507. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5508. var obs = _a[_i];
  5509. if (obs.mask & mask || obs.mask === mask) {
  5510. return true;
  5511. }
  5512. }
  5513. return false;
  5514. };
  5515. return Observable;
  5516. }());
  5517. BABYLON.Observable = Observable;
  5518. })(BABYLON || (BABYLON = {}));
  5519. //# sourceMappingURL=babylon.observable.js.map
  5520. var BABYLON;
  5521. (function (BABYLON) {
  5522. var SmartArray = (function () {
  5523. function SmartArray(capacity) {
  5524. this.length = 0;
  5525. this._duplicateId = 0;
  5526. this.data = new Array(capacity);
  5527. this._id = SmartArray._GlobalId++;
  5528. }
  5529. SmartArray.prototype.push = function (value) {
  5530. this.data[this.length++] = value;
  5531. if (this.length > this.data.length) {
  5532. this.data.length *= 2;
  5533. }
  5534. if (!value.__smartArrayFlags) {
  5535. value.__smartArrayFlags = {};
  5536. }
  5537. value.__smartArrayFlags[this._id] = this._duplicateId;
  5538. };
  5539. SmartArray.prototype.forEach = function (func) {
  5540. for (var index = 0; index < this.length; index++) {
  5541. func(this.data[index]);
  5542. }
  5543. };
  5544. SmartArray.prototype.pushNoDuplicate = function (value) {
  5545. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5546. return false;
  5547. }
  5548. this.push(value);
  5549. return true;
  5550. };
  5551. SmartArray.prototype.sort = function (compareFn) {
  5552. this.data.sort(compareFn);
  5553. };
  5554. SmartArray.prototype.reset = function () {
  5555. this.length = 0;
  5556. this._duplicateId++;
  5557. };
  5558. SmartArray.prototype.dispose = function () {
  5559. this.reset();
  5560. if (this.data) {
  5561. this.data.length = 0;
  5562. this.data = null;
  5563. }
  5564. };
  5565. SmartArray.prototype.concat = function (array) {
  5566. if (array.length === 0) {
  5567. return;
  5568. }
  5569. if (this.length + array.length > this.data.length) {
  5570. this.data.length = (this.length + array.length) * 2;
  5571. }
  5572. for (var index = 0; index < array.length; index++) {
  5573. this.data[this.length++] = (array.data || array)[index];
  5574. }
  5575. };
  5576. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5577. if (array.length === 0) {
  5578. return;
  5579. }
  5580. if (this.length + array.length > this.data.length) {
  5581. this.data.length = (this.length + array.length) * 2;
  5582. }
  5583. for (var index = 0; index < array.length; index++) {
  5584. var item = (array.data || array)[index];
  5585. this.pushNoDuplicate(item);
  5586. }
  5587. };
  5588. SmartArray.prototype.indexOf = function (value) {
  5589. var position = this.data.indexOf(value);
  5590. if (position >= this.length) {
  5591. return -1;
  5592. }
  5593. return position;
  5594. };
  5595. SmartArray.prototype.contains = function (value) {
  5596. return this.data.indexOf(value) !== -1;
  5597. };
  5598. // Statics
  5599. SmartArray._GlobalId = 0;
  5600. return SmartArray;
  5601. }());
  5602. BABYLON.SmartArray = SmartArray;
  5603. })(BABYLON || (BABYLON = {}));
  5604. //# sourceMappingURL=babylon.smartArray.js.map
  5605. var BABYLON;
  5606. (function (BABYLON) {
  5607. // Screenshots
  5608. var screenshotCanvas;
  5609. var cloneValue = function (source, destinationObject) {
  5610. if (!source)
  5611. return null;
  5612. if (source instanceof BABYLON.Mesh) {
  5613. return null;
  5614. }
  5615. if (source instanceof BABYLON.SubMesh) {
  5616. return source.clone(destinationObject);
  5617. }
  5618. else if (source.clone) {
  5619. return source.clone();
  5620. }
  5621. return null;
  5622. };
  5623. var Tools = (function () {
  5624. function Tools() {
  5625. }
  5626. ;
  5627. /**
  5628. * Interpolates between a and b via alpha
  5629. * @param a The lower value (returned when alpha = 0)
  5630. * @param b The upper value (returned when alpha = 1)
  5631. * @param alpha The interpolation-factor
  5632. * @return The mixed value
  5633. */
  5634. Tools.Mix = function (a, b, alpha) {
  5635. return a * (1 - alpha) + b * alpha;
  5636. };
  5637. Tools.Instantiate = function (className) {
  5638. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  5639. return Tools.RegisteredExternalClasses[className];
  5640. }
  5641. var arr = className.split(".");
  5642. var fn = (window || this);
  5643. for (var i = 0, len = arr.length; i < len; i++) {
  5644. fn = fn[arr[i]];
  5645. }
  5646. if (typeof fn !== "function") {
  5647. return null;
  5648. }
  5649. return fn;
  5650. };
  5651. Tools.SetImmediate = function (action) {
  5652. if (window.setImmediate) {
  5653. window.setImmediate(action);
  5654. }
  5655. else {
  5656. setTimeout(action, 1);
  5657. }
  5658. };
  5659. Tools.IsExponentOfTwo = function (value) {
  5660. var count = 1;
  5661. do {
  5662. count *= 2;
  5663. } while (count < value);
  5664. return count === value;
  5665. };
  5666. /**
  5667. * Find the next highest power of two.
  5668. * @param x Number to start search from.
  5669. * @return Next highest power of two.
  5670. */
  5671. Tools.CeilingPOT = function (x) {
  5672. x--;
  5673. x |= x >> 1;
  5674. x |= x >> 2;
  5675. x |= x >> 4;
  5676. x |= x >> 8;
  5677. x |= x >> 16;
  5678. x++;
  5679. return x;
  5680. };
  5681. /**
  5682. * Find the next lowest power of two.
  5683. * @param x Number to start search from.
  5684. * @return Next lowest power of two.
  5685. */
  5686. Tools.FloorPOT = function (x) {
  5687. x = x | (x >> 1);
  5688. x = x | (x >> 2);
  5689. x = x | (x >> 4);
  5690. x = x | (x >> 8);
  5691. x = x | (x >> 16);
  5692. return x - (x >> 1);
  5693. };
  5694. /**
  5695. * Find the nearest power of two.
  5696. * @param x Number to start search from.
  5697. * @return Next nearest power of two.
  5698. */
  5699. Tools.NearestPOT = function (x) {
  5700. var c = Tools.CeilingPOT(x);
  5701. var f = Tools.FloorPOT(x);
  5702. return (c - x) > (x - f) ? f : c;
  5703. };
  5704. Tools.GetExponentOfTwo = function (value, max, mode) {
  5705. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5706. var pot;
  5707. switch (mode) {
  5708. case BABYLON.Engine.SCALEMODE_FLOOR:
  5709. pot = Tools.FloorPOT(value);
  5710. break;
  5711. case BABYLON.Engine.SCALEMODE_NEAREST:
  5712. pot = Tools.NearestPOT(value);
  5713. break;
  5714. case BABYLON.Engine.SCALEMODE_CEILING:
  5715. pot = Tools.CeilingPOT(value);
  5716. break;
  5717. }
  5718. return Math.min(pot, max);
  5719. };
  5720. Tools.GetFilename = function (path) {
  5721. var index = path.lastIndexOf("/");
  5722. if (index < 0)
  5723. return path;
  5724. return path.substring(index + 1);
  5725. };
  5726. Tools.GetDOMTextContent = function (element) {
  5727. var result = "";
  5728. var child = element.firstChild;
  5729. while (child) {
  5730. if (child.nodeType === 3) {
  5731. result += child.textContent;
  5732. }
  5733. child = child.nextSibling;
  5734. }
  5735. return result;
  5736. };
  5737. Tools.ToDegrees = function (angle) {
  5738. return angle * 180 / Math.PI;
  5739. };
  5740. Tools.ToRadians = function (angle) {
  5741. return angle * Math.PI / 180;
  5742. };
  5743. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5744. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5745. var output = "";
  5746. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5747. var i = 0;
  5748. var bytes = new Uint8Array(buffer);
  5749. while (i < bytes.length) {
  5750. chr1 = bytes[i++];
  5751. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5752. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5753. enc1 = chr1 >> 2;
  5754. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5755. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5756. enc4 = chr3 & 63;
  5757. if (isNaN(chr2)) {
  5758. enc3 = enc4 = 64;
  5759. }
  5760. else if (isNaN(chr3)) {
  5761. enc4 = 64;
  5762. }
  5763. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5764. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5765. }
  5766. return "data:image/png;base64," + output;
  5767. };
  5768. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5769. if (bias === void 0) { bias = null; }
  5770. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5771. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5772. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5773. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5774. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5775. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5776. }
  5777. if (bias) {
  5778. minimum.x -= minimum.x * bias.x + bias.y;
  5779. minimum.y -= minimum.y * bias.x + bias.y;
  5780. minimum.z -= minimum.z * bias.x + bias.y;
  5781. maximum.x += maximum.x * bias.x + bias.y;
  5782. maximum.y += maximum.y * bias.x + bias.y;
  5783. maximum.z += maximum.z * bias.x + bias.y;
  5784. }
  5785. return {
  5786. minimum: minimum,
  5787. maximum: maximum
  5788. };
  5789. };
  5790. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5791. if (bias === void 0) { bias = null; }
  5792. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5793. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5794. if (!stride) {
  5795. stride = 3;
  5796. }
  5797. for (var index = start; index < start + count; index++) {
  5798. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5799. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5800. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5801. }
  5802. if (bias) {
  5803. minimum.x -= minimum.x * bias.x + bias.y;
  5804. minimum.y -= minimum.y * bias.x + bias.y;
  5805. minimum.z -= minimum.z * bias.x + bias.y;
  5806. maximum.x += maximum.x * bias.x + bias.y;
  5807. maximum.y += maximum.y * bias.x + bias.y;
  5808. maximum.z += maximum.z * bias.x + bias.y;
  5809. }
  5810. return {
  5811. minimum: minimum,
  5812. maximum: maximum
  5813. };
  5814. };
  5815. Tools.Vector2ArrayFeeder = function (array) {
  5816. return function (index) {
  5817. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5818. var length = isFloatArray ? array.length / 2 : array.length;
  5819. if (index >= length) {
  5820. return null;
  5821. }
  5822. if (isFloatArray) {
  5823. var fa = array;
  5824. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5825. }
  5826. var a = array;
  5827. return a[index];
  5828. };
  5829. };
  5830. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5831. if (bias === void 0) { bias = null; }
  5832. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5833. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5834. var i = 0;
  5835. var cur = feeder(i++);
  5836. while (cur) {
  5837. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5838. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5839. cur = feeder(i++);
  5840. }
  5841. if (bias) {
  5842. minimum.x -= minimum.x * bias.x + bias.y;
  5843. minimum.y -= minimum.y * bias.x + bias.y;
  5844. maximum.x += maximum.x * bias.x + bias.y;
  5845. maximum.y += maximum.y * bias.x + bias.y;
  5846. }
  5847. return {
  5848. minimum: minimum,
  5849. maximum: maximum
  5850. };
  5851. };
  5852. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5853. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5854. return undefined;
  5855. return Array.isArray(obj) ? obj : [obj];
  5856. };
  5857. // Misc.
  5858. Tools.GetPointerPrefix = function () {
  5859. var eventPrefix = "pointer";
  5860. // Check if pointer events are supported
  5861. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  5862. eventPrefix = "mouse";
  5863. }
  5864. return eventPrefix;
  5865. };
  5866. /**
  5867. * @param func - the function to be called
  5868. * @param requester - the object that will request the next frame. Falls back to window.
  5869. */
  5870. Tools.QueueNewFrame = function (func, requester) {
  5871. if (!Tools.IsWindowObjectExist()) {
  5872. return setTimeout(func, 16);
  5873. }
  5874. if (!requester) {
  5875. requester = window;
  5876. }
  5877. if (requester.requestAnimationFrame) {
  5878. return requester.requestAnimationFrame(func);
  5879. }
  5880. else if (requester.msRequestAnimationFrame) {
  5881. return requester.msRequestAnimationFrame(func);
  5882. }
  5883. else if (requester.webkitRequestAnimationFrame) {
  5884. return requester.webkitRequestAnimationFrame(func);
  5885. }
  5886. else if (requester.mozRequestAnimationFrame) {
  5887. return requester.mozRequestAnimationFrame(func);
  5888. }
  5889. else if (requester.oRequestAnimationFrame) {
  5890. return requester.oRequestAnimationFrame(func);
  5891. }
  5892. else {
  5893. return window.setTimeout(func, 16);
  5894. }
  5895. };
  5896. Tools.RequestFullscreen = function (element) {
  5897. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5898. if (!requestFunction)
  5899. return;
  5900. requestFunction.call(element);
  5901. };
  5902. Tools.ExitFullscreen = function () {
  5903. if (document.exitFullscreen) {
  5904. document.exitFullscreen();
  5905. }
  5906. else if (document.mozCancelFullScreen) {
  5907. document.mozCancelFullScreen();
  5908. }
  5909. else if (document.webkitCancelFullScreen) {
  5910. document.webkitCancelFullScreen();
  5911. }
  5912. else if (document.msCancelFullScreen) {
  5913. document.msCancelFullScreen();
  5914. }
  5915. };
  5916. Tools.SetCorsBehavior = function (url, img) {
  5917. if (Tools.CorsBehavior) {
  5918. switch (typeof (Tools.CorsBehavior)) {
  5919. case "function":
  5920. var result = Tools.CorsBehavior(url);
  5921. if (result) {
  5922. img.crossOrigin = result;
  5923. }
  5924. break;
  5925. case "string":
  5926. default:
  5927. img.crossOrigin = Tools.CorsBehavior;
  5928. break;
  5929. }
  5930. }
  5931. };
  5932. // External files
  5933. Tools.CleanUrl = function (url) {
  5934. url = url.replace(/#/mg, "%23");
  5935. return url;
  5936. };
  5937. Tools.LoadImage = function (url, onLoad, onError, database) {
  5938. if (url instanceof ArrayBuffer) {
  5939. url = Tools.EncodeArrayBufferTobase64(url);
  5940. }
  5941. url = Tools.CleanUrl(url);
  5942. url = Tools.PreprocessUrl(url);
  5943. var img = new Image();
  5944. if (url.substr(0, 5) !== "data:") {
  5945. Tools.SetCorsBehavior(url, img);
  5946. }
  5947. img.onload = function () {
  5948. onLoad(img);
  5949. };
  5950. img.onerror = function (err) {
  5951. Tools.Error("Error while trying to load image: " + url);
  5952. if (Tools.UseFallbackTexture) {
  5953. img.src = Tools.fallbackTexture;
  5954. onLoad(img);
  5955. }
  5956. else {
  5957. onError("Error while trying to load image: " + url, err);
  5958. }
  5959. };
  5960. var noIndexedDB = function () {
  5961. img.src = url;
  5962. };
  5963. var loadFromIndexedDB = function () {
  5964. database.loadImageFromDB(url, img);
  5965. };
  5966. //ANY database to do!
  5967. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5968. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5969. }
  5970. else {
  5971. if (url.indexOf("file:") !== 0) {
  5972. noIndexedDB();
  5973. }
  5974. else {
  5975. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  5976. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5977. try {
  5978. var blobURL;
  5979. try {
  5980. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5981. }
  5982. catch (ex) {
  5983. // Chrome doesn't support oneTimeOnly parameter
  5984. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5985. }
  5986. img.src = blobURL;
  5987. }
  5988. catch (e) {
  5989. img.src = null;
  5990. }
  5991. }
  5992. else {
  5993. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5994. img.src = Tools.fallbackTexture;
  5995. }
  5996. }
  5997. }
  5998. return img;
  5999. };
  6000. //ANY
  6001. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6002. url = Tools.CleanUrl(url);
  6003. url = Tools.PreprocessUrl(url);
  6004. var noIndexedDB = function () {
  6005. var request = new XMLHttpRequest();
  6006. var loadUrl = Tools.BaseUrl + url;
  6007. request.open('GET', loadUrl, true);
  6008. if (useArrayBuffer) {
  6009. request.responseType = "arraybuffer";
  6010. }
  6011. request.onprogress = progressCallBack;
  6012. request.onreadystatechange = function () {
  6013. // In case of undefined state in some browsers.
  6014. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  6015. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6016. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  6017. callback(!useArrayBuffer ? request.responseText : request.response);
  6018. }
  6019. else {
  6020. var e = new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  6021. if (onError) {
  6022. onError(request, e);
  6023. }
  6024. else {
  6025. throw e;
  6026. }
  6027. }
  6028. }
  6029. };
  6030. request.send(null);
  6031. };
  6032. var loadFromIndexedDB = function () {
  6033. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6034. };
  6035. if (url.indexOf("file:") !== -1) {
  6036. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  6037. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6038. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6039. }
  6040. else {
  6041. var errorMessage = "File: " + fileName + " not found. Did you forget to provide it?";
  6042. if (onError) {
  6043. var e = new Error(errorMessage);
  6044. onError(undefined, e);
  6045. }
  6046. else {
  6047. Tools.Error(errorMessage);
  6048. }
  6049. }
  6050. }
  6051. else {
  6052. // Caching all files
  6053. if (database && database.enableSceneOffline) {
  6054. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6055. }
  6056. else {
  6057. noIndexedDB();
  6058. }
  6059. }
  6060. };
  6061. /**
  6062. * Load a script (identified by an url). When the url returns, the
  6063. * content of this file is added into a new script element, attached to the DOM (body element)
  6064. */
  6065. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6066. var head = document.getElementsByTagName('head')[0];
  6067. var script = document.createElement('script');
  6068. script.type = 'text/javascript';
  6069. script.src = scriptUrl;
  6070. var self = this;
  6071. script.onload = function () {
  6072. if (onSuccess) {
  6073. onSuccess();
  6074. }
  6075. };
  6076. script.onerror = function (e) {
  6077. if (onError) {
  6078. onError("Unable to load script", e);
  6079. }
  6080. };
  6081. head.appendChild(script);
  6082. };
  6083. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6084. var reader = new FileReader();
  6085. reader.onload = function (e) {
  6086. //target doesn't have result from ts 1.3
  6087. callback(e.target['result']);
  6088. };
  6089. reader.onprogress = progressCallback;
  6090. reader.readAsDataURL(fileToLoad);
  6091. };
  6092. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6093. var reader = new FileReader();
  6094. reader.onerror = function (e) {
  6095. Tools.Log("Error while reading file: " + fileToLoad.name);
  6096. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6097. };
  6098. reader.onload = function (e) {
  6099. //target doesn't have result from ts 1.3
  6100. callback(e.target['result']);
  6101. };
  6102. reader.onprogress = progressCallBack;
  6103. if (!useArrayBuffer) {
  6104. // Asynchronous read
  6105. reader.readAsText(fileToLoad);
  6106. }
  6107. else {
  6108. reader.readAsArrayBuffer(fileToLoad);
  6109. }
  6110. };
  6111. //returns a downloadable url to a file content.
  6112. Tools.FileAsURL = function (content) {
  6113. var fileBlob = new Blob([content]);
  6114. var url = window.URL || window.webkitURL;
  6115. var link = url.createObjectURL(fileBlob);
  6116. return link;
  6117. };
  6118. // Misc.
  6119. Tools.Format = function (value, decimals) {
  6120. if (decimals === void 0) { decimals = 2; }
  6121. return value.toFixed(decimals);
  6122. };
  6123. Tools.CheckExtends = function (v, min, max) {
  6124. if (v.x < min.x)
  6125. min.x = v.x;
  6126. if (v.y < min.y)
  6127. min.y = v.y;
  6128. if (v.z < min.z)
  6129. min.z = v.z;
  6130. if (v.x > max.x)
  6131. max.x = v.x;
  6132. if (v.y > max.y)
  6133. max.y = v.y;
  6134. if (v.z > max.z)
  6135. max.z = v.z;
  6136. };
  6137. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6138. for (var prop in source) {
  6139. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6140. continue;
  6141. }
  6142. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6143. continue;
  6144. }
  6145. var sourceValue = source[prop];
  6146. var typeOfSourceValue = typeof sourceValue;
  6147. if (typeOfSourceValue === "function") {
  6148. continue;
  6149. }
  6150. if (typeOfSourceValue === "object") {
  6151. if (sourceValue instanceof Array) {
  6152. destination[prop] = [];
  6153. if (sourceValue.length > 0) {
  6154. if (typeof sourceValue[0] == "object") {
  6155. for (var index = 0; index < sourceValue.length; index++) {
  6156. var clonedValue = cloneValue(sourceValue[index], destination);
  6157. if (destination[prop].indexOf(clonedValue) === -1) {
  6158. destination[prop].push(clonedValue);
  6159. }
  6160. }
  6161. }
  6162. else {
  6163. destination[prop] = sourceValue.slice(0);
  6164. }
  6165. }
  6166. }
  6167. else {
  6168. destination[prop] = cloneValue(sourceValue, destination);
  6169. }
  6170. }
  6171. else {
  6172. destination[prop] = sourceValue;
  6173. }
  6174. }
  6175. };
  6176. Tools.IsEmpty = function (obj) {
  6177. for (var i in obj) {
  6178. return false;
  6179. }
  6180. return true;
  6181. };
  6182. Tools.RegisterTopRootEvents = function (events) {
  6183. for (var index = 0; index < events.length; index++) {
  6184. var event = events[index];
  6185. window.addEventListener(event.name, event.handler, false);
  6186. try {
  6187. if (window.parent) {
  6188. window.parent.addEventListener(event.name, event.handler, false);
  6189. }
  6190. }
  6191. catch (e) {
  6192. // Silently fails...
  6193. }
  6194. }
  6195. };
  6196. Tools.UnregisterTopRootEvents = function (events) {
  6197. for (var index = 0; index < events.length; index++) {
  6198. var event = events[index];
  6199. window.removeEventListener(event.name, event.handler);
  6200. try {
  6201. if (window.parent) {
  6202. window.parent.removeEventListener(event.name, event.handler);
  6203. }
  6204. }
  6205. catch (e) {
  6206. // Silently fails...
  6207. }
  6208. }
  6209. };
  6210. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6211. if (mimeType === void 0) { mimeType = "image/png"; }
  6212. // Read the contents of the framebuffer
  6213. var numberOfChannelsByLine = width * 4;
  6214. var halfHeight = height / 2;
  6215. //Reading datas from WebGL
  6216. var data = engine.readPixels(0, 0, width, height);
  6217. //To flip image on Y axis.
  6218. for (var i = 0; i < halfHeight; i++) {
  6219. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6220. var currentCell = j + i * numberOfChannelsByLine;
  6221. var targetLine = height - i - 1;
  6222. var targetCell = j + targetLine * numberOfChannelsByLine;
  6223. var temp = data[currentCell];
  6224. data[currentCell] = data[targetCell];
  6225. data[targetCell] = temp;
  6226. }
  6227. }
  6228. // Create a 2D canvas to store the result
  6229. if (!screenshotCanvas) {
  6230. screenshotCanvas = document.createElement('canvas');
  6231. }
  6232. screenshotCanvas.width = width;
  6233. screenshotCanvas.height = height;
  6234. var context = screenshotCanvas.getContext('2d');
  6235. // Copy the pixels to a 2D canvas
  6236. var imageData = context.createImageData(width, height);
  6237. var castData = (imageData.data);
  6238. castData.set(data);
  6239. context.putImageData(imageData, 0, 0);
  6240. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6241. };
  6242. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6243. if (mimeType === void 0) { mimeType = "image/png"; }
  6244. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6245. if (successCallback) {
  6246. successCallback(base64Image);
  6247. }
  6248. else {
  6249. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6250. if (("download" in document.createElement("a"))) {
  6251. var a = window.document.createElement("a");
  6252. a.href = base64Image;
  6253. var date = new Date();
  6254. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6255. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6256. window.document.body.appendChild(a);
  6257. a.addEventListener("click", function () {
  6258. a.parentElement.removeChild(a);
  6259. });
  6260. a.click();
  6261. //Or opening a new tab with the image if it is not possible to automatically start download.
  6262. }
  6263. else {
  6264. var newWindow = window.open("");
  6265. var img = newWindow.document.createElement("img");
  6266. img.src = base64Image;
  6267. newWindow.document.body.appendChild(img);
  6268. }
  6269. }
  6270. };
  6271. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6272. if (mimeType === void 0) { mimeType = "image/png"; }
  6273. var width;
  6274. var height;
  6275. // If a precision value is specified
  6276. if (size.precision) {
  6277. width = Math.round(engine.getRenderWidth() * size.precision);
  6278. height = Math.round(width / engine.getAspectRatio(camera));
  6279. }
  6280. else if (size.width && size.height) {
  6281. width = size.width;
  6282. height = size.height;
  6283. }
  6284. else if (size.width && !size.height) {
  6285. width = size.width;
  6286. height = Math.round(width / engine.getAspectRatio(camera));
  6287. }
  6288. else if (size.height && !size.width) {
  6289. height = size.height;
  6290. width = Math.round(height * engine.getAspectRatio(camera));
  6291. }
  6292. else if (!isNaN(size)) {
  6293. height = size;
  6294. width = size;
  6295. }
  6296. else {
  6297. Tools.Error("Invalid 'size' parameter !");
  6298. return;
  6299. }
  6300. if (!screenshotCanvas) {
  6301. screenshotCanvas = document.createElement('canvas');
  6302. }
  6303. screenshotCanvas.width = width;
  6304. screenshotCanvas.height = height;
  6305. var renderContext = screenshotCanvas.getContext("2d");
  6306. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6307. var newWidth = width;
  6308. var newHeight = newWidth / ratio;
  6309. if (newHeight > height) {
  6310. newHeight = height;
  6311. newWidth = newHeight * ratio;
  6312. }
  6313. var offsetX = Math.max(0, width - newWidth) / 2;
  6314. var offsetY = Math.max(0, height - newHeight) / 2;
  6315. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6316. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6317. };
  6318. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6319. if (mimeType === void 0) { mimeType = "image/png"; }
  6320. if (samples === void 0) { samples = 1; }
  6321. var width;
  6322. var height;
  6323. //If a precision value is specified
  6324. if (size.precision) {
  6325. width = Math.round(engine.getRenderWidth() * size.precision);
  6326. height = Math.round(width / engine.getAspectRatio(camera));
  6327. size = { width: width, height: height };
  6328. }
  6329. else if (size.width && size.height) {
  6330. width = size.width;
  6331. height = size.height;
  6332. }
  6333. else if (size.width && !size.height) {
  6334. width = size.width;
  6335. height = Math.round(width / engine.getAspectRatio(camera));
  6336. size = { width: width, height: height };
  6337. }
  6338. else if (size.height && !size.width) {
  6339. height = size.height;
  6340. width = Math.round(height * engine.getAspectRatio(camera));
  6341. size = { width: width, height: height };
  6342. }
  6343. else if (!isNaN(size)) {
  6344. height = size;
  6345. width = size;
  6346. }
  6347. else {
  6348. Tools.Error("Invalid 'size' parameter !");
  6349. return;
  6350. }
  6351. var scene = camera.getScene();
  6352. var previousCamera = null;
  6353. if (scene.activeCamera !== camera) {
  6354. previousCamera = scene.activeCamera;
  6355. scene.activeCamera = camera;
  6356. }
  6357. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6358. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6359. texture.renderList = null;
  6360. texture.samples = samples;
  6361. texture.onAfterRenderObservable.add(function () {
  6362. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6363. });
  6364. scene.incrementRenderId();
  6365. scene.resetCachedMaterial();
  6366. texture.render(true);
  6367. texture.dispose();
  6368. if (previousCamera) {
  6369. scene.activeCamera = previousCamera;
  6370. }
  6371. camera.getProjectionMatrix(true); // Force cache refresh;
  6372. };
  6373. // XHR response validator for local file scenario
  6374. Tools.ValidateXHRData = function (xhr, dataType) {
  6375. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6376. if (dataType === void 0) { dataType = 7; }
  6377. try {
  6378. if (dataType & 1) {
  6379. if (xhr.responseText && xhr.responseText.length > 0) {
  6380. return true;
  6381. }
  6382. else if (dataType === 1) {
  6383. return false;
  6384. }
  6385. }
  6386. if (dataType & 2) {
  6387. // Check header width and height since there is no "TGA" magic number
  6388. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6389. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6390. return true;
  6391. }
  6392. else if (dataType === 2) {
  6393. return false;
  6394. }
  6395. }
  6396. if (dataType & 4) {
  6397. // Check for the "DDS" magic number
  6398. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6399. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6400. return true;
  6401. }
  6402. else {
  6403. return false;
  6404. }
  6405. }
  6406. }
  6407. catch (e) {
  6408. // Global protection
  6409. }
  6410. return false;
  6411. };
  6412. /**
  6413. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6414. * Be aware Math.random() could cause collisions, but:
  6415. * "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"
  6416. */
  6417. Tools.RandomId = function () {
  6418. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6419. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6420. return v.toString(16);
  6421. });
  6422. };
  6423. Object.defineProperty(Tools, "NoneLogLevel", {
  6424. get: function () {
  6425. return Tools._NoneLogLevel;
  6426. },
  6427. enumerable: true,
  6428. configurable: true
  6429. });
  6430. Object.defineProperty(Tools, "MessageLogLevel", {
  6431. get: function () {
  6432. return Tools._MessageLogLevel;
  6433. },
  6434. enumerable: true,
  6435. configurable: true
  6436. });
  6437. Object.defineProperty(Tools, "WarningLogLevel", {
  6438. get: function () {
  6439. return Tools._WarningLogLevel;
  6440. },
  6441. enumerable: true,
  6442. configurable: true
  6443. });
  6444. Object.defineProperty(Tools, "ErrorLogLevel", {
  6445. get: function () {
  6446. return Tools._ErrorLogLevel;
  6447. },
  6448. enumerable: true,
  6449. configurable: true
  6450. });
  6451. Object.defineProperty(Tools, "AllLogLevel", {
  6452. get: function () {
  6453. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6454. },
  6455. enumerable: true,
  6456. configurable: true
  6457. });
  6458. Tools._AddLogEntry = function (entry) {
  6459. Tools._LogCache = entry + Tools._LogCache;
  6460. if (Tools.OnNewCacheEntry) {
  6461. Tools.OnNewCacheEntry(entry);
  6462. }
  6463. };
  6464. Tools._FormatMessage = function (message) {
  6465. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6466. var date = new Date();
  6467. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6468. };
  6469. Tools._LogDisabled = function (message) {
  6470. // nothing to do
  6471. };
  6472. Tools._LogEnabled = function (message) {
  6473. var formattedMessage = Tools._FormatMessage(message);
  6474. console.log("BJS - " + formattedMessage);
  6475. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6476. Tools._AddLogEntry(entry);
  6477. };
  6478. Tools._WarnDisabled = function (message) {
  6479. // nothing to do
  6480. };
  6481. Tools._WarnEnabled = function (message) {
  6482. var formattedMessage = Tools._FormatMessage(message);
  6483. console.warn("BJS - " + formattedMessage);
  6484. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6485. Tools._AddLogEntry(entry);
  6486. };
  6487. Tools._ErrorDisabled = function (message) {
  6488. // nothing to do
  6489. };
  6490. Tools._ErrorEnabled = function (message) {
  6491. Tools.errorsCount++;
  6492. var formattedMessage = Tools._FormatMessage(message);
  6493. console.error("BJS - " + formattedMessage);
  6494. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6495. Tools._AddLogEntry(entry);
  6496. };
  6497. Object.defineProperty(Tools, "LogCache", {
  6498. get: function () {
  6499. return Tools._LogCache;
  6500. },
  6501. enumerable: true,
  6502. configurable: true
  6503. });
  6504. Tools.ClearLogCache = function () {
  6505. Tools._LogCache = "";
  6506. Tools.errorsCount = 0;
  6507. };
  6508. Object.defineProperty(Tools, "LogLevels", {
  6509. set: function (level) {
  6510. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6511. Tools.Log = Tools._LogEnabled;
  6512. }
  6513. else {
  6514. Tools.Log = Tools._LogDisabled;
  6515. }
  6516. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6517. Tools.Warn = Tools._WarnEnabled;
  6518. }
  6519. else {
  6520. Tools.Warn = Tools._WarnDisabled;
  6521. }
  6522. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6523. Tools.Error = Tools._ErrorEnabled;
  6524. }
  6525. else {
  6526. Tools.Error = Tools._ErrorDisabled;
  6527. }
  6528. },
  6529. enumerable: true,
  6530. configurable: true
  6531. });
  6532. Tools.IsWindowObjectExist = function () {
  6533. return (typeof window) !== "undefined";
  6534. };
  6535. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6536. get: function () {
  6537. return Tools._PerformanceNoneLogLevel;
  6538. },
  6539. enumerable: true,
  6540. configurable: true
  6541. });
  6542. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6543. get: function () {
  6544. return Tools._PerformanceUserMarkLogLevel;
  6545. },
  6546. enumerable: true,
  6547. configurable: true
  6548. });
  6549. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6550. get: function () {
  6551. return Tools._PerformanceConsoleLogLevel;
  6552. },
  6553. enumerable: true,
  6554. configurable: true
  6555. });
  6556. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6557. set: function (level) {
  6558. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6559. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6560. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6561. return;
  6562. }
  6563. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6564. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6565. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6566. return;
  6567. }
  6568. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6569. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6570. },
  6571. enumerable: true,
  6572. configurable: true
  6573. });
  6574. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6575. };
  6576. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6577. };
  6578. Tools._StartUserMark = function (counterName, condition) {
  6579. if (condition === void 0) { condition = true; }
  6580. if (!Tools._performance) {
  6581. if (!Tools.IsWindowObjectExist()) {
  6582. return;
  6583. }
  6584. Tools._performance = window.performance;
  6585. }
  6586. if (!condition || !Tools._performance.mark) {
  6587. return;
  6588. }
  6589. Tools._performance.mark(counterName + "-Begin");
  6590. };
  6591. Tools._EndUserMark = function (counterName, condition) {
  6592. if (condition === void 0) { condition = true; }
  6593. if (!condition || !Tools._performance.mark) {
  6594. return;
  6595. }
  6596. Tools._performance.mark(counterName + "-End");
  6597. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6598. };
  6599. Tools._StartPerformanceConsole = function (counterName, condition) {
  6600. if (condition === void 0) { condition = true; }
  6601. if (!condition) {
  6602. return;
  6603. }
  6604. Tools._StartUserMark(counterName, condition);
  6605. if (console.time) {
  6606. console.time(counterName);
  6607. }
  6608. };
  6609. Tools._EndPerformanceConsole = function (counterName, condition) {
  6610. if (condition === void 0) { condition = true; }
  6611. if (!condition) {
  6612. return;
  6613. }
  6614. Tools._EndUserMark(counterName, condition);
  6615. if (console.time) {
  6616. console.timeEnd(counterName);
  6617. }
  6618. };
  6619. Object.defineProperty(Tools, "Now", {
  6620. get: function () {
  6621. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  6622. return window.performance.now();
  6623. }
  6624. return new Date().getTime();
  6625. },
  6626. enumerable: true,
  6627. configurable: true
  6628. });
  6629. /**
  6630. * This method will return the name of the class used to create the instance of the given object.
  6631. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6632. * @param object the object to get the class name from
  6633. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6634. */
  6635. Tools.GetClassName = function (object, isType) {
  6636. if (isType === void 0) { isType = false; }
  6637. var name = null;
  6638. if (!isType && object.getClassName) {
  6639. name = object.getClassName();
  6640. }
  6641. else {
  6642. if (object instanceof Object) {
  6643. var classObj = isType ? object : Object.getPrototypeOf(object);
  6644. name = classObj.constructor["__bjsclassName__"];
  6645. }
  6646. if (!name) {
  6647. name = typeof object;
  6648. }
  6649. }
  6650. return name;
  6651. };
  6652. Tools.first = function (array, predicate) {
  6653. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6654. var el = array_1[_i];
  6655. if (predicate(el)) {
  6656. return el;
  6657. }
  6658. }
  6659. };
  6660. /**
  6661. * This method will return the name of the full name of the class, including its owning module (if any).
  6662. * 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).
  6663. * @param object the object to get the class name from
  6664. * @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.
  6665. */
  6666. Tools.getFullClassName = function (object, isType) {
  6667. if (isType === void 0) { isType = false; }
  6668. var className = null;
  6669. var moduleName = null;
  6670. if (!isType && object.getClassName) {
  6671. className = object.getClassName();
  6672. }
  6673. else {
  6674. if (object instanceof Object) {
  6675. var classObj = isType ? object : Object.getPrototypeOf(object);
  6676. className = classObj.constructor["__bjsclassName__"];
  6677. moduleName = classObj.constructor["__bjsmoduleName__"];
  6678. }
  6679. if (!className) {
  6680. className = typeof object;
  6681. }
  6682. }
  6683. if (!className) {
  6684. return null;
  6685. }
  6686. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6687. };
  6688. /**
  6689. * 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.
  6690. * @param array
  6691. */
  6692. Tools.arrayOrStringFeeder = function (array) {
  6693. return function (index) {
  6694. if (index >= array.length) {
  6695. return null;
  6696. }
  6697. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6698. if (val && val.getHashCode) {
  6699. val = val.getHashCode();
  6700. }
  6701. if (typeof val === "string") {
  6702. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6703. }
  6704. return val;
  6705. };
  6706. };
  6707. /**
  6708. * Compute the hashCode of a stream of number
  6709. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6710. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6711. * @return the hash code computed
  6712. */
  6713. Tools.hashCodeFromStream = function (feeder) {
  6714. // Based from here: http://stackoverflow.com/a/7616484/802124
  6715. var hash = 0;
  6716. var index = 0;
  6717. var chr = feeder(index++);
  6718. while (chr != null) {
  6719. hash = ((hash << 5) - hash) + chr;
  6720. hash |= 0; // Convert to 32bit integer
  6721. chr = feeder(index++);
  6722. }
  6723. return hash;
  6724. };
  6725. Tools.BaseUrl = "";
  6726. Tools.CorsBehavior = "anonymous";
  6727. Tools.UseFallbackTexture = true;
  6728. /**
  6729. * Use this object to register external classes like custom textures or material
  6730. * to allow the laoders to instantiate them
  6731. */
  6732. Tools.RegisteredExternalClasses = {};
  6733. // Used in case of a texture loading problem
  6734. 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";
  6735. Tools.PreprocessUrl = function (url) {
  6736. return url;
  6737. };
  6738. // Logs
  6739. Tools._NoneLogLevel = 0;
  6740. Tools._MessageLogLevel = 1;
  6741. Tools._WarningLogLevel = 2;
  6742. Tools._ErrorLogLevel = 4;
  6743. Tools._LogCache = "";
  6744. Tools.errorsCount = 0;
  6745. Tools.Log = Tools._LogEnabled;
  6746. Tools.Warn = Tools._WarnEnabled;
  6747. Tools.Error = Tools._ErrorEnabled;
  6748. // Performances
  6749. Tools._PerformanceNoneLogLevel = 0;
  6750. Tools._PerformanceUserMarkLogLevel = 1;
  6751. Tools._PerformanceConsoleLogLevel = 2;
  6752. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6753. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6754. return Tools;
  6755. }());
  6756. BABYLON.Tools = Tools;
  6757. /**
  6758. * This class is used to track a performance counter which is number based.
  6759. * The user has access to many properties which give statistics of different nature
  6760. *
  6761. * The implementer can track two kinds of Performance Counter: time and count
  6762. * 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.
  6763. * 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.
  6764. */
  6765. var PerfCounter = (function () {
  6766. function PerfCounter() {
  6767. this._startMonitoringTime = 0;
  6768. this._min = 0;
  6769. this._max = 0;
  6770. this._average = 0;
  6771. this._lastSecAverage = 0;
  6772. this._current = 0;
  6773. this._totalValueCount = 0;
  6774. this._totalAccumulated = 0;
  6775. this._lastSecAccumulated = 0;
  6776. this._lastSecTime = 0;
  6777. this._lastSecValueCount = 0;
  6778. }
  6779. Object.defineProperty(PerfCounter.prototype, "min", {
  6780. /**
  6781. * Returns the smallest value ever
  6782. */
  6783. get: function () {
  6784. return this._min;
  6785. },
  6786. enumerable: true,
  6787. configurable: true
  6788. });
  6789. Object.defineProperty(PerfCounter.prototype, "max", {
  6790. /**
  6791. * Returns the biggest value ever
  6792. */
  6793. get: function () {
  6794. return this._max;
  6795. },
  6796. enumerable: true,
  6797. configurable: true
  6798. });
  6799. Object.defineProperty(PerfCounter.prototype, "average", {
  6800. /**
  6801. * Returns the average value since the performance counter is running
  6802. */
  6803. get: function () {
  6804. return this._average;
  6805. },
  6806. enumerable: true,
  6807. configurable: true
  6808. });
  6809. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6810. /**
  6811. * Returns the average value of the last second the counter was monitored
  6812. */
  6813. get: function () {
  6814. return this._lastSecAverage;
  6815. },
  6816. enumerable: true,
  6817. configurable: true
  6818. });
  6819. Object.defineProperty(PerfCounter.prototype, "current", {
  6820. /**
  6821. * Returns the current value
  6822. */
  6823. get: function () {
  6824. return this._current;
  6825. },
  6826. enumerable: true,
  6827. configurable: true
  6828. });
  6829. Object.defineProperty(PerfCounter.prototype, "total", {
  6830. get: function () {
  6831. return this._totalAccumulated;
  6832. },
  6833. enumerable: true,
  6834. configurable: true
  6835. });
  6836. /**
  6837. * Call this method to start monitoring a new frame.
  6838. * 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.
  6839. */
  6840. PerfCounter.prototype.fetchNewFrame = function () {
  6841. this._totalValueCount++;
  6842. this._current = 0;
  6843. this._lastSecValueCount++;
  6844. };
  6845. /**
  6846. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6847. * @param newCount the count value to add to the monitored count
  6848. * @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.
  6849. */
  6850. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6851. if (!PerfCounter.Enabled) {
  6852. return;
  6853. }
  6854. this._current += newCount;
  6855. if (fetchResult) {
  6856. this._fetchResult();
  6857. }
  6858. };
  6859. /**
  6860. * Start monitoring this performance counter
  6861. */
  6862. PerfCounter.prototype.beginMonitoring = function () {
  6863. if (!PerfCounter.Enabled) {
  6864. return;
  6865. }
  6866. this._startMonitoringTime = Tools.Now;
  6867. };
  6868. /**
  6869. * Compute the time lapsed since the previous beginMonitoring() call.
  6870. * @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
  6871. */
  6872. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6873. if (newFrame === void 0) { newFrame = true; }
  6874. if (!PerfCounter.Enabled) {
  6875. return;
  6876. }
  6877. if (newFrame) {
  6878. this.fetchNewFrame();
  6879. }
  6880. var currentTime = Tools.Now;
  6881. this._current = currentTime - this._startMonitoringTime;
  6882. if (newFrame) {
  6883. this._fetchResult();
  6884. }
  6885. };
  6886. PerfCounter.prototype._fetchResult = function () {
  6887. this._totalAccumulated += this._current;
  6888. this._lastSecAccumulated += this._current;
  6889. // Min/Max update
  6890. this._min = Math.min(this._min, this._current);
  6891. this._max = Math.max(this._max, this._current);
  6892. this._average = this._totalAccumulated / this._totalValueCount;
  6893. // Reset last sec?
  6894. var now = Tools.Now;
  6895. if ((now - this._lastSecTime) > 1000) {
  6896. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6897. this._lastSecTime = now;
  6898. this._lastSecAccumulated = 0;
  6899. this._lastSecValueCount = 0;
  6900. }
  6901. };
  6902. PerfCounter.Enabled = true;
  6903. return PerfCounter;
  6904. }());
  6905. BABYLON.PerfCounter = PerfCounter;
  6906. /**
  6907. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6908. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6909. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6910. * @param name The name of the class, case should be preserved
  6911. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6912. */
  6913. function className(name, module) {
  6914. return function (target) {
  6915. target["__bjsclassName__"] = name;
  6916. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6917. };
  6918. }
  6919. BABYLON.className = className;
  6920. /**
  6921. * An implementation of a loop for asynchronous functions.
  6922. */
  6923. var AsyncLoop = (function () {
  6924. /**
  6925. * Constroctor.
  6926. * @param iterations the number of iterations.
  6927. * @param _fn the function to run each iteration
  6928. * @param _successCallback the callback that will be called upon succesful execution
  6929. * @param offset starting offset.
  6930. */
  6931. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6932. if (offset === void 0) { offset = 0; }
  6933. this.iterations = iterations;
  6934. this._fn = _fn;
  6935. this._successCallback = _successCallback;
  6936. this.index = offset - 1;
  6937. this._done = false;
  6938. }
  6939. /**
  6940. * Execute the next iteration. Must be called after the last iteration was finished.
  6941. */
  6942. AsyncLoop.prototype.executeNext = function () {
  6943. if (!this._done) {
  6944. if (this.index + 1 < this.iterations) {
  6945. ++this.index;
  6946. this._fn(this);
  6947. }
  6948. else {
  6949. this.breakLoop();
  6950. }
  6951. }
  6952. };
  6953. /**
  6954. * Break the loop and run the success callback.
  6955. */
  6956. AsyncLoop.prototype.breakLoop = function () {
  6957. this._done = true;
  6958. this._successCallback();
  6959. };
  6960. /**
  6961. * Helper function
  6962. */
  6963. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6964. if (offset === void 0) { offset = 0; }
  6965. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6966. loop.executeNext();
  6967. return loop;
  6968. };
  6969. /**
  6970. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6971. * @param iterations total number of iterations
  6972. * @param syncedIterations number of synchronous iterations in each async iteration.
  6973. * @param fn the function to call each iteration.
  6974. * @param callback a success call back that will be called when iterating stops.
  6975. * @param breakFunction a break condition (optional)
  6976. * @param timeout timeout settings for the setTimeout function. default - 0.
  6977. * @constructor
  6978. */
  6979. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6980. if (timeout === void 0) { timeout = 0; }
  6981. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6982. if (breakFunction && breakFunction())
  6983. loop.breakLoop();
  6984. else {
  6985. setTimeout(function () {
  6986. for (var i = 0; i < syncedIterations; ++i) {
  6987. var iteration = (loop.index * syncedIterations) + i;
  6988. if (iteration >= iterations)
  6989. break;
  6990. fn(iteration);
  6991. if (breakFunction && breakFunction()) {
  6992. loop.breakLoop();
  6993. break;
  6994. }
  6995. }
  6996. loop.executeNext();
  6997. }, timeout);
  6998. }
  6999. }, callback);
  7000. };
  7001. return AsyncLoop;
  7002. }());
  7003. BABYLON.AsyncLoop = AsyncLoop;
  7004. })(BABYLON || (BABYLON = {}));
  7005. //# sourceMappingURL=babylon.tools.js.map
  7006. var BABYLON;
  7007. (function (BABYLON) {
  7008. var Internals;
  7009. (function (Internals) {
  7010. var _AlphaState = (function () {
  7011. /**
  7012. * Initializes the state.
  7013. */
  7014. function _AlphaState() {
  7015. this._isAlphaBlendDirty = false;
  7016. this._isBlendFunctionParametersDirty = false;
  7017. this._isBlendEquationParametersDirty = false;
  7018. this._isBlendConstantsDirty = false;
  7019. this._alphaBlend = false;
  7020. this._blendFunctionParameters = new Array(4);
  7021. this._blendEquationParameters = new Array(2);
  7022. this._blendConstants = new Array(4);
  7023. this.reset();
  7024. }
  7025. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7026. get: function () {
  7027. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7028. },
  7029. enumerable: true,
  7030. configurable: true
  7031. });
  7032. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7033. get: function () {
  7034. return this._alphaBlend;
  7035. },
  7036. set: function (value) {
  7037. if (this._alphaBlend === value) {
  7038. return;
  7039. }
  7040. this._alphaBlend = value;
  7041. this._isAlphaBlendDirty = true;
  7042. },
  7043. enumerable: true,
  7044. configurable: true
  7045. });
  7046. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  7047. if (this._blendConstants[0] === r &&
  7048. this._blendConstants[1] === g &&
  7049. this._blendConstants[2] === b &&
  7050. this._blendConstants[3] === a) {
  7051. return;
  7052. }
  7053. this._blendConstants[0] = r;
  7054. this._blendConstants[1] = g;
  7055. this._blendConstants[2] = b;
  7056. this._blendConstants[3] = a;
  7057. this._isBlendConstantsDirty = true;
  7058. };
  7059. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7060. if (this._blendFunctionParameters[0] === value0 &&
  7061. this._blendFunctionParameters[1] === value1 &&
  7062. this._blendFunctionParameters[2] === value2 &&
  7063. this._blendFunctionParameters[3] === value3) {
  7064. return;
  7065. }
  7066. this._blendFunctionParameters[0] = value0;
  7067. this._blendFunctionParameters[1] = value1;
  7068. this._blendFunctionParameters[2] = value2;
  7069. this._blendFunctionParameters[3] = value3;
  7070. this._isBlendFunctionParametersDirty = true;
  7071. };
  7072. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7073. if (this._blendEquationParameters[0] === rgb &&
  7074. this._blendEquationParameters[1] === alpha) {
  7075. return;
  7076. }
  7077. this._blendEquationParameters[0] = rgb;
  7078. this._blendEquationParameters[1] = alpha;
  7079. this._isBlendEquationParametersDirty = true;
  7080. };
  7081. _AlphaState.prototype.reset = function () {
  7082. this._alphaBlend = false;
  7083. this._blendFunctionParameters[0] = null;
  7084. this._blendFunctionParameters[1] = null;
  7085. this._blendFunctionParameters[2] = null;
  7086. this._blendFunctionParameters[3] = null;
  7087. this._blendEquationParameters[0] = null;
  7088. this._blendEquationParameters[1] = null;
  7089. this._blendConstants[0] = null;
  7090. this._blendConstants[1] = null;
  7091. this._blendConstants[2] = null;
  7092. this._blendConstants[3] = null;
  7093. this._isAlphaBlendDirty = true;
  7094. this._isBlendFunctionParametersDirty = false;
  7095. this._isBlendEquationParametersDirty = false;
  7096. this._isBlendConstantsDirty = false;
  7097. };
  7098. _AlphaState.prototype.apply = function (gl) {
  7099. if (!this.isDirty) {
  7100. return;
  7101. }
  7102. // Alpha blend
  7103. if (this._isAlphaBlendDirty) {
  7104. if (this._alphaBlend) {
  7105. gl.enable(gl.BLEND);
  7106. }
  7107. else {
  7108. gl.disable(gl.BLEND);
  7109. }
  7110. this._isAlphaBlendDirty = false;
  7111. }
  7112. // Alpha function
  7113. if (this._isBlendFunctionParametersDirty) {
  7114. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7115. this._isBlendFunctionParametersDirty = false;
  7116. }
  7117. // Alpha equation
  7118. if (this._isBlendEquationParametersDirty) {
  7119. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7120. this._isBlendEquationParametersDirty = false;
  7121. }
  7122. // Constants
  7123. if (this._isBlendConstantsDirty) {
  7124. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7125. this._isBlendConstantsDirty = false;
  7126. }
  7127. };
  7128. return _AlphaState;
  7129. }());
  7130. Internals._AlphaState = _AlphaState;
  7131. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7132. })(BABYLON || (BABYLON = {}));
  7133. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7134. var BABYLON;
  7135. (function (BABYLON) {
  7136. var Internals;
  7137. (function (Internals) {
  7138. var _DepthCullingState = (function () {
  7139. /**
  7140. * Initializes the state.
  7141. */
  7142. function _DepthCullingState() {
  7143. this._isDepthTestDirty = false;
  7144. this._isDepthMaskDirty = false;
  7145. this._isDepthFuncDirty = false;
  7146. this._isCullFaceDirty = false;
  7147. this._isCullDirty = false;
  7148. this._isZOffsetDirty = false;
  7149. this.reset();
  7150. }
  7151. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7152. get: function () {
  7153. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7154. },
  7155. enumerable: true,
  7156. configurable: true
  7157. });
  7158. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7159. get: function () {
  7160. return this._zOffset;
  7161. },
  7162. set: function (value) {
  7163. if (this._zOffset === value) {
  7164. return;
  7165. }
  7166. this._zOffset = value;
  7167. this._isZOffsetDirty = true;
  7168. },
  7169. enumerable: true,
  7170. configurable: true
  7171. });
  7172. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7173. get: function () {
  7174. return this._cullFace;
  7175. },
  7176. set: function (value) {
  7177. if (this._cullFace === value) {
  7178. return;
  7179. }
  7180. this._cullFace = value;
  7181. this._isCullFaceDirty = true;
  7182. },
  7183. enumerable: true,
  7184. configurable: true
  7185. });
  7186. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7187. get: function () {
  7188. return this._cull;
  7189. },
  7190. set: function (value) {
  7191. if (this._cull === value) {
  7192. return;
  7193. }
  7194. this._cull = value;
  7195. this._isCullDirty = true;
  7196. },
  7197. enumerable: true,
  7198. configurable: true
  7199. });
  7200. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7201. get: function () {
  7202. return this._depthFunc;
  7203. },
  7204. set: function (value) {
  7205. if (this._depthFunc === value) {
  7206. return;
  7207. }
  7208. this._depthFunc = value;
  7209. this._isDepthFuncDirty = true;
  7210. },
  7211. enumerable: true,
  7212. configurable: true
  7213. });
  7214. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7215. get: function () {
  7216. return this._depthMask;
  7217. },
  7218. set: function (value) {
  7219. if (this._depthMask === value) {
  7220. return;
  7221. }
  7222. this._depthMask = value;
  7223. this._isDepthMaskDirty = true;
  7224. },
  7225. enumerable: true,
  7226. configurable: true
  7227. });
  7228. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7229. get: function () {
  7230. return this._depthTest;
  7231. },
  7232. set: function (value) {
  7233. if (this._depthTest === value) {
  7234. return;
  7235. }
  7236. this._depthTest = value;
  7237. this._isDepthTestDirty = true;
  7238. },
  7239. enumerable: true,
  7240. configurable: true
  7241. });
  7242. _DepthCullingState.prototype.reset = function () {
  7243. this._depthMask = true;
  7244. this._depthTest = true;
  7245. this._depthFunc = null;
  7246. this._cullFace = null;
  7247. this._cull = null;
  7248. this._zOffset = 0;
  7249. this._isDepthTestDirty = true;
  7250. this._isDepthMaskDirty = true;
  7251. this._isDepthFuncDirty = false;
  7252. this._isCullFaceDirty = false;
  7253. this._isCullDirty = false;
  7254. this._isZOffsetDirty = false;
  7255. };
  7256. _DepthCullingState.prototype.apply = function (gl) {
  7257. if (!this.isDirty) {
  7258. return;
  7259. }
  7260. // Cull
  7261. if (this._isCullDirty) {
  7262. if (this.cull) {
  7263. gl.enable(gl.CULL_FACE);
  7264. }
  7265. else {
  7266. gl.disable(gl.CULL_FACE);
  7267. }
  7268. this._isCullDirty = false;
  7269. }
  7270. // Cull face
  7271. if (this._isCullFaceDirty) {
  7272. gl.cullFace(this.cullFace);
  7273. this._isCullFaceDirty = false;
  7274. }
  7275. // Depth mask
  7276. if (this._isDepthMaskDirty) {
  7277. gl.depthMask(this.depthMask);
  7278. this._isDepthMaskDirty = false;
  7279. }
  7280. // Depth test
  7281. if (this._isDepthTestDirty) {
  7282. if (this.depthTest) {
  7283. gl.enable(gl.DEPTH_TEST);
  7284. }
  7285. else {
  7286. gl.disable(gl.DEPTH_TEST);
  7287. }
  7288. this._isDepthTestDirty = false;
  7289. }
  7290. // Depth func
  7291. if (this._isDepthFuncDirty) {
  7292. gl.depthFunc(this.depthFunc);
  7293. this._isDepthFuncDirty = false;
  7294. }
  7295. // zOffset
  7296. if (this._isZOffsetDirty) {
  7297. if (this.zOffset) {
  7298. gl.enable(gl.POLYGON_OFFSET_FILL);
  7299. gl.polygonOffset(this.zOffset, 0);
  7300. }
  7301. else {
  7302. gl.disable(gl.POLYGON_OFFSET_FILL);
  7303. }
  7304. this._isZOffsetDirty = false;
  7305. }
  7306. };
  7307. return _DepthCullingState;
  7308. }());
  7309. Internals._DepthCullingState = _DepthCullingState;
  7310. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7311. })(BABYLON || (BABYLON = {}));
  7312. //# sourceMappingURL=babylon.depthCullingState.js.map
  7313. var BABYLON;
  7314. (function (BABYLON) {
  7315. var Internals;
  7316. (function (Internals) {
  7317. var _StencilState = (function () {
  7318. function _StencilState() {
  7319. this._isStencilTestDirty = false;
  7320. this._isStencilMaskDirty = false;
  7321. this._isStencilFuncDirty = false;
  7322. this._isStencilOpDirty = false;
  7323. this.reset();
  7324. }
  7325. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7326. get: function () {
  7327. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7328. },
  7329. enumerable: true,
  7330. configurable: true
  7331. });
  7332. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7333. get: function () {
  7334. return this._stencilFunc;
  7335. },
  7336. set: function (value) {
  7337. if (this._stencilFunc === value) {
  7338. return;
  7339. }
  7340. this._stencilFunc = value;
  7341. this._isStencilFuncDirty = true;
  7342. },
  7343. enumerable: true,
  7344. configurable: true
  7345. });
  7346. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7347. get: function () {
  7348. return this._stencilFuncRef;
  7349. },
  7350. set: function (value) {
  7351. if (this._stencilFuncRef === value) {
  7352. return;
  7353. }
  7354. this._stencilFuncRef = value;
  7355. this._isStencilFuncDirty = true;
  7356. },
  7357. enumerable: true,
  7358. configurable: true
  7359. });
  7360. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7361. get: function () {
  7362. return this._stencilFuncMask;
  7363. },
  7364. set: function (value) {
  7365. if (this._stencilFuncMask === value) {
  7366. return;
  7367. }
  7368. this._stencilFuncMask = value;
  7369. this._isStencilFuncDirty = true;
  7370. },
  7371. enumerable: true,
  7372. configurable: true
  7373. });
  7374. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7375. get: function () {
  7376. return this._stencilOpStencilFail;
  7377. },
  7378. set: function (value) {
  7379. if (this._stencilOpStencilFail === value) {
  7380. return;
  7381. }
  7382. this._stencilOpStencilFail = value;
  7383. this._isStencilOpDirty = true;
  7384. },
  7385. enumerable: true,
  7386. configurable: true
  7387. });
  7388. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7389. get: function () {
  7390. return this._stencilOpDepthFail;
  7391. },
  7392. set: function (value) {
  7393. if (this._stencilOpDepthFail === value) {
  7394. return;
  7395. }
  7396. this._stencilOpDepthFail = value;
  7397. this._isStencilOpDirty = true;
  7398. },
  7399. enumerable: true,
  7400. configurable: true
  7401. });
  7402. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7403. get: function () {
  7404. return this._stencilOpStencilDepthPass;
  7405. },
  7406. set: function (value) {
  7407. if (this._stencilOpStencilDepthPass === value) {
  7408. return;
  7409. }
  7410. this._stencilOpStencilDepthPass = value;
  7411. this._isStencilOpDirty = true;
  7412. },
  7413. enumerable: true,
  7414. configurable: true
  7415. });
  7416. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7417. get: function () {
  7418. return this._stencilMask;
  7419. },
  7420. set: function (value) {
  7421. if (this._stencilMask === value) {
  7422. return;
  7423. }
  7424. this._stencilMask = value;
  7425. this._isStencilMaskDirty = true;
  7426. },
  7427. enumerable: true,
  7428. configurable: true
  7429. });
  7430. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7431. get: function () {
  7432. return this._stencilTest;
  7433. },
  7434. set: function (value) {
  7435. if (this._stencilTest === value) {
  7436. return;
  7437. }
  7438. this._stencilTest = value;
  7439. this._isStencilTestDirty = true;
  7440. },
  7441. enumerable: true,
  7442. configurable: true
  7443. });
  7444. _StencilState.prototype.reset = function () {
  7445. this._stencilTest = false;
  7446. this._stencilMask = 0xFF;
  7447. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7448. this._stencilFuncRef = 1;
  7449. this._stencilFuncMask = 0xFF;
  7450. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7451. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7452. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7453. this._isStencilTestDirty = true;
  7454. this._isStencilMaskDirty = true;
  7455. this._isStencilFuncDirty = true;
  7456. this._isStencilOpDirty = true;
  7457. };
  7458. _StencilState.prototype.apply = function (gl) {
  7459. if (!this.isDirty) {
  7460. return;
  7461. }
  7462. // Stencil test
  7463. if (this._isStencilTestDirty) {
  7464. if (this.stencilTest) {
  7465. gl.enable(gl.STENCIL_TEST);
  7466. }
  7467. else {
  7468. gl.disable(gl.STENCIL_TEST);
  7469. }
  7470. this._isStencilTestDirty = false;
  7471. }
  7472. // Stencil mask
  7473. if (this._isStencilMaskDirty) {
  7474. gl.stencilMask(this.stencilMask);
  7475. this._isStencilMaskDirty = false;
  7476. }
  7477. // Stencil func
  7478. if (this._isStencilFuncDirty) {
  7479. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7480. this._isStencilFuncDirty = false;
  7481. }
  7482. // Stencil op
  7483. if (this._isStencilOpDirty) {
  7484. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7485. this._isStencilOpDirty = false;
  7486. }
  7487. };
  7488. return _StencilState;
  7489. }());
  7490. Internals._StencilState = _StencilState;
  7491. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7492. })(BABYLON || (BABYLON = {}));
  7493. //# sourceMappingURL=babylon.stencilState.js.map
  7494. var BABYLON;
  7495. (function (BABYLON) {
  7496. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7497. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7498. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7499. gl.compileShader(shader);
  7500. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7501. throw new Error(gl.getShaderInfoLog(shader));
  7502. }
  7503. return shader;
  7504. };
  7505. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7506. var magFilter = gl.NEAREST;
  7507. var minFilter = gl.NEAREST;
  7508. switch (samplingMode) {
  7509. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7510. magFilter = gl.LINEAR;
  7511. if (generateMipMaps) {
  7512. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7513. }
  7514. else {
  7515. minFilter = gl.LINEAR;
  7516. }
  7517. break;
  7518. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7519. magFilter = gl.LINEAR;
  7520. if (generateMipMaps) {
  7521. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7522. }
  7523. else {
  7524. minFilter = gl.LINEAR;
  7525. }
  7526. break;
  7527. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7528. magFilter = gl.NEAREST;
  7529. if (generateMipMaps) {
  7530. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7531. }
  7532. else {
  7533. minFilter = gl.NEAREST;
  7534. }
  7535. break;
  7536. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7537. magFilter = gl.NEAREST;
  7538. if (generateMipMaps) {
  7539. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7540. }
  7541. else {
  7542. minFilter = gl.NEAREST;
  7543. }
  7544. break;
  7545. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7546. magFilter = gl.NEAREST;
  7547. if (generateMipMaps) {
  7548. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7549. }
  7550. else {
  7551. minFilter = gl.LINEAR;
  7552. }
  7553. break;
  7554. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7555. magFilter = gl.NEAREST;
  7556. if (generateMipMaps) {
  7557. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7558. }
  7559. else {
  7560. minFilter = gl.LINEAR;
  7561. }
  7562. break;
  7563. case BABYLON.Texture.NEAREST_LINEAR:
  7564. magFilter = gl.NEAREST;
  7565. minFilter = gl.LINEAR;
  7566. break;
  7567. case BABYLON.Texture.NEAREST_NEAREST:
  7568. magFilter = gl.NEAREST;
  7569. minFilter = gl.NEAREST;
  7570. break;
  7571. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7572. magFilter = gl.LINEAR;
  7573. if (generateMipMaps) {
  7574. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7575. }
  7576. else {
  7577. minFilter = gl.NEAREST;
  7578. }
  7579. break;
  7580. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7581. magFilter = gl.LINEAR;
  7582. if (generateMipMaps) {
  7583. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7584. }
  7585. else {
  7586. minFilter = gl.NEAREST;
  7587. }
  7588. break;
  7589. case BABYLON.Texture.LINEAR_LINEAR:
  7590. magFilter = gl.LINEAR;
  7591. minFilter = gl.LINEAR;
  7592. break;
  7593. case BABYLON.Texture.LINEAR_NEAREST:
  7594. magFilter = gl.LINEAR;
  7595. minFilter = gl.NEAREST;
  7596. break;
  7597. }
  7598. return {
  7599. min: minFilter,
  7600. mag: magFilter
  7601. };
  7602. };
  7603. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7604. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7605. var img;
  7606. var onload = function () {
  7607. loadedImages[index] = img;
  7608. loadedImages._internalCount++;
  7609. if (scene) {
  7610. scene._removePendingData(img);
  7611. }
  7612. if (loadedImages._internalCount === 6) {
  7613. onfinish(loadedImages);
  7614. }
  7615. };
  7616. var onerror = function (message, exception) {
  7617. if (scene) {
  7618. scene._removePendingData(img);
  7619. }
  7620. if (onErrorCallBack) {
  7621. onErrorCallBack(message, exception);
  7622. }
  7623. };
  7624. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7625. if (scene) {
  7626. scene._addPendingData(img);
  7627. }
  7628. };
  7629. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7630. if (onError === void 0) { onError = null; }
  7631. var loadedImages = [];
  7632. loadedImages._internalCount = 0;
  7633. for (var index = 0; index < 6; index++) {
  7634. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7635. }
  7636. };
  7637. var BufferPointer = (function () {
  7638. function BufferPointer() {
  7639. }
  7640. return BufferPointer;
  7641. }());
  7642. var InstancingAttributeInfo = (function () {
  7643. function InstancingAttributeInfo() {
  7644. }
  7645. return InstancingAttributeInfo;
  7646. }());
  7647. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7648. /**
  7649. * Define options used to create a render target texture
  7650. */
  7651. var RenderTargetCreationOptions = (function () {
  7652. function RenderTargetCreationOptions() {
  7653. }
  7654. return RenderTargetCreationOptions;
  7655. }());
  7656. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7657. /**
  7658. * Regroup several parameters relative to the browser in use
  7659. */
  7660. var EngineCapabilities = (function () {
  7661. function EngineCapabilities() {
  7662. }
  7663. return EngineCapabilities;
  7664. }());
  7665. BABYLON.EngineCapabilities = EngineCapabilities;
  7666. /**
  7667. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7668. */
  7669. var Engine = (function () {
  7670. /**
  7671. * @constructor
  7672. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7673. * @param {boolean} [antialias] - enable antialias
  7674. * @param options - further options to be sent to the getContext function
  7675. */
  7676. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7677. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7678. var _this = this;
  7679. // Public members
  7680. this.forcePOTTextures = false;
  7681. this.isFullscreen = false;
  7682. this.isPointerLock = false;
  7683. this.cullBackFaces = true;
  7684. this.renderEvenInBackground = true;
  7685. this.preventCacheWipeBetweenFrames = false;
  7686. // To enable/disable IDB support and avoid XHR on .manifest
  7687. this.enableOfflineSupport = false;
  7688. this.scenes = new Array();
  7689. this.postProcesses = new Array();
  7690. // Observables
  7691. /**
  7692. * Observable event triggered each time the rendering canvas is resized
  7693. */
  7694. this.onResizeObservable = new BABYLON.Observable();
  7695. /**
  7696. * Observable event triggered each time the canvas loses focus
  7697. */
  7698. this.onCanvasBlurObservable = new BABYLON.Observable();
  7699. /**
  7700. * Observable event triggered each time the canvas gains focus
  7701. */
  7702. this.onCanvasFocusObservable = new BABYLON.Observable();
  7703. /**
  7704. * Observable event triggered each time the canvas receives pointerout event
  7705. */
  7706. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7707. /**
  7708. * Observable event triggered before each texture is initialized
  7709. */
  7710. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  7711. //WebVR
  7712. this._vrDisplay = undefined;
  7713. this._vrSupported = false;
  7714. this._vrExclusivePointerMode = false;
  7715. // Uniform buffers list
  7716. this.disableUniformBuffers = false;
  7717. this._uniformBuffers = new Array();
  7718. this._windowIsBackground = false;
  7719. this._webGLVersion = 1.0;
  7720. this._badOS = false;
  7721. this._badDesktopOS = false;
  7722. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  7723. this.onVRRequestPresentComplete = new BABYLON.Observable();
  7724. this.onVRRequestPresentStart = new BABYLON.Observable();
  7725. this._colorWrite = true;
  7726. this._drawCalls = new BABYLON.PerfCounter();
  7727. this._renderingQueueLaunched = false;
  7728. this._activeRenderLoops = new Array();
  7729. // Deterministic lockstepMaxSteps
  7730. this._deterministicLockstep = false;
  7731. this._lockstepMaxSteps = 4;
  7732. // Lost context
  7733. this.onContextLostObservable = new BABYLON.Observable();
  7734. this.onContextRestoredObservable = new BABYLON.Observable();
  7735. this._contextWasLost = false;
  7736. this._doNotHandleContextLost = false;
  7737. // FPS
  7738. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7739. this._fps = 60;
  7740. this._deltaTime = 0;
  7741. /**
  7742. * Turn this value on if you want to pause FPS computation when in background
  7743. */
  7744. this.disablePerformanceMonitorInBackground = false;
  7745. // States
  7746. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7747. this._stencilState = new BABYLON.Internals._StencilState();
  7748. this._alphaState = new BABYLON.Internals._AlphaState();
  7749. this._alphaMode = Engine.ALPHA_DISABLE;
  7750. // Cache
  7751. this._internalTexturesCache = new Array();
  7752. this._maxTextureChannels = 16;
  7753. this._activeTexturesCache = {};
  7754. this._compiledEffects = {};
  7755. this._vertexAttribArraysEnabled = [];
  7756. this._uintIndicesCurrentlySet = false;
  7757. this._currentBoundBuffer = new Array();
  7758. this._currentBufferPointers = new Array();
  7759. this._currentInstanceLocations = new Array();
  7760. this._currentInstanceBuffers = new Array();
  7761. this._vaoRecordInProgress = false;
  7762. this._mustWipeVertexAttributes = false;
  7763. // Hardware supported Compressed Textures
  7764. this._texturesSupported = new Array();
  7765. this._onVRFullScreenTriggered = function () {
  7766. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  7767. //get the old size before we change
  7768. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7769. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7770. //get the width and height, change the render size
  7771. var leftEye = _this._vrDisplay.getEyeParameters('left');
  7772. var width, height;
  7773. _this.setHardwareScalingLevel(1);
  7774. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7775. }
  7776. else {
  7777. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7778. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7779. }
  7780. };
  7781. var canvas;
  7782. Engine.Instances.push(this);
  7783. if (!canvasOrContext) {
  7784. return;
  7785. }
  7786. options = options || {};
  7787. if (canvasOrContext.getContext) {
  7788. canvas = canvasOrContext;
  7789. this._renderingCanvas = canvas;
  7790. if (antialias != null) {
  7791. options.antialias = antialias;
  7792. }
  7793. if (options.deterministicLockstep === undefined) {
  7794. options.deterministicLockstep = false;
  7795. }
  7796. if (options.lockstepMaxSteps === undefined) {
  7797. options.lockstepMaxSteps = 4;
  7798. }
  7799. if (options.preserveDrawingBuffer === undefined) {
  7800. options.preserveDrawingBuffer = false;
  7801. }
  7802. if (options.audioEngine === undefined) {
  7803. options.audioEngine = true;
  7804. }
  7805. if (options.stencil === undefined) {
  7806. options.stencil = true;
  7807. }
  7808. this._deterministicLockstep = options.deterministicLockstep;
  7809. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7810. this._doNotHandleContextLost = options.doNotHandleContextLost;
  7811. // GL
  7812. if (!options.disableWebGL2Support) {
  7813. try {
  7814. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7815. if (this._gl) {
  7816. this._webGLVersion = 2.0;
  7817. }
  7818. }
  7819. catch (e) {
  7820. // Do nothing
  7821. }
  7822. }
  7823. if (!this._gl) {
  7824. if (!canvas) {
  7825. throw new Error("The provided canvas is null or undefined.");
  7826. }
  7827. try {
  7828. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7829. }
  7830. catch (e) {
  7831. throw new Error("WebGL not supported");
  7832. }
  7833. }
  7834. if (!this._gl) {
  7835. throw new Error("WebGL not supported");
  7836. }
  7837. this._onCanvasFocus = function () {
  7838. _this.onCanvasFocusObservable.notifyObservers(_this);
  7839. };
  7840. this._onCanvasBlur = function () {
  7841. _this.onCanvasBlurObservable.notifyObservers(_this);
  7842. };
  7843. canvas.addEventListener("focus", this._onCanvasFocus);
  7844. canvas.addEventListener("blur", this._onCanvasBlur);
  7845. this._onBlur = function () {
  7846. if (_this.disablePerformanceMonitorInBackground) {
  7847. _this._performanceMonitor.disable();
  7848. }
  7849. _this._windowIsBackground = true;
  7850. };
  7851. this._onFocus = function () {
  7852. if (_this.disablePerformanceMonitorInBackground) {
  7853. _this._performanceMonitor.enable();
  7854. }
  7855. _this._windowIsBackground = false;
  7856. };
  7857. this._onCanvasPointerOut = function () {
  7858. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  7859. };
  7860. window.addEventListener("blur", this._onBlur);
  7861. window.addEventListener("focus", this._onFocus);
  7862. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  7863. // Context lost
  7864. if (!this._doNotHandleContextLost) {
  7865. this._onContextLost = function (evt) {
  7866. evt.preventDefault();
  7867. _this._contextWasLost = true;
  7868. BABYLON.Tools.Warn("WebGL context lost.");
  7869. _this.onContextLostObservable.notifyObservers(_this);
  7870. };
  7871. this._onContextRestored = function (evt) {
  7872. // Adding a timeout to avoid race condition at browser level
  7873. setTimeout(function () {
  7874. // Rebuild gl context
  7875. _this._initGLContext();
  7876. // Rebuild effects
  7877. _this._rebuildEffects();
  7878. // Rebuild textures
  7879. _this._rebuildInternalTextures();
  7880. // Rebuild buffers
  7881. _this._rebuildBuffers();
  7882. // Cache
  7883. _this.wipeCaches(true);
  7884. BABYLON.Tools.Warn("WebGL context successfully restored.");
  7885. _this.onContextRestoredObservable.notifyObservers(_this);
  7886. _this._contextWasLost = false;
  7887. }, 0);
  7888. };
  7889. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  7890. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  7891. }
  7892. }
  7893. else {
  7894. this._gl = canvasOrContext;
  7895. this._renderingCanvas = this._gl.canvas;
  7896. if (this._gl.renderbufferStorageMultisample) {
  7897. this._webGLVersion = 2.0;
  7898. }
  7899. options.stencil = this._gl.getContextAttributes().stencil;
  7900. }
  7901. // Viewport
  7902. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7903. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7904. this.resize();
  7905. this._isStencilEnable = options.stencil;
  7906. this._initGLContext();
  7907. if (canvas) {
  7908. // Fullscreen
  7909. this._onFullscreenChange = function () {
  7910. if (document.fullscreen !== undefined) {
  7911. _this.isFullscreen = document.fullscreen;
  7912. }
  7913. else if (document.mozFullScreen !== undefined) {
  7914. _this.isFullscreen = document.mozFullScreen;
  7915. }
  7916. else if (document.webkitIsFullScreen !== undefined) {
  7917. _this.isFullscreen = document.webkitIsFullScreen;
  7918. }
  7919. else if (document.msIsFullScreen !== undefined) {
  7920. _this.isFullscreen = document.msIsFullScreen;
  7921. }
  7922. // Pointer lock
  7923. if (_this.isFullscreen && _this._pointerLockRequested) {
  7924. canvas.requestPointerLock = canvas.requestPointerLock ||
  7925. canvas.msRequestPointerLock ||
  7926. canvas.mozRequestPointerLock ||
  7927. canvas.webkitRequestPointerLock;
  7928. if (canvas.requestPointerLock) {
  7929. canvas.requestPointerLock();
  7930. }
  7931. }
  7932. };
  7933. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7934. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7935. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7936. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7937. // Pointer lock
  7938. this._onPointerLockChange = function () {
  7939. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7940. document.webkitPointerLockElement === canvas ||
  7941. document.msPointerLockElement === canvas ||
  7942. document.pointerLockElement === canvas);
  7943. };
  7944. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7945. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7946. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7947. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7948. this._onVRDisplayPointerRestricted = function () {
  7949. canvas.requestPointerLock();
  7950. };
  7951. this._onVRDisplayPointerUnrestricted = function () {
  7952. document.exitPointerLock();
  7953. };
  7954. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  7955. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  7956. }
  7957. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7958. Engine.audioEngine = new BABYLON.AudioEngine();
  7959. }
  7960. // Prepare buffer pointers
  7961. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  7962. this._currentBufferPointers[i] = new BufferPointer();
  7963. }
  7964. // Load WebVR Devices
  7965. if (options.autoEnableWebVR) {
  7966. this.initWebVR();
  7967. }
  7968. // Detect if we are running on a faulty buggy OS.
  7969. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  7970. // Detect if we are running on a faulty buggy desktop OS.
  7971. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  7972. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7973. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  7974. }
  7975. Object.defineProperty(Engine, "LastCreatedEngine", {
  7976. get: function () {
  7977. if (Engine.Instances.length === 0) {
  7978. return null;
  7979. }
  7980. return Engine.Instances[Engine.Instances.length - 1];
  7981. },
  7982. enumerable: true,
  7983. configurable: true
  7984. });
  7985. Object.defineProperty(Engine, "LastCreatedScene", {
  7986. get: function () {
  7987. var lastCreatedEngine = Engine.LastCreatedEngine;
  7988. if (!lastCreatedEngine) {
  7989. return null;
  7990. }
  7991. if (lastCreatedEngine.scenes.length === 0) {
  7992. return null;
  7993. }
  7994. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7995. },
  7996. enumerable: true,
  7997. configurable: true
  7998. });
  7999. /**
  8000. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8001. */
  8002. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8003. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8004. var engine = Engine.Instances[engineIndex];
  8005. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8006. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8007. }
  8008. }
  8009. };
  8010. Object.defineProperty(Engine, "NEVER", {
  8011. get: function () {
  8012. return Engine._NEVER;
  8013. },
  8014. enumerable: true,
  8015. configurable: true
  8016. });
  8017. Object.defineProperty(Engine, "ALWAYS", {
  8018. get: function () {
  8019. return Engine._ALWAYS;
  8020. },
  8021. enumerable: true,
  8022. configurable: true
  8023. });
  8024. Object.defineProperty(Engine, "LESS", {
  8025. get: function () {
  8026. return Engine._LESS;
  8027. },
  8028. enumerable: true,
  8029. configurable: true
  8030. });
  8031. Object.defineProperty(Engine, "EQUAL", {
  8032. get: function () {
  8033. return Engine._EQUAL;
  8034. },
  8035. enumerable: true,
  8036. configurable: true
  8037. });
  8038. Object.defineProperty(Engine, "LEQUAL", {
  8039. get: function () {
  8040. return Engine._LEQUAL;
  8041. },
  8042. enumerable: true,
  8043. configurable: true
  8044. });
  8045. Object.defineProperty(Engine, "GREATER", {
  8046. get: function () {
  8047. return Engine._GREATER;
  8048. },
  8049. enumerable: true,
  8050. configurable: true
  8051. });
  8052. Object.defineProperty(Engine, "GEQUAL", {
  8053. get: function () {
  8054. return Engine._GEQUAL;
  8055. },
  8056. enumerable: true,
  8057. configurable: true
  8058. });
  8059. Object.defineProperty(Engine, "NOTEQUAL", {
  8060. get: function () {
  8061. return Engine._NOTEQUAL;
  8062. },
  8063. enumerable: true,
  8064. configurable: true
  8065. });
  8066. Object.defineProperty(Engine, "KEEP", {
  8067. get: function () {
  8068. return Engine._KEEP;
  8069. },
  8070. enumerable: true,
  8071. configurable: true
  8072. });
  8073. Object.defineProperty(Engine, "REPLACE", {
  8074. get: function () {
  8075. return Engine._REPLACE;
  8076. },
  8077. enumerable: true,
  8078. configurable: true
  8079. });
  8080. Object.defineProperty(Engine, "INCR", {
  8081. get: function () {
  8082. return Engine._INCR;
  8083. },
  8084. enumerable: true,
  8085. configurable: true
  8086. });
  8087. Object.defineProperty(Engine, "DECR", {
  8088. get: function () {
  8089. return Engine._DECR;
  8090. },
  8091. enumerable: true,
  8092. configurable: true
  8093. });
  8094. Object.defineProperty(Engine, "INVERT", {
  8095. get: function () {
  8096. return Engine._INVERT;
  8097. },
  8098. enumerable: true,
  8099. configurable: true
  8100. });
  8101. Object.defineProperty(Engine, "INCR_WRAP", {
  8102. get: function () {
  8103. return Engine._INCR_WRAP;
  8104. },
  8105. enumerable: true,
  8106. configurable: true
  8107. });
  8108. Object.defineProperty(Engine, "DECR_WRAP", {
  8109. get: function () {
  8110. return Engine._DECR_WRAP;
  8111. },
  8112. enumerable: true,
  8113. configurable: true
  8114. });
  8115. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8116. get: function () {
  8117. return Engine._ALPHA_DISABLE;
  8118. },
  8119. enumerable: true,
  8120. configurable: true
  8121. });
  8122. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8123. get: function () {
  8124. return Engine._ALPHA_ONEONE;
  8125. },
  8126. enumerable: true,
  8127. configurable: true
  8128. });
  8129. Object.defineProperty(Engine, "ALPHA_ADD", {
  8130. get: function () {
  8131. return Engine._ALPHA_ADD;
  8132. },
  8133. enumerable: true,
  8134. configurable: true
  8135. });
  8136. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8137. get: function () {
  8138. return Engine._ALPHA_COMBINE;
  8139. },
  8140. enumerable: true,
  8141. configurable: true
  8142. });
  8143. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8144. get: function () {
  8145. return Engine._ALPHA_SUBTRACT;
  8146. },
  8147. enumerable: true,
  8148. configurable: true
  8149. });
  8150. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8151. get: function () {
  8152. return Engine._ALPHA_MULTIPLY;
  8153. },
  8154. enumerable: true,
  8155. configurable: true
  8156. });
  8157. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8158. get: function () {
  8159. return Engine._ALPHA_MAXIMIZED;
  8160. },
  8161. enumerable: true,
  8162. configurable: true
  8163. });
  8164. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8165. get: function () {
  8166. return Engine._ALPHA_PREMULTIPLIED;
  8167. },
  8168. enumerable: true,
  8169. configurable: true
  8170. });
  8171. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8172. get: function () {
  8173. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8174. },
  8175. enumerable: true,
  8176. configurable: true
  8177. });
  8178. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8179. get: function () {
  8180. return Engine._ALPHA_INTERPOLATE;
  8181. },
  8182. enumerable: true,
  8183. configurable: true
  8184. });
  8185. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8186. get: function () {
  8187. return Engine._ALPHA_SCREENMODE;
  8188. },
  8189. enumerable: true,
  8190. configurable: true
  8191. });
  8192. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8193. get: function () {
  8194. return Engine._DELAYLOADSTATE_NONE;
  8195. },
  8196. enumerable: true,
  8197. configurable: true
  8198. });
  8199. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8200. get: function () {
  8201. return Engine._DELAYLOADSTATE_LOADED;
  8202. },
  8203. enumerable: true,
  8204. configurable: true
  8205. });
  8206. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8207. get: function () {
  8208. return Engine._DELAYLOADSTATE_LOADING;
  8209. },
  8210. enumerable: true,
  8211. configurable: true
  8212. });
  8213. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8214. get: function () {
  8215. return Engine._DELAYLOADSTATE_NOTLOADED;
  8216. },
  8217. enumerable: true,
  8218. configurable: true
  8219. });
  8220. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8221. get: function () {
  8222. return Engine._TEXTUREFORMAT_ALPHA;
  8223. },
  8224. enumerable: true,
  8225. configurable: true
  8226. });
  8227. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8228. get: function () {
  8229. return Engine._TEXTUREFORMAT_LUMINANCE;
  8230. },
  8231. enumerable: true,
  8232. configurable: true
  8233. });
  8234. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8235. get: function () {
  8236. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8237. },
  8238. enumerable: true,
  8239. configurable: true
  8240. });
  8241. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8242. get: function () {
  8243. return Engine._TEXTUREFORMAT_RGB;
  8244. },
  8245. enumerable: true,
  8246. configurable: true
  8247. });
  8248. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8249. get: function () {
  8250. return Engine._TEXTUREFORMAT_RGBA;
  8251. },
  8252. enumerable: true,
  8253. configurable: true
  8254. });
  8255. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8256. get: function () {
  8257. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8258. },
  8259. enumerable: true,
  8260. configurable: true
  8261. });
  8262. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8263. get: function () {
  8264. return Engine._TEXTURETYPE_FLOAT;
  8265. },
  8266. enumerable: true,
  8267. configurable: true
  8268. });
  8269. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8270. get: function () {
  8271. return Engine._TEXTURETYPE_HALF_FLOAT;
  8272. },
  8273. enumerable: true,
  8274. configurable: true
  8275. });
  8276. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8277. get: function () {
  8278. return Engine._SCALEMODE_FLOOR;
  8279. },
  8280. enumerable: true,
  8281. configurable: true
  8282. });
  8283. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8284. get: function () {
  8285. return Engine._SCALEMODE_NEAREST;
  8286. },
  8287. enumerable: true,
  8288. configurable: true
  8289. });
  8290. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8291. get: function () {
  8292. return Engine._SCALEMODE_CEILING;
  8293. },
  8294. enumerable: true,
  8295. configurable: true
  8296. });
  8297. Object.defineProperty(Engine, "Version", {
  8298. get: function () {
  8299. return "3.1-alpha";
  8300. },
  8301. enumerable: true,
  8302. configurable: true
  8303. });
  8304. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8305. get: function () {
  8306. return this._vrExclusivePointerMode;
  8307. },
  8308. enumerable: true,
  8309. configurable: true
  8310. });
  8311. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8312. get: function () {
  8313. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8314. },
  8315. enumerable: true,
  8316. configurable: true
  8317. });
  8318. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8319. get: function () {
  8320. return this._webGLVersion < 2 || this.forcePOTTextures;
  8321. },
  8322. enumerable: true,
  8323. configurable: true
  8324. });
  8325. Object.defineProperty(Engine.prototype, "badOS", {
  8326. get: function () {
  8327. return this._badOS;
  8328. },
  8329. enumerable: true,
  8330. configurable: true
  8331. });
  8332. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8333. get: function () {
  8334. return this._badDesktopOS;
  8335. },
  8336. enumerable: true,
  8337. configurable: true
  8338. });
  8339. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8340. get: function () {
  8341. return this._performanceMonitor;
  8342. },
  8343. enumerable: true,
  8344. configurable: true
  8345. });
  8346. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8347. get: function () {
  8348. return this._texturesSupported;
  8349. },
  8350. enumerable: true,
  8351. configurable: true
  8352. });
  8353. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8354. get: function () {
  8355. return this._textureFormatInUse;
  8356. },
  8357. enumerable: true,
  8358. configurable: true
  8359. });
  8360. Object.defineProperty(Engine.prototype, "currentViewport", {
  8361. get: function () {
  8362. return this._cachedViewport;
  8363. },
  8364. enumerable: true,
  8365. configurable: true
  8366. });
  8367. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8368. // Empty texture
  8369. get: function () {
  8370. if (!this._emptyTexture) {
  8371. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8372. }
  8373. return this._emptyTexture;
  8374. },
  8375. enumerable: true,
  8376. configurable: true
  8377. });
  8378. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8379. get: function () {
  8380. if (!this._emptyCubeTexture) {
  8381. var faceData = new Uint8Array(4);
  8382. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8383. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8384. }
  8385. return this._emptyCubeTexture;
  8386. },
  8387. enumerable: true,
  8388. configurable: true
  8389. });
  8390. Engine.prototype._rebuildInternalTextures = function () {
  8391. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8392. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8393. var internalTexture = currentState_1[_i];
  8394. internalTexture._rebuild();
  8395. }
  8396. };
  8397. Engine.prototype._rebuildEffects = function () {
  8398. for (var key in this._compiledEffects) {
  8399. var effect = this._compiledEffects[key];
  8400. effect._prepareEffect();
  8401. }
  8402. BABYLON.Effect.ResetCache();
  8403. };
  8404. Engine.prototype._rebuildBuffers = function () {
  8405. // Index / Vertex
  8406. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8407. var scene = _a[_i];
  8408. scene.resetCachedMaterial();
  8409. scene._rebuildGeometries();
  8410. scene._rebuildTextures();
  8411. }
  8412. // Uniforms
  8413. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8414. var uniformBuffer = _c[_b];
  8415. uniformBuffer._rebuild();
  8416. }
  8417. };
  8418. Engine.prototype._initGLContext = function () {
  8419. // Caps
  8420. this._caps = new EngineCapabilities();
  8421. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8422. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8423. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8424. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8425. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8426. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8427. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8428. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8429. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8430. // Infos
  8431. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8432. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8433. if (rendererInfo != null) {
  8434. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8435. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8436. }
  8437. if (!this._glVendor) {
  8438. this._glVendor = "Unknown vendor";
  8439. }
  8440. if (!this._glRenderer) {
  8441. this._glRenderer = "Unknown renderer";
  8442. }
  8443. // Constants
  8444. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8445. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8446. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8447. this._gl.DEPTH24_STENCIL8 = 35056;
  8448. // Extensions
  8449. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8450. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8451. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8452. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8453. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8454. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8455. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8456. 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');
  8457. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8458. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8459. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8460. this._caps.highPrecisionShaderSupported = true;
  8461. // Checks if some of the format renders first to allow the use of webgl inspector.
  8462. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8463. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8464. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8465. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8466. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8467. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8468. if (this._webGLVersion > 1) {
  8469. this._gl.HALF_FLOAT_OES = 0x140B;
  8470. }
  8471. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8472. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8473. // Draw buffers
  8474. if (this._webGLVersion > 1) {
  8475. this._caps.drawBuffersExtension = true;
  8476. }
  8477. else {
  8478. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8479. if (drawBuffersExtension !== null) {
  8480. this._caps.drawBuffersExtension = true;
  8481. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8482. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8483. for (var i = 0; i < 16; i++) {
  8484. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8485. }
  8486. }
  8487. else {
  8488. this._caps.drawBuffersExtension = false;
  8489. }
  8490. }
  8491. // Depth Texture
  8492. if (this._webGLVersion > 1) {
  8493. this._caps.depthTextureExtension = true;
  8494. }
  8495. else {
  8496. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8497. if (depthTextureExtension != null) {
  8498. this._caps.depthTextureExtension = true;
  8499. }
  8500. }
  8501. // Vertex array object
  8502. if (this._webGLVersion > 1) {
  8503. this._caps.vertexArrayObject = true;
  8504. }
  8505. else {
  8506. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8507. if (vertexArrayObjectExtension != null) {
  8508. this._caps.vertexArrayObject = true;
  8509. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8510. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8511. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8512. }
  8513. else {
  8514. this._caps.vertexArrayObject = false;
  8515. }
  8516. }
  8517. // Instances count
  8518. if (this._webGLVersion > 1) {
  8519. this._caps.instancedArrays = true;
  8520. }
  8521. else {
  8522. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8523. if (instanceExtension != null) {
  8524. this._caps.instancedArrays = true;
  8525. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8526. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8527. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8528. }
  8529. else {
  8530. this._caps.instancedArrays = false;
  8531. }
  8532. }
  8533. // Intelligently add supported compressed formats in order to check for.
  8534. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8535. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8536. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8537. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8538. if (this._caps.astc)
  8539. this.texturesSupported.push('-astc.ktx');
  8540. if (this._caps.s3tc)
  8541. this.texturesSupported.push('-dxt.ktx');
  8542. if (this._caps.pvrtc)
  8543. this.texturesSupported.push('-pvrtc.ktx');
  8544. if (this._caps.etc2)
  8545. this.texturesSupported.push('-etc2.ktx');
  8546. if (this._caps.etc1)
  8547. this.texturesSupported.push('-etc1.ktx');
  8548. if (this._gl.getShaderPrecisionFormat) {
  8549. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8550. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8551. }
  8552. // Depth buffer
  8553. this.setDepthBuffer(true);
  8554. this.setDepthFunctionToLessOrEqual();
  8555. this.setDepthWrite(true);
  8556. };
  8557. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8558. get: function () {
  8559. return this._webGLVersion;
  8560. },
  8561. enumerable: true,
  8562. configurable: true
  8563. });
  8564. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8565. /**
  8566. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8567. */
  8568. get: function () {
  8569. return this._isStencilEnable;
  8570. },
  8571. enumerable: true,
  8572. configurable: true
  8573. });
  8574. Engine.prototype._prepareWorkingCanvas = function () {
  8575. if (this._workingCanvas) {
  8576. return;
  8577. }
  8578. this._workingCanvas = document.createElement("canvas");
  8579. this._workingContext = this._workingCanvas.getContext("2d");
  8580. };
  8581. Engine.prototype.resetTextureCache = function () {
  8582. for (var key in this._activeTexturesCache) {
  8583. this._activeTexturesCache[key] = null;
  8584. }
  8585. };
  8586. Engine.prototype.isDeterministicLockStep = function () {
  8587. return this._deterministicLockstep;
  8588. };
  8589. Engine.prototype.getLockstepMaxSteps = function () {
  8590. return this._lockstepMaxSteps;
  8591. };
  8592. Engine.prototype.getGlInfo = function () {
  8593. return {
  8594. vendor: this._glVendor,
  8595. renderer: this._glRenderer,
  8596. version: this._glVersion
  8597. };
  8598. };
  8599. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8600. if (useScreen === void 0) { useScreen = false; }
  8601. var viewport = camera.viewport;
  8602. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8603. };
  8604. Engine.prototype.getRenderWidth = function (useScreen) {
  8605. if (useScreen === void 0) { useScreen = false; }
  8606. if (!useScreen && this._currentRenderTarget) {
  8607. return this._currentRenderTarget.width;
  8608. }
  8609. return this._gl.drawingBufferWidth;
  8610. };
  8611. Engine.prototype.getRenderHeight = function (useScreen) {
  8612. if (useScreen === void 0) { useScreen = false; }
  8613. if (!useScreen && this._currentRenderTarget) {
  8614. return this._currentRenderTarget.height;
  8615. }
  8616. return this._gl.drawingBufferHeight;
  8617. };
  8618. Engine.prototype.getRenderingCanvas = function () {
  8619. return this._renderingCanvas;
  8620. };
  8621. Engine.prototype.getRenderingCanvasClientRect = function () {
  8622. return this._renderingCanvas.getBoundingClientRect();
  8623. };
  8624. Engine.prototype.setHardwareScalingLevel = function (level) {
  8625. this._hardwareScalingLevel = level;
  8626. this.resize();
  8627. };
  8628. Engine.prototype.getHardwareScalingLevel = function () {
  8629. return this._hardwareScalingLevel;
  8630. };
  8631. Engine.prototype.getLoadedTexturesCache = function () {
  8632. return this._internalTexturesCache;
  8633. };
  8634. Engine.prototype.getCaps = function () {
  8635. return this._caps;
  8636. };
  8637. Object.defineProperty(Engine.prototype, "drawCalls", {
  8638. /** The number of draw calls submitted last frame */
  8639. get: function () {
  8640. return this._drawCalls.current;
  8641. },
  8642. enumerable: true,
  8643. configurable: true
  8644. });
  8645. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8646. get: function () {
  8647. return this._drawCalls;
  8648. },
  8649. enumerable: true,
  8650. configurable: true
  8651. });
  8652. Engine.prototype.getDepthFunction = function () {
  8653. return this._depthCullingState.depthFunc;
  8654. };
  8655. Engine.prototype.setDepthFunction = function (depthFunc) {
  8656. this._depthCullingState.depthFunc = depthFunc;
  8657. };
  8658. Engine.prototype.setDepthFunctionToGreater = function () {
  8659. this._depthCullingState.depthFunc = this._gl.GREATER;
  8660. };
  8661. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8662. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8663. };
  8664. Engine.prototype.setDepthFunctionToLess = function () {
  8665. this._depthCullingState.depthFunc = this._gl.LESS;
  8666. };
  8667. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8668. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8669. };
  8670. Engine.prototype.getStencilBuffer = function () {
  8671. return this._stencilState.stencilTest;
  8672. };
  8673. Engine.prototype.setStencilBuffer = function (enable) {
  8674. this._stencilState.stencilTest = enable;
  8675. };
  8676. Engine.prototype.getStencilMask = function () {
  8677. return this._stencilState.stencilMask;
  8678. };
  8679. Engine.prototype.setStencilMask = function (mask) {
  8680. this._stencilState.stencilMask = mask;
  8681. };
  8682. Engine.prototype.getStencilFunction = function () {
  8683. return this._stencilState.stencilFunc;
  8684. };
  8685. Engine.prototype.getStencilFunctionReference = function () {
  8686. return this._stencilState.stencilFuncRef;
  8687. };
  8688. Engine.prototype.getStencilFunctionMask = function () {
  8689. return this._stencilState.stencilFuncMask;
  8690. };
  8691. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8692. this._stencilState.stencilFunc = stencilFunc;
  8693. };
  8694. Engine.prototype.setStencilFunctionReference = function (reference) {
  8695. this._stencilState.stencilFuncRef = reference;
  8696. };
  8697. Engine.prototype.setStencilFunctionMask = function (mask) {
  8698. this._stencilState.stencilFuncMask = mask;
  8699. };
  8700. Engine.prototype.getStencilOperationFail = function () {
  8701. return this._stencilState.stencilOpStencilFail;
  8702. };
  8703. Engine.prototype.getStencilOperationDepthFail = function () {
  8704. return this._stencilState.stencilOpDepthFail;
  8705. };
  8706. Engine.prototype.getStencilOperationPass = function () {
  8707. return this._stencilState.stencilOpStencilDepthPass;
  8708. };
  8709. Engine.prototype.setStencilOperationFail = function (operation) {
  8710. this._stencilState.stencilOpStencilFail = operation;
  8711. };
  8712. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8713. this._stencilState.stencilOpDepthFail = operation;
  8714. };
  8715. Engine.prototype.setStencilOperationPass = function (operation) {
  8716. this._stencilState.stencilOpStencilDepthPass = operation;
  8717. };
  8718. Engine.prototype.setDitheringState = function (value) {
  8719. if (value) {
  8720. this._gl.enable(this._gl.DITHER);
  8721. }
  8722. else {
  8723. this._gl.disable(this._gl.DITHER);
  8724. }
  8725. };
  8726. /**
  8727. * stop executing a render loop function and remove it from the execution array
  8728. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8729. */
  8730. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8731. if (!renderFunction) {
  8732. this._activeRenderLoops = [];
  8733. return;
  8734. }
  8735. var index = this._activeRenderLoops.indexOf(renderFunction);
  8736. if (index >= 0) {
  8737. this._activeRenderLoops.splice(index, 1);
  8738. }
  8739. };
  8740. Engine.prototype._renderLoop = function () {
  8741. if (!this._contextWasLost) {
  8742. var shouldRender = true;
  8743. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8744. shouldRender = false;
  8745. }
  8746. if (shouldRender) {
  8747. // Start new frame
  8748. this.beginFrame();
  8749. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8750. var renderFunction = this._activeRenderLoops[index];
  8751. renderFunction();
  8752. }
  8753. // Present
  8754. this.endFrame();
  8755. }
  8756. }
  8757. if (this._activeRenderLoops.length > 0) {
  8758. // Register new frame
  8759. var requester = null;
  8760. if (this._vrDisplay && this._vrDisplay.isPresenting)
  8761. requester = this._vrDisplay;
  8762. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  8763. }
  8764. else {
  8765. this._renderingQueueLaunched = false;
  8766. }
  8767. };
  8768. /**
  8769. * Register and execute a render loop. The engine can have more than one render function.
  8770. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8771. * @example
  8772. * engine.runRenderLoop(function () {
  8773. * scene.render()
  8774. * })
  8775. */
  8776. Engine.prototype.runRenderLoop = function (renderFunction) {
  8777. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8778. return;
  8779. }
  8780. this._activeRenderLoops.push(renderFunction);
  8781. if (!this._renderingQueueLaunched) {
  8782. this._renderingQueueLaunched = true;
  8783. this._bindedRenderFunction = this._renderLoop.bind(this);
  8784. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8785. }
  8786. };
  8787. /**
  8788. * Toggle full screen mode.
  8789. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8790. * @param {any} options - an options object to be sent to the requestFullscreen function
  8791. */
  8792. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8793. if (this.isFullscreen) {
  8794. BABYLON.Tools.ExitFullscreen();
  8795. }
  8796. else {
  8797. this._pointerLockRequested = requestPointerLock;
  8798. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8799. }
  8800. };
  8801. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8802. if (stencil === void 0) { stencil = false; }
  8803. this.applyStates();
  8804. var mode = 0;
  8805. if (backBuffer && color) {
  8806. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8807. mode |= this._gl.COLOR_BUFFER_BIT;
  8808. }
  8809. if (depth) {
  8810. this._gl.clearDepth(1.0);
  8811. mode |= this._gl.DEPTH_BUFFER_BIT;
  8812. }
  8813. if (stencil) {
  8814. this._gl.clearStencil(0);
  8815. mode |= this._gl.STENCIL_BUFFER_BIT;
  8816. }
  8817. this._gl.clear(mode);
  8818. };
  8819. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8820. var gl = this._gl;
  8821. // Save state
  8822. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8823. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8824. // Change state
  8825. gl.enable(gl.SCISSOR_TEST);
  8826. gl.scissor(x, y, width, height);
  8827. // Clear
  8828. this.clear(clearColor, true, true, true);
  8829. // Restore state
  8830. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8831. if (curScissor === true) {
  8832. gl.enable(gl.SCISSOR_TEST);
  8833. }
  8834. else {
  8835. gl.disable(gl.SCISSOR_TEST);
  8836. }
  8837. };
  8838. /**
  8839. * Set the WebGL's viewport
  8840. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8841. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8842. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8843. */
  8844. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8845. var width = requiredWidth || this.getRenderWidth();
  8846. var height = requiredHeight || this.getRenderHeight();
  8847. var x = viewport.x || 0;
  8848. var y = viewport.y || 0;
  8849. this._cachedViewport = viewport;
  8850. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8851. };
  8852. /**
  8853. * Directly set the WebGL Viewport
  8854. * The x, y, width & height are directly passed to the WebGL call
  8855. * @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.
  8856. */
  8857. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8858. var currentViewport = this._cachedViewport;
  8859. this._cachedViewport = null;
  8860. this._gl.viewport(x, y, width, height);
  8861. return currentViewport;
  8862. };
  8863. Engine.prototype.beginFrame = function () {
  8864. this._measureFps();
  8865. };
  8866. Engine.prototype.endFrame = function () {
  8867. //force a flush in case we are using a bad OS.
  8868. if (this._badOS) {
  8869. this.flushFramebuffer();
  8870. }
  8871. //submit frame to the vr device, if enabled
  8872. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  8873. // TODO: We should only submit the frame if we read frameData successfully.
  8874. this._vrDisplay.submitFrame();
  8875. }
  8876. };
  8877. /**
  8878. * resize the view according to the canvas' size.
  8879. * @example
  8880. * window.addEventListener("resize", function () {
  8881. * engine.resize();
  8882. * });
  8883. */
  8884. Engine.prototype.resize = function () {
  8885. // We're not resizing the size of the canvas while in VR mode & presenting
  8886. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  8887. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8888. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8889. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8890. }
  8891. };
  8892. /**
  8893. * force a specific size of the canvas
  8894. * @param {number} width - the new canvas' width
  8895. * @param {number} height - the new canvas' height
  8896. */
  8897. Engine.prototype.setSize = function (width, height) {
  8898. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8899. return;
  8900. }
  8901. this._renderingCanvas.width = width;
  8902. this._renderingCanvas.height = height;
  8903. for (var index = 0; index < this.scenes.length; index++) {
  8904. var scene = this.scenes[index];
  8905. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8906. var cam = scene.cameras[camIndex];
  8907. cam._currentRenderId = 0;
  8908. }
  8909. }
  8910. if (this.onResizeObservable.hasObservers) {
  8911. this.onResizeObservable.notifyObservers(this);
  8912. }
  8913. };
  8914. // WebVR functions
  8915. Engine.prototype.isVRDevicePresent = function () {
  8916. return !!this._vrDisplay;
  8917. };
  8918. Engine.prototype.getVRDevice = function () {
  8919. return this._vrDisplay;
  8920. };
  8921. Engine.prototype.initWebVR = function () {
  8922. var _this = this;
  8923. var notifyObservers = function () {
  8924. var eventArgs = {
  8925. vrDisplay: _this._vrDisplay,
  8926. vrSupported: _this._vrSupported
  8927. };
  8928. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  8929. };
  8930. if (!this._onVrDisplayConnect) {
  8931. this._onVrDisplayConnect = function (event) {
  8932. _this._vrDisplay = event.display;
  8933. notifyObservers();
  8934. };
  8935. this._onVrDisplayDisconnect = function () {
  8936. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  8937. _this._vrDisplay = undefined;
  8938. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  8939. notifyObservers();
  8940. };
  8941. this._onVrDisplayPresentChange = function () {
  8942. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  8943. };
  8944. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  8945. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  8946. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  8947. }
  8948. this._getVRDisplays(notifyObservers);
  8949. return this.onVRDisplayChangedObservable;
  8950. };
  8951. Engine.prototype.enableVR = function () {
  8952. var _this = this;
  8953. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  8954. var onResolved = function () {
  8955. _this.onVRRequestPresentComplete.notifyObservers(true);
  8956. _this._onVRFullScreenTriggered();
  8957. };
  8958. var onRejected = function () {
  8959. _this.onVRRequestPresentComplete.notifyObservers(false);
  8960. };
  8961. this.onVRRequestPresentStart.notifyObservers(this);
  8962. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  8963. }
  8964. };
  8965. Engine.prototype.disableVR = function () {
  8966. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  8967. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  8968. }
  8969. };
  8970. Engine.prototype._getVRDisplays = function (callback) {
  8971. var _this = this;
  8972. var getWebVRDevices = function (devices) {
  8973. _this._vrSupported = true;
  8974. // note that devices may actually be an empty array. This is fine;
  8975. // we expect this._vrDisplay to be undefined in this case.
  8976. return _this._vrDisplay = devices[0];
  8977. };
  8978. if (navigator.getVRDisplays) {
  8979. // TODO: Backwards compatible for 1.0?
  8980. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  8981. // TODO: System CANNOT support WebVR, despite API presence.
  8982. _this._vrSupported = false;
  8983. callback();
  8984. });
  8985. }
  8986. else {
  8987. // TODO: Browser does not support WebVR
  8988. this._vrDisplay = undefined;
  8989. this._vrSupported = false;
  8990. callback();
  8991. }
  8992. };
  8993. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  8994. if (this._currentRenderTarget) {
  8995. this.unBindFramebuffer(this._currentRenderTarget);
  8996. }
  8997. this._currentRenderTarget = texture;
  8998. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8999. var gl = this._gl;
  9000. if (texture.isCube) {
  9001. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9002. }
  9003. if (this._cachedViewport && !forceFullscreenViewport) {
  9004. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9005. }
  9006. else {
  9007. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9008. }
  9009. this.wipeCaches();
  9010. };
  9011. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9012. if (this._currentFramebuffer !== framebuffer) {
  9013. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9014. this._currentFramebuffer = framebuffer;
  9015. }
  9016. };
  9017. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9018. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9019. this._currentRenderTarget = null;
  9020. // If MSAA, we need to bitblt back to main texture
  9021. var gl = this._gl;
  9022. if (texture._MSAAFramebuffer) {
  9023. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9024. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9025. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9026. }
  9027. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9028. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9029. gl.generateMipmap(gl.TEXTURE_2D);
  9030. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9031. }
  9032. if (onBeforeUnbind) {
  9033. if (texture._MSAAFramebuffer) {
  9034. // Bind the correct framebuffer
  9035. this.bindUnboundFramebuffer(texture._framebuffer);
  9036. }
  9037. onBeforeUnbind();
  9038. }
  9039. this.bindUnboundFramebuffer(null);
  9040. };
  9041. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9042. if (texture.generateMipMaps) {
  9043. var gl = this._gl;
  9044. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9045. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9046. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9047. }
  9048. };
  9049. Engine.prototype.flushFramebuffer = function () {
  9050. this._gl.flush();
  9051. };
  9052. Engine.prototype.restoreDefaultFramebuffer = function () {
  9053. if (this._currentRenderTarget) {
  9054. this.unBindFramebuffer(this._currentRenderTarget);
  9055. }
  9056. else {
  9057. this.bindUnboundFramebuffer(null);
  9058. }
  9059. if (this._cachedViewport) {
  9060. this.setViewport(this._cachedViewport);
  9061. }
  9062. this.wipeCaches();
  9063. };
  9064. // UBOs
  9065. Engine.prototype.createUniformBuffer = function (elements) {
  9066. var ubo = this._gl.createBuffer();
  9067. this.bindUniformBuffer(ubo);
  9068. if (elements instanceof Float32Array) {
  9069. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9070. }
  9071. else {
  9072. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9073. }
  9074. this.bindUniformBuffer(null);
  9075. ubo.references = 1;
  9076. return ubo;
  9077. };
  9078. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9079. var ubo = this._gl.createBuffer();
  9080. this.bindUniformBuffer(ubo);
  9081. if (elements instanceof Float32Array) {
  9082. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9083. }
  9084. else {
  9085. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9086. }
  9087. this.bindUniformBuffer(null);
  9088. ubo.references = 1;
  9089. return ubo;
  9090. };
  9091. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9092. this.bindUniformBuffer(uniformBuffer);
  9093. if (offset === undefined) {
  9094. offset = 0;
  9095. }
  9096. if (count === undefined) {
  9097. if (elements instanceof Float32Array) {
  9098. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9099. }
  9100. else {
  9101. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9102. }
  9103. }
  9104. else {
  9105. if (elements instanceof Float32Array) {
  9106. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9107. }
  9108. else {
  9109. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9110. }
  9111. }
  9112. this.bindUniformBuffer(null);
  9113. };
  9114. // VBOs
  9115. Engine.prototype._resetVertexBufferBinding = function () {
  9116. this.bindArrayBuffer(null);
  9117. this._cachedVertexBuffers = null;
  9118. };
  9119. Engine.prototype.createVertexBuffer = function (vertices) {
  9120. var vbo = this._gl.createBuffer();
  9121. this.bindArrayBuffer(vbo);
  9122. if (vertices instanceof Float32Array) {
  9123. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9124. }
  9125. else {
  9126. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9127. }
  9128. this._resetVertexBufferBinding();
  9129. vbo.references = 1;
  9130. return vbo;
  9131. };
  9132. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9133. var vbo = this._gl.createBuffer();
  9134. this.bindArrayBuffer(vbo);
  9135. if (vertices instanceof Float32Array) {
  9136. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9137. }
  9138. else {
  9139. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9140. }
  9141. this._resetVertexBufferBinding();
  9142. vbo.references = 1;
  9143. return vbo;
  9144. };
  9145. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9146. this.bindArrayBuffer(vertexBuffer);
  9147. if (offset === undefined) {
  9148. offset = 0;
  9149. }
  9150. if (count === undefined) {
  9151. if (vertices instanceof Float32Array) {
  9152. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9153. }
  9154. else {
  9155. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9156. }
  9157. }
  9158. else {
  9159. if (vertices instanceof Float32Array) {
  9160. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9161. }
  9162. else {
  9163. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9164. }
  9165. }
  9166. this._resetVertexBufferBinding();
  9167. };
  9168. Engine.prototype._resetIndexBufferBinding = function () {
  9169. this.bindIndexBuffer(null);
  9170. this._cachedIndexBuffer = null;
  9171. };
  9172. Engine.prototype.createIndexBuffer = function (indices) {
  9173. var vbo = this._gl.createBuffer();
  9174. this.bindIndexBuffer(vbo);
  9175. // Check for 32 bits indices
  9176. var arrayBuffer;
  9177. var need32Bits = false;
  9178. if (indices instanceof Uint16Array) {
  9179. arrayBuffer = indices;
  9180. }
  9181. else {
  9182. //check 32 bit support
  9183. if (this._caps.uintIndices) {
  9184. if (indices instanceof Uint32Array) {
  9185. arrayBuffer = indices;
  9186. need32Bits = true;
  9187. }
  9188. else {
  9189. //number[] or Int32Array, check if 32 bit is necessary
  9190. for (var index = 0; index < indices.length; index++) {
  9191. if (indices[index] > 65535) {
  9192. need32Bits = true;
  9193. break;
  9194. }
  9195. }
  9196. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9197. }
  9198. }
  9199. else {
  9200. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9201. arrayBuffer = new Uint16Array(indices);
  9202. }
  9203. }
  9204. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  9205. this._resetIndexBufferBinding();
  9206. vbo.references = 1;
  9207. vbo.is32Bits = need32Bits;
  9208. return vbo;
  9209. };
  9210. Engine.prototype.bindArrayBuffer = function (buffer) {
  9211. if (!this._vaoRecordInProgress) {
  9212. this._unbindVertexArrayObject();
  9213. }
  9214. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9215. };
  9216. Engine.prototype.bindUniformBuffer = function (buffer) {
  9217. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9218. };
  9219. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9220. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9221. };
  9222. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9223. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9224. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9225. };
  9226. ;
  9227. Engine.prototype.bindIndexBuffer = function (buffer) {
  9228. if (!this._vaoRecordInProgress) {
  9229. this._unbindVertexArrayObject();
  9230. }
  9231. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9232. };
  9233. Engine.prototype.bindBuffer = function (buffer, target) {
  9234. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9235. this._gl.bindBuffer(target, buffer);
  9236. this._currentBoundBuffer[target] = buffer;
  9237. }
  9238. };
  9239. Engine.prototype.updateArrayBuffer = function (data) {
  9240. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9241. };
  9242. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9243. var pointer = this._currentBufferPointers[indx];
  9244. var changed = false;
  9245. if (!pointer.active) {
  9246. changed = true;
  9247. pointer.active = true;
  9248. pointer.index = indx;
  9249. pointer.size = size;
  9250. pointer.type = type;
  9251. pointer.normalized = normalized;
  9252. pointer.stride = stride;
  9253. pointer.offset = offset;
  9254. pointer.buffer = buffer;
  9255. }
  9256. else {
  9257. if (pointer.buffer !== buffer) {
  9258. pointer.buffer = buffer;
  9259. changed = true;
  9260. }
  9261. if (pointer.size !== size) {
  9262. pointer.size = size;
  9263. changed = true;
  9264. }
  9265. if (pointer.type !== type) {
  9266. pointer.type = type;
  9267. changed = true;
  9268. }
  9269. if (pointer.normalized !== normalized) {
  9270. pointer.normalized = normalized;
  9271. changed = true;
  9272. }
  9273. if (pointer.stride !== stride) {
  9274. pointer.stride = stride;
  9275. changed = true;
  9276. }
  9277. if (pointer.offset !== offset) {
  9278. pointer.offset = offset;
  9279. changed = true;
  9280. }
  9281. }
  9282. if (changed || this._vaoRecordInProgress) {
  9283. this.bindArrayBuffer(buffer);
  9284. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9285. }
  9286. };
  9287. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9288. if (indexBuffer == null) {
  9289. return;
  9290. }
  9291. if (this._cachedIndexBuffer !== indexBuffer) {
  9292. this._cachedIndexBuffer = indexBuffer;
  9293. this.bindIndexBuffer(indexBuffer);
  9294. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9295. }
  9296. };
  9297. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9298. var attributes = effect.getAttributesNames();
  9299. if (!this._vaoRecordInProgress) {
  9300. this._unbindVertexArrayObject();
  9301. }
  9302. this.unbindAllAttributes();
  9303. for (var index = 0; index < attributes.length; index++) {
  9304. var order = effect.getAttributeLocation(index);
  9305. if (order >= 0) {
  9306. var vertexBuffer = vertexBuffers[attributes[index]];
  9307. if (!vertexBuffer) {
  9308. continue;
  9309. }
  9310. this._gl.enableVertexAttribArray(order);
  9311. if (!this._vaoRecordInProgress) {
  9312. this._vertexAttribArraysEnabled[order] = true;
  9313. }
  9314. var buffer = vertexBuffer.getBuffer();
  9315. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9316. if (vertexBuffer.getIsInstanced()) {
  9317. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9318. if (!this._vaoRecordInProgress) {
  9319. this._currentInstanceLocations.push(order);
  9320. this._currentInstanceBuffers.push(buffer);
  9321. }
  9322. }
  9323. }
  9324. }
  9325. };
  9326. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9327. var vao = this._gl.createVertexArray();
  9328. this._vaoRecordInProgress = true;
  9329. this._gl.bindVertexArray(vao);
  9330. this._mustWipeVertexAttributes = true;
  9331. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9332. this.bindIndexBuffer(indexBuffer);
  9333. this._vaoRecordInProgress = false;
  9334. this._gl.bindVertexArray(null);
  9335. return vao;
  9336. };
  9337. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9338. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9339. this._cachedVertexArrayObject = vertexArrayObject;
  9340. this._gl.bindVertexArray(vertexArrayObject);
  9341. this._cachedVertexBuffers = null;
  9342. this._cachedIndexBuffer = null;
  9343. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9344. this._mustWipeVertexAttributes = true;
  9345. }
  9346. };
  9347. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9348. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9349. this._cachedVertexBuffers = vertexBuffer;
  9350. this._cachedEffectForVertexBuffers = effect;
  9351. var attributesCount = effect.getAttributesCount();
  9352. this._unbindVertexArrayObject();
  9353. this.unbindAllAttributes();
  9354. var offset = 0;
  9355. for (var index = 0; index < attributesCount; index++) {
  9356. if (index < vertexDeclaration.length) {
  9357. var order = effect.getAttributeLocation(index);
  9358. if (order >= 0) {
  9359. this._gl.enableVertexAttribArray(order);
  9360. this._vertexAttribArraysEnabled[order] = true;
  9361. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9362. }
  9363. offset += vertexDeclaration[index] * 4;
  9364. }
  9365. }
  9366. }
  9367. this._bindIndexBufferWithCache(indexBuffer);
  9368. };
  9369. Engine.prototype._unbindVertexArrayObject = function () {
  9370. if (!this._cachedVertexArrayObject) {
  9371. return;
  9372. }
  9373. this._cachedVertexArrayObject = null;
  9374. this._gl.bindVertexArray(null);
  9375. };
  9376. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9377. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9378. this._cachedVertexBuffers = vertexBuffers;
  9379. this._cachedEffectForVertexBuffers = effect;
  9380. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9381. }
  9382. this._bindIndexBufferWithCache(indexBuffer);
  9383. };
  9384. Engine.prototype.unbindInstanceAttributes = function () {
  9385. var boundBuffer;
  9386. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9387. var instancesBuffer = this._currentInstanceBuffers[i];
  9388. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9389. boundBuffer = instancesBuffer;
  9390. this.bindArrayBuffer(instancesBuffer);
  9391. }
  9392. var offsetLocation = this._currentInstanceLocations[i];
  9393. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9394. }
  9395. this._currentInstanceBuffers.length = 0;
  9396. this._currentInstanceLocations.length = 0;
  9397. };
  9398. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9399. this._gl.deleteVertexArray(vao);
  9400. };
  9401. Engine.prototype._releaseBuffer = function (buffer) {
  9402. buffer.references--;
  9403. if (buffer.references === 0) {
  9404. this._gl.deleteBuffer(buffer);
  9405. return true;
  9406. }
  9407. return false;
  9408. };
  9409. Engine.prototype.createInstancesBuffer = function (capacity) {
  9410. var buffer = this._gl.createBuffer();
  9411. buffer.capacity = capacity;
  9412. this.bindArrayBuffer(buffer);
  9413. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9414. return buffer;
  9415. };
  9416. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9417. this._gl.deleteBuffer(buffer);
  9418. };
  9419. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9420. this.bindArrayBuffer(instancesBuffer);
  9421. if (data) {
  9422. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9423. }
  9424. if (offsetLocations[0].index !== undefined) {
  9425. var stride = 0;
  9426. for (var i = 0; i < offsetLocations.length; i++) {
  9427. var ai = offsetLocations[i];
  9428. stride += ai.attributeSize * 4;
  9429. }
  9430. for (var i = 0; i < offsetLocations.length; i++) {
  9431. var ai = offsetLocations[i];
  9432. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9433. this._gl.enableVertexAttribArray(ai.index);
  9434. this._vertexAttribArraysEnabled[ai.index] = true;
  9435. }
  9436. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9437. this._gl.vertexAttribDivisor(ai.index, 1);
  9438. this._currentInstanceLocations.push(ai.index);
  9439. this._currentInstanceBuffers.push(instancesBuffer);
  9440. }
  9441. }
  9442. else {
  9443. for (var index = 0; index < 4; index++) {
  9444. var offsetLocation = offsetLocations[index];
  9445. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9446. this._gl.enableVertexAttribArray(offsetLocation);
  9447. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9448. }
  9449. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9450. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9451. this._currentInstanceLocations.push(offsetLocation);
  9452. this._currentInstanceBuffers.push(instancesBuffer);
  9453. }
  9454. }
  9455. };
  9456. Engine.prototype.applyStates = function () {
  9457. this._depthCullingState.apply(this._gl);
  9458. this._stencilState.apply(this._gl);
  9459. this._alphaState.apply(this._gl);
  9460. };
  9461. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9462. // Apply states
  9463. this.applyStates();
  9464. this._drawCalls.addCount(1, false);
  9465. // Render
  9466. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9467. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9468. if (instancesCount) {
  9469. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9470. return;
  9471. }
  9472. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9473. };
  9474. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9475. // Apply states
  9476. this.applyStates();
  9477. this._drawCalls.addCount(1, false);
  9478. if (instancesCount) {
  9479. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9480. return;
  9481. }
  9482. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9483. };
  9484. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9485. // Apply states
  9486. this.applyStates();
  9487. this._drawCalls.addCount(1, false);
  9488. if (instancesCount) {
  9489. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9490. return;
  9491. }
  9492. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9493. };
  9494. // Shaders
  9495. Engine.prototype._releaseEffect = function (effect) {
  9496. if (this._compiledEffects[effect._key]) {
  9497. delete this._compiledEffects[effect._key];
  9498. if (effect.getProgram()) {
  9499. this._gl.deleteProgram(effect.getProgram());
  9500. }
  9501. }
  9502. };
  9503. /**
  9504. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9505. * @param samplers An array of string used to represent textures
  9506. */
  9507. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9508. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9509. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9510. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9511. if (this._compiledEffects[name]) {
  9512. var compiledEffect = this._compiledEffects[name];
  9513. if (onCompiled && compiledEffect.isReady()) {
  9514. onCompiled(compiledEffect);
  9515. }
  9516. return compiledEffect;
  9517. }
  9518. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9519. effect._key = name;
  9520. this._compiledEffects[name] = effect;
  9521. return effect;
  9522. };
  9523. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9524. if (uniformsNames === void 0) { uniformsNames = []; }
  9525. if (samplers === void 0) { samplers = []; }
  9526. if (defines === void 0) { defines = ""; }
  9527. return this.createEffect({
  9528. vertex: "particles",
  9529. fragmentElement: fragmentName
  9530. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9531. };
  9532. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9533. context = context || this._gl;
  9534. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9535. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9536. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9537. var shaderProgram = context.createProgram();
  9538. context.attachShader(shaderProgram, vertexShader);
  9539. context.attachShader(shaderProgram, fragmentShader);
  9540. context.linkProgram(shaderProgram);
  9541. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9542. if (!linked) {
  9543. context.validateProgram(shaderProgram);
  9544. var error = context.getProgramInfoLog(shaderProgram);
  9545. if (error) {
  9546. throw new Error(error);
  9547. }
  9548. }
  9549. context.deleteShader(vertexShader);
  9550. context.deleteShader(fragmentShader);
  9551. return shaderProgram;
  9552. };
  9553. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9554. var results = [];
  9555. for (var index = 0; index < uniformsNames.length; index++) {
  9556. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9557. }
  9558. return results;
  9559. };
  9560. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9561. var results = [];
  9562. for (var index = 0; index < attributesNames.length; index++) {
  9563. try {
  9564. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9565. }
  9566. catch (e) {
  9567. results.push(-1);
  9568. }
  9569. }
  9570. return results;
  9571. };
  9572. Engine.prototype.enableEffect = function (effect) {
  9573. // Use program
  9574. this.setProgram(effect.getProgram());
  9575. this._currentEffect = effect;
  9576. if (effect.onBind) {
  9577. effect.onBind(effect);
  9578. }
  9579. effect.onBindObservable.notifyObservers(effect);
  9580. };
  9581. Engine.prototype.setIntArray = function (uniform, array) {
  9582. if (!uniform)
  9583. return;
  9584. this._gl.uniform1iv(uniform, array);
  9585. };
  9586. Engine.prototype.setIntArray2 = function (uniform, array) {
  9587. if (!uniform || array.length % 2 !== 0)
  9588. return;
  9589. this._gl.uniform2iv(uniform, array);
  9590. };
  9591. Engine.prototype.setIntArray3 = function (uniform, array) {
  9592. if (!uniform || array.length % 3 !== 0)
  9593. return;
  9594. this._gl.uniform3iv(uniform, array);
  9595. };
  9596. Engine.prototype.setIntArray4 = function (uniform, array) {
  9597. if (!uniform || array.length % 4 !== 0)
  9598. return;
  9599. this._gl.uniform4iv(uniform, array);
  9600. };
  9601. Engine.prototype.setFloatArray = function (uniform, array) {
  9602. if (!uniform)
  9603. return;
  9604. this._gl.uniform1fv(uniform, array);
  9605. };
  9606. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9607. if (!uniform || array.length % 2 !== 0)
  9608. return;
  9609. this._gl.uniform2fv(uniform, array);
  9610. };
  9611. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9612. if (!uniform || array.length % 3 !== 0)
  9613. return;
  9614. this._gl.uniform3fv(uniform, array);
  9615. };
  9616. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9617. if (!uniform || array.length % 4 !== 0)
  9618. return;
  9619. this._gl.uniform4fv(uniform, array);
  9620. };
  9621. Engine.prototype.setArray = function (uniform, array) {
  9622. if (!uniform)
  9623. return;
  9624. this._gl.uniform1fv(uniform, array);
  9625. };
  9626. Engine.prototype.setArray2 = function (uniform, array) {
  9627. if (!uniform || array.length % 2 !== 0)
  9628. return;
  9629. this._gl.uniform2fv(uniform, array);
  9630. };
  9631. Engine.prototype.setArray3 = function (uniform, array) {
  9632. if (!uniform || array.length % 3 !== 0)
  9633. return;
  9634. this._gl.uniform3fv(uniform, array);
  9635. };
  9636. Engine.prototype.setArray4 = function (uniform, array) {
  9637. if (!uniform || array.length % 4 !== 0)
  9638. return;
  9639. this._gl.uniform4fv(uniform, array);
  9640. };
  9641. Engine.prototype.setMatrices = function (uniform, matrices) {
  9642. if (!uniform)
  9643. return;
  9644. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9645. };
  9646. Engine.prototype.setMatrix = function (uniform, matrix) {
  9647. if (!uniform)
  9648. return;
  9649. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9650. };
  9651. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9652. if (!uniform)
  9653. return;
  9654. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9655. };
  9656. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9657. if (!uniform)
  9658. return;
  9659. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9660. };
  9661. Engine.prototype.setFloat = function (uniform, value) {
  9662. if (!uniform)
  9663. return;
  9664. this._gl.uniform1f(uniform, value);
  9665. };
  9666. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9667. if (!uniform)
  9668. return;
  9669. this._gl.uniform2f(uniform, x, y);
  9670. };
  9671. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9672. if (!uniform)
  9673. return;
  9674. this._gl.uniform3f(uniform, x, y, z);
  9675. };
  9676. Engine.prototype.setBool = function (uniform, bool) {
  9677. if (!uniform)
  9678. return;
  9679. this._gl.uniform1i(uniform, bool);
  9680. };
  9681. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9682. if (!uniform)
  9683. return;
  9684. this._gl.uniform4f(uniform, x, y, z, w);
  9685. };
  9686. Engine.prototype.setColor3 = function (uniform, color3) {
  9687. if (!uniform)
  9688. return;
  9689. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9690. };
  9691. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9692. if (!uniform)
  9693. return;
  9694. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9695. };
  9696. // States
  9697. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9698. if (zOffset === void 0) { zOffset = 0; }
  9699. if (reverseSide === void 0) { reverseSide = false; }
  9700. // Culling
  9701. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9702. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9703. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9704. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9705. if (culling) {
  9706. this._depthCullingState.cullFace = cullFace;
  9707. this._depthCullingState.cull = true;
  9708. }
  9709. else {
  9710. this._depthCullingState.cull = false;
  9711. }
  9712. }
  9713. // Z offset
  9714. this.setZOffset(zOffset);
  9715. };
  9716. Engine.prototype.setZOffset = function (value) {
  9717. this._depthCullingState.zOffset = value;
  9718. };
  9719. Engine.prototype.getZOffset = function () {
  9720. return this._depthCullingState.zOffset;
  9721. };
  9722. Engine.prototype.setDepthBuffer = function (enable) {
  9723. this._depthCullingState.depthTest = enable;
  9724. };
  9725. Engine.prototype.getDepthWrite = function () {
  9726. return this._depthCullingState.depthMask;
  9727. };
  9728. Engine.prototype.setDepthWrite = function (enable) {
  9729. this._depthCullingState.depthMask = enable;
  9730. };
  9731. Engine.prototype.setColorWrite = function (enable) {
  9732. this._gl.colorMask(enable, enable, enable, enable);
  9733. this._colorWrite = enable;
  9734. };
  9735. Engine.prototype.getColorWrite = function () {
  9736. return this._colorWrite;
  9737. };
  9738. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9739. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9740. };
  9741. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9742. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9743. if (this._alphaMode === mode) {
  9744. return;
  9745. }
  9746. switch (mode) {
  9747. case Engine.ALPHA_DISABLE:
  9748. this._alphaState.alphaBlend = false;
  9749. break;
  9750. case Engine.ALPHA_PREMULTIPLIED:
  9751. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9752. this._alphaState.alphaBlend = true;
  9753. break;
  9754. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9755. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9756. this._alphaState.alphaBlend = true;
  9757. break;
  9758. case Engine.ALPHA_COMBINE:
  9759. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9760. this._alphaState.alphaBlend = true;
  9761. break;
  9762. case Engine.ALPHA_ONEONE:
  9763. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9764. this._alphaState.alphaBlend = true;
  9765. break;
  9766. case Engine.ALPHA_ADD:
  9767. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9768. this._alphaState.alphaBlend = true;
  9769. break;
  9770. case Engine.ALPHA_SUBTRACT:
  9771. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9772. this._alphaState.alphaBlend = true;
  9773. break;
  9774. case Engine.ALPHA_MULTIPLY:
  9775. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9776. this._alphaState.alphaBlend = true;
  9777. break;
  9778. case Engine.ALPHA_MAXIMIZED:
  9779. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9780. this._alphaState.alphaBlend = true;
  9781. break;
  9782. case Engine.ALPHA_INTERPOLATE:
  9783. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9784. this._alphaState.alphaBlend = true;
  9785. break;
  9786. case Engine.ALPHA_SCREENMODE:
  9787. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9788. this._alphaState.alphaBlend = true;
  9789. break;
  9790. }
  9791. if (!noDepthWriteChange) {
  9792. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9793. }
  9794. this._alphaMode = mode;
  9795. };
  9796. Engine.prototype.getAlphaMode = function () {
  9797. return this._alphaMode;
  9798. };
  9799. Engine.prototype.setAlphaTesting = function (enable) {
  9800. this._alphaTest = enable;
  9801. };
  9802. Engine.prototype.getAlphaTesting = function () {
  9803. return !!this._alphaTest;
  9804. };
  9805. // Textures
  9806. Engine.prototype.wipeCaches = function (bruteForce) {
  9807. if (this.preventCacheWipeBetweenFrames) {
  9808. return;
  9809. }
  9810. this.resetTextureCache();
  9811. this._currentEffect = null;
  9812. // 6/8/2017: deltakosh: Should not be required anymore.
  9813. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9814. if (bruteForce) {
  9815. this._currentProgram = null;
  9816. this._stencilState.reset();
  9817. this._depthCullingState.reset();
  9818. this.setDepthFunctionToLessOrEqual();
  9819. this._alphaState.reset();
  9820. }
  9821. this._cachedVertexBuffers = null;
  9822. this._cachedIndexBuffer = null;
  9823. this._cachedEffectForVertexBuffers = null;
  9824. this._unbindVertexArrayObject();
  9825. this.bindIndexBuffer(null);
  9826. this.bindArrayBuffer(null);
  9827. };
  9828. /**
  9829. * Set the compressed texture format to use, based on the formats you have, and the formats
  9830. * supported by the hardware / browser.
  9831. *
  9832. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9833. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9834. * to API arguments needed to compressed textures. This puts the burden on the container
  9835. * generator to house the arcane code for determining these for current & future formats.
  9836. *
  9837. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9838. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9839. *
  9840. * Note: The result of this call is not taken into account when a texture is base64.
  9841. *
  9842. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9843. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9844. *
  9845. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9846. * @returns The extension selected.
  9847. */
  9848. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9849. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9850. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9851. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9852. return this._textureFormatInUse = this._texturesSupported[i];
  9853. }
  9854. }
  9855. }
  9856. // actively set format to nothing, to allow this to be called more than once
  9857. // and possibly fail the 2nd time
  9858. return this._textureFormatInUse = null;
  9859. };
  9860. Engine.prototype._createTexture = function () {
  9861. return this._gl.createTexture();
  9862. };
  9863. /**
  9864. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9865. * @param {string} urlArg- This contains one of the following:
  9866. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9867. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9868. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9869. *
  9870. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9871. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9872. * @param {Scene} scene- Needed for loading to the correct scene.
  9873. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9874. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9875. * @param {callback} onError- Optional callback to be called upon failure.
  9876. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9877. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9878. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9879. *
  9880. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9881. */
  9882. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9883. var _this = this;
  9884. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9885. if (onLoad === void 0) { onLoad = null; }
  9886. if (onError === void 0) { onError = null; }
  9887. if (buffer === void 0) { buffer = null; }
  9888. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9889. var fromData = url.substr(0, 5) === "data:";
  9890. var fromBlob = url.substr(0, 5) === "blob:";
  9891. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9892. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  9893. // establish the file extension, if possible
  9894. var lastDot = url.lastIndexOf('.');
  9895. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9896. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9897. var isTGA = (extension === ".tga");
  9898. // determine if a ktx file should be substituted
  9899. var isKTX = false;
  9900. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9901. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9902. isKTX = true;
  9903. }
  9904. if (scene) {
  9905. scene._addPendingData(texture);
  9906. }
  9907. texture.url = url;
  9908. texture.generateMipMaps = !noMipmap;
  9909. texture.samplingMode = samplingMode;
  9910. texture.invertY = invertY;
  9911. if (!this._doNotHandleContextLost) {
  9912. // Keep a link to the buffer only if we plan to handle context lost
  9913. texture._buffer = buffer;
  9914. }
  9915. if (onLoad) {
  9916. texture.onLoadedObservable.add(onLoad);
  9917. }
  9918. if (!fallBack)
  9919. this._internalTexturesCache.push(texture);
  9920. var onerror = function () {
  9921. if (scene) {
  9922. scene._removePendingData(texture);
  9923. }
  9924. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9925. if (isKTX) {
  9926. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9927. }
  9928. else if (onError) {
  9929. onError();
  9930. }
  9931. };
  9932. var callback;
  9933. // processing for non-image formats
  9934. if (isKTX || isTGA || isDDS) {
  9935. if (isKTX) {
  9936. callback = function (data) {
  9937. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9938. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9939. ktx.uploadLevels(_this._gl, !noMipmap);
  9940. return false;
  9941. }, samplingMode);
  9942. };
  9943. }
  9944. else if (isTGA) {
  9945. callback = function (arrayBuffer) {
  9946. var data = new Uint8Array(arrayBuffer);
  9947. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9948. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9949. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9950. return false;
  9951. }, samplingMode);
  9952. };
  9953. }
  9954. else if (isDDS) {
  9955. callback = function (data) {
  9956. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9957. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9958. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9959. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  9960. return false;
  9961. }, samplingMode);
  9962. };
  9963. }
  9964. if (!buffer) {
  9965. BABYLON.Tools.LoadFile(url, function (data) {
  9966. callback(data);
  9967. }, null, scene ? scene.database : null, true, onerror);
  9968. }
  9969. else {
  9970. callback(buffer);
  9971. }
  9972. // image format processing
  9973. }
  9974. else {
  9975. var onload = function (img) {
  9976. if (fromBlob && !_this._doNotHandleContextLost) {
  9977. // We need to store the image if we need to rebuild the texture
  9978. // in case of a webgl context lost
  9979. texture._buffer = img;
  9980. }
  9981. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  9982. var gl = _this._gl;
  9983. var isPot = (img.width === potWidth && img.height === potHeight);
  9984. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  9985. if (isPot) {
  9986. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9987. return false;
  9988. }
  9989. // Using shaders to rescale because canvas.drawImage is lossy
  9990. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  9991. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  9992. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9993. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9994. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  9995. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9996. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9997. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  9998. _this._releaseTexture(source);
  9999. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10000. continuationCallback();
  10001. });
  10002. return true;
  10003. }, samplingMode);
  10004. };
  10005. if (!fromData || isBase64)
  10006. if (buffer instanceof HTMLImageElement) {
  10007. onload(buffer);
  10008. }
  10009. else {
  10010. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10011. }
  10012. else if (buffer instanceof Array || typeof buffer === "string")
  10013. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10014. else
  10015. onload(buffer);
  10016. }
  10017. return texture;
  10018. };
  10019. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10020. var _this = this;
  10021. var rtt = this.createRenderTargetTexture({
  10022. width: destination.width,
  10023. height: destination.height,
  10024. }, {
  10025. generateMipMaps: false,
  10026. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10027. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10028. generateDepthBuffer: false,
  10029. generateStencilBuffer: false
  10030. });
  10031. if (!this._rescalePostProcess) {
  10032. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10033. }
  10034. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10035. _this._rescalePostProcess.onApply = function (effect) {
  10036. effect._bindTexture("textureSampler", source);
  10037. };
  10038. var hostingScene = scene;
  10039. if (!hostingScene) {
  10040. hostingScene = _this.scenes[_this.scenes.length - 1];
  10041. }
  10042. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  10043. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  10044. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10045. _this.unBindFramebuffer(rtt);
  10046. _this._releaseTexture(rtt);
  10047. if (onComplete) {
  10048. onComplete();
  10049. }
  10050. });
  10051. };
  10052. Engine.prototype._getInternalFormat = function (format) {
  10053. var internalFormat = this._gl.RGBA;
  10054. switch (format) {
  10055. case Engine.TEXTUREFORMAT_ALPHA:
  10056. internalFormat = this._gl.ALPHA;
  10057. break;
  10058. case Engine.TEXTUREFORMAT_LUMINANCE:
  10059. internalFormat = this._gl.LUMINANCE;
  10060. break;
  10061. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10062. internalFormat = this._gl.LUMINANCE_ALPHA;
  10063. break;
  10064. case Engine.TEXTUREFORMAT_RGB:
  10065. internalFormat = this._gl.RGB;
  10066. break;
  10067. case Engine.TEXTUREFORMAT_RGBA:
  10068. internalFormat = this._gl.RGBA;
  10069. break;
  10070. }
  10071. return internalFormat;
  10072. };
  10073. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  10074. if (compression === void 0) { compression = null; }
  10075. var internalFormat = this._getInternalFormat(format);
  10076. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10077. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10078. if (!this._doNotHandleContextLost) {
  10079. texture._bufferView = data;
  10080. texture.format = format;
  10081. texture.invertY = invertY;
  10082. texture._compression = compression;
  10083. }
  10084. if (texture.width % 4 !== 0) {
  10085. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10086. }
  10087. if (compression) {
  10088. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10089. }
  10090. else {
  10091. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  10092. }
  10093. if (texture.generateMipMaps) {
  10094. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10095. }
  10096. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10097. this.resetTextureCache();
  10098. texture.isReady = true;
  10099. };
  10100. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  10101. if (compression === void 0) { compression = null; }
  10102. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10103. texture.baseWidth = width;
  10104. texture.baseHeight = height;
  10105. texture.width = width;
  10106. texture.height = height;
  10107. texture.format = format;
  10108. texture.generateMipMaps = generateMipMaps;
  10109. texture.samplingMode = samplingMode;
  10110. texture.invertY = invertY;
  10111. texture._compression = compression;
  10112. if (!this._doNotHandleContextLost) {
  10113. texture._bufferView = data;
  10114. }
  10115. this.updateRawTexture(texture, data, format, invertY, compression);
  10116. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10117. // Filters
  10118. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10119. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10120. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10121. if (generateMipMaps) {
  10122. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10123. }
  10124. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10125. this._internalTexturesCache.push(texture);
  10126. return texture;
  10127. };
  10128. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10129. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10130. texture.baseWidth = width;
  10131. texture.baseHeight = height;
  10132. if (generateMipMaps) {
  10133. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10134. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10135. }
  10136. this.resetTextureCache();
  10137. texture.width = width;
  10138. texture.height = height;
  10139. texture.isReady = false;
  10140. texture.generateMipMaps = generateMipMaps;
  10141. texture.samplingMode = samplingMode;
  10142. this.updateTextureSamplingMode(samplingMode, texture);
  10143. this._internalTexturesCache.push(texture);
  10144. return texture;
  10145. };
  10146. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10147. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10148. if (texture.isCube) {
  10149. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10150. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10151. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10152. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10153. }
  10154. else {
  10155. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10156. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10157. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10158. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10159. }
  10160. texture.samplingMode = samplingMode;
  10161. };
  10162. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10163. if (premulAlpha === void 0) { premulAlpha = false; }
  10164. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10165. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10166. if (premulAlpha) {
  10167. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10168. }
  10169. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10170. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10171. if (texture.generateMipMaps) {
  10172. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10173. }
  10174. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10175. if (premulAlpha) {
  10176. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10177. }
  10178. this.resetTextureCache();
  10179. texture.isReady = true;
  10180. };
  10181. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10182. if (texture._isDisabled) {
  10183. return;
  10184. }
  10185. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10186. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10187. try {
  10188. // Testing video texture support
  10189. if (this._videoTextureSupported === undefined) {
  10190. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10191. if (this._gl.getError() !== 0) {
  10192. this._videoTextureSupported = false;
  10193. }
  10194. else {
  10195. this._videoTextureSupported = true;
  10196. }
  10197. }
  10198. // Copy video through the current working canvas if video texture is not supported
  10199. if (!this._videoTextureSupported) {
  10200. if (!texture._workingCanvas) {
  10201. texture._workingCanvas = document.createElement("canvas");
  10202. texture._workingContext = texture._workingCanvas.getContext("2d");
  10203. texture._workingCanvas.width = texture.width;
  10204. texture._workingCanvas.height = texture.height;
  10205. }
  10206. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10207. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10208. }
  10209. else {
  10210. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10211. }
  10212. if (texture.generateMipMaps) {
  10213. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10214. }
  10215. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10216. this.resetTextureCache();
  10217. texture.isReady = true;
  10218. }
  10219. catch (ex) {
  10220. // Something unexpected
  10221. // Let's disable the texture
  10222. texture._isDisabled = true;
  10223. }
  10224. };
  10225. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10226. var fullOptions = new RenderTargetCreationOptions();
  10227. if (options !== undefined && typeof options === "object") {
  10228. fullOptions.generateMipMaps = options.generateMipMaps;
  10229. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10230. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10231. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10232. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10233. }
  10234. else {
  10235. fullOptions.generateMipMaps = options;
  10236. fullOptions.generateDepthBuffer = true;
  10237. fullOptions.generateStencilBuffer = false;
  10238. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10239. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10240. }
  10241. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10242. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10243. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10244. }
  10245. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10246. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10247. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10248. }
  10249. var gl = this._gl;
  10250. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10251. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10252. var width = size.width || size;
  10253. var height = size.height || size;
  10254. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  10255. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10256. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10257. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10258. }
  10259. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10260. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10261. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10262. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10263. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10264. // Create the framebuffer
  10265. var framebuffer = gl.createFramebuffer();
  10266. this.bindUnboundFramebuffer(framebuffer);
  10267. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10268. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, width, height);
  10269. if (fullOptions.generateMipMaps) {
  10270. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10271. }
  10272. // Unbind
  10273. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10274. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10275. this.bindUnboundFramebuffer(null);
  10276. texture._framebuffer = framebuffer;
  10277. texture.baseWidth = width;
  10278. texture.baseHeight = height;
  10279. texture.width = width;
  10280. texture.height = height;
  10281. texture.isReady = true;
  10282. texture.samples = 1;
  10283. texture.generateMipMaps = fullOptions.generateMipMaps;
  10284. texture.samplingMode = fullOptions.samplingMode;
  10285. texture.type = fullOptions.type;
  10286. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10287. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  10288. this.resetTextureCache();
  10289. this._internalTexturesCache.push(texture);
  10290. return texture;
  10291. };
  10292. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10293. var generateMipMaps = false;
  10294. var generateDepthBuffer = true;
  10295. var generateStencilBuffer = false;
  10296. var generateDepthTexture = false;
  10297. var textureCount = 1;
  10298. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10299. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10300. var types = [], samplingModes = [];
  10301. if (options !== undefined) {
  10302. generateMipMaps = options.generateMipMaps;
  10303. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10304. generateStencilBuffer = options.generateStencilBuffer;
  10305. generateDepthTexture = options.generateDepthTexture;
  10306. textureCount = options.textureCount || 1;
  10307. if (options.types) {
  10308. types = options.types;
  10309. }
  10310. if (options.samplingModes) {
  10311. samplingModes = options.samplingModes;
  10312. }
  10313. }
  10314. var gl = this._gl;
  10315. // Create the framebuffer
  10316. var framebuffer = gl.createFramebuffer();
  10317. this.bindUnboundFramebuffer(framebuffer);
  10318. var width = size.width || size;
  10319. var height = size.height || size;
  10320. var textures = [];
  10321. var attachments = [];
  10322. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10323. for (var i = 0; i < textureCount; i++) {
  10324. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10325. var type = types[i] || defaultType;
  10326. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10327. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10328. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10329. }
  10330. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10331. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10332. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10333. }
  10334. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10335. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10336. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10337. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10338. }
  10339. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10340. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10341. textures.push(texture);
  10342. attachments.push(attachment);
  10343. gl.activeTexture(gl["TEXTURE" + i]);
  10344. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10345. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10346. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10347. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10348. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10349. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10350. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10351. if (generateMipMaps) {
  10352. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10353. }
  10354. // Unbind
  10355. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10356. texture._framebuffer = framebuffer;
  10357. texture._depthStencilBuffer = depthStencilBuffer;
  10358. texture.baseWidth = width;
  10359. texture.baseHeight = height;
  10360. texture.width = width;
  10361. texture.height = height;
  10362. texture.isReady = true;
  10363. texture.samples = 1;
  10364. texture.generateMipMaps = generateMipMaps;
  10365. texture.samplingMode = samplingMode;
  10366. texture.type = type;
  10367. texture._generateDepthBuffer = generateDepthBuffer;
  10368. texture._generateStencilBuffer = generateStencilBuffer;
  10369. this._internalTexturesCache.push(texture);
  10370. }
  10371. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10372. // Depth texture
  10373. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10374. gl.activeTexture(gl.TEXTURE0);
  10375. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10376. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10377. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10378. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10379. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10380. 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);
  10381. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10382. depthTexture._framebuffer = framebuffer;
  10383. depthTexture.baseWidth = width;
  10384. depthTexture.baseHeight = height;
  10385. depthTexture.width = width;
  10386. depthTexture.height = height;
  10387. depthTexture.isReady = true;
  10388. depthTexture.samples = 1;
  10389. depthTexture.generateMipMaps = generateMipMaps;
  10390. depthTexture.samplingMode = gl.NEAREST;
  10391. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10392. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10393. textures.push(depthTexture);
  10394. this._internalTexturesCache.push(depthTexture);
  10395. }
  10396. gl.drawBuffers(attachments);
  10397. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10398. this.bindUnboundFramebuffer(null);
  10399. this.resetTextureCache();
  10400. return textures;
  10401. };
  10402. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10403. if (samples === void 0) { samples = 1; }
  10404. var depthStencilBuffer = null;
  10405. var gl = this._gl;
  10406. // Create the depth/stencil buffer
  10407. if (generateStencilBuffer) {
  10408. depthStencilBuffer = gl.createRenderbuffer();
  10409. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10410. if (samples > 1) {
  10411. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10412. }
  10413. else {
  10414. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10415. }
  10416. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10417. }
  10418. else if (generateDepthBuffer) {
  10419. depthStencilBuffer = gl.createRenderbuffer();
  10420. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10421. if (samples > 1) {
  10422. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10423. }
  10424. else {
  10425. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10426. }
  10427. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10428. }
  10429. return depthStencilBuffer;
  10430. };
  10431. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10432. if (this.webGLVersion < 2) {
  10433. return 1;
  10434. }
  10435. if (texture.samples === samples) {
  10436. return samples;
  10437. }
  10438. var gl = this._gl;
  10439. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10440. // Dispose previous render buffers
  10441. if (texture._depthStencilBuffer) {
  10442. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10443. }
  10444. if (texture._MSAAFramebuffer) {
  10445. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10446. }
  10447. if (texture._MSAARenderBuffer) {
  10448. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10449. }
  10450. if (samples > 1) {
  10451. texture._MSAAFramebuffer = gl.createFramebuffer();
  10452. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10453. var colorRenderbuffer = gl.createRenderbuffer();
  10454. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10455. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10456. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10457. texture._MSAARenderBuffer = colorRenderbuffer;
  10458. }
  10459. else {
  10460. this.bindUnboundFramebuffer(texture._framebuffer);
  10461. }
  10462. texture.samples = samples;
  10463. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10464. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10465. this.bindUnboundFramebuffer(null);
  10466. return samples;
  10467. };
  10468. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10469. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10470. };
  10471. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10472. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10473. };
  10474. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10475. var gl = this._gl;
  10476. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10477. var generateMipMaps = true;
  10478. var generateDepthBuffer = true;
  10479. var generateStencilBuffer = false;
  10480. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10481. if (options !== undefined) {
  10482. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10483. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10484. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  10485. if (options.samplingMode !== undefined) {
  10486. samplingMode = options.samplingMode;
  10487. }
  10488. }
  10489. texture.isCube = true;
  10490. texture.generateMipMaps = generateMipMaps;
  10491. texture.samples = 1;
  10492. texture.samplingMode = samplingMode;
  10493. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10494. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10495. for (var face = 0; face < 6; face++) {
  10496. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10497. }
  10498. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10499. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10500. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10501. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10502. // Create the framebuffer
  10503. var framebuffer = gl.createFramebuffer();
  10504. this.bindUnboundFramebuffer(framebuffer);
  10505. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10506. // Mipmaps
  10507. if (texture.generateMipMaps) {
  10508. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10509. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10510. }
  10511. // Unbind
  10512. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10513. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10514. this.bindUnboundFramebuffer(null);
  10515. texture._framebuffer = framebuffer;
  10516. texture.width = size;
  10517. texture.height = size;
  10518. texture.isReady = true;
  10519. this.resetTextureCache();
  10520. this._internalTexturesCache.push(texture);
  10521. return texture;
  10522. };
  10523. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10524. var _this = this;
  10525. if (onError === void 0) { onError = null; }
  10526. if (forcedExtension === void 0) { forcedExtension = null; }
  10527. var callback = function (loadData) {
  10528. if (!loadData) {
  10529. if (onLoad) {
  10530. onLoad(null);
  10531. }
  10532. return;
  10533. }
  10534. var texture = loadData.texture;
  10535. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10536. texture._lodGenerationScale = scale;
  10537. texture._lodGenerationOffset = offset;
  10538. if (_this._caps.textureLOD) {
  10539. // Do not add extra process if texture lod is supported.
  10540. if (onLoad) {
  10541. onLoad(texture);
  10542. }
  10543. return;
  10544. }
  10545. var mipSlices = 3;
  10546. var gl = _this._gl;
  10547. var width = loadData.width;
  10548. if (!width) {
  10549. return;
  10550. }
  10551. var textures = [];
  10552. for (var i = 0; i < mipSlices; i++) {
  10553. //compute LOD from even spacing in smoothness (matching shader calculation)
  10554. var smoothness = i / (mipSlices - 1);
  10555. var roughness = 1 - smoothness;
  10556. var minLODIndex = offset; // roughness = 0
  10557. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10558. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10559. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10560. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10561. glTextureFromLod.isCube = true;
  10562. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10563. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10564. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10565. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10566. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10567. if (loadData.isDDS) {
  10568. var info = loadData.info;
  10569. var data = loadData.data;
  10570. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10571. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10572. }
  10573. else {
  10574. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10575. }
  10576. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10577. // Wrap in a base texture for easy binding.
  10578. var lodTexture = new BABYLON.BaseTexture(scene);
  10579. lodTexture.isCube = true;
  10580. lodTexture._texture = glTextureFromLod;
  10581. glTextureFromLod.isReady = true;
  10582. textures.push(lodTexture);
  10583. }
  10584. texture._lodTextureHigh = textures[2];
  10585. texture._lodTextureMid = textures[1];
  10586. texture._lodTextureLow = textures[0];
  10587. if (onLoad) {
  10588. onLoad(texture);
  10589. }
  10590. };
  10591. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10592. };
  10593. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10594. var _this = this;
  10595. if (onLoad === void 0) { onLoad = null; }
  10596. if (onError === void 0) { onError = null; }
  10597. if (forcedExtension === void 0) { forcedExtension = null; }
  10598. var gl = this._gl;
  10599. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10600. texture.isCube = true;
  10601. texture.url = rootUrl;
  10602. texture.generateMipMaps = !noMipmap;
  10603. if (!this._doNotHandleContextLost) {
  10604. texture._extension = forcedExtension;
  10605. texture._files = files;
  10606. }
  10607. var isKTX = false;
  10608. var isDDS = false;
  10609. var lastDot = rootUrl.lastIndexOf('.');
  10610. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  10611. if (this._textureFormatInUse) {
  10612. extension = this._textureFormatInUse;
  10613. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10614. isKTX = true;
  10615. }
  10616. else {
  10617. isDDS = (extension === ".dds");
  10618. }
  10619. var onerror = function (request, exception) {
  10620. if (onError) {
  10621. onError(request.status + " " + request.statusText, exception);
  10622. }
  10623. };
  10624. if (isKTX) {
  10625. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10626. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10627. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10628. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10629. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10630. ktx.uploadLevels(_this._gl, !noMipmap);
  10631. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10632. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10633. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10634. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10635. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10636. _this.resetTextureCache();
  10637. texture.width = ktx.pixelWidth;
  10638. texture.height = ktx.pixelHeight;
  10639. texture.isReady = true;
  10640. }, null, null, true, onerror);
  10641. }
  10642. else if (isDDS) {
  10643. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10644. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10645. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10646. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10647. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10648. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10649. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10650. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10651. }
  10652. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10653. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10654. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10655. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10656. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10657. _this.resetTextureCache();
  10658. texture.width = info.width;
  10659. texture.height = info.height;
  10660. texture.isReady = true;
  10661. texture.type = info.textureType;
  10662. if (onLoad) {
  10663. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10664. }
  10665. }, null, null, true, onerror);
  10666. }
  10667. else {
  10668. cascadeLoad(rootUrl, scene, function (imgs) {
  10669. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10670. var height = width;
  10671. _this._prepareWorkingCanvas();
  10672. _this._workingCanvas.width = width;
  10673. _this._workingCanvas.height = height;
  10674. var faces = [
  10675. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10676. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10677. ];
  10678. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10679. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10680. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10681. for (var index = 0; index < faces.length; index++) {
  10682. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10683. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10684. }
  10685. if (!noMipmap) {
  10686. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10687. }
  10688. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10689. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10690. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10691. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10692. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10693. _this.resetTextureCache();
  10694. texture.width = width;
  10695. texture.height = height;
  10696. texture.isReady = true;
  10697. texture.format = format;
  10698. texture.onLoadedObservable.notifyObservers(texture);
  10699. texture.onLoadedObservable.clear();
  10700. if (onLoad) {
  10701. onLoad();
  10702. }
  10703. }, files, onError);
  10704. }
  10705. this._internalTexturesCache.push(texture);
  10706. return texture;
  10707. };
  10708. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10709. if (compression === void 0) { compression = null; }
  10710. if (level === void 0) { level = 0; }
  10711. texture._bufferViewArray = data;
  10712. texture.format = format;
  10713. texture.type = type;
  10714. texture.invertY = invertY;
  10715. texture._compression = compression;
  10716. var gl = this._gl;
  10717. var textureType = this._getWebGLTextureType(type);
  10718. var internalFormat = this._getInternalFormat(format);
  10719. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10720. var needConversion = false;
  10721. if (internalFormat === gl.RGB) {
  10722. internalFormat = gl.RGBA;
  10723. needConversion = true;
  10724. }
  10725. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10726. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10727. if (texture.width % 4 !== 0) {
  10728. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  10729. }
  10730. // Data are known to be in +X +Y +Z -X -Y -Z
  10731. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10732. var faceData = data[faceIndex];
  10733. if (compression) {
  10734. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  10735. }
  10736. else {
  10737. if (needConversion) {
  10738. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  10739. }
  10740. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  10741. }
  10742. }
  10743. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10744. if (isPot && texture.generateMipMaps && level === 0) {
  10745. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10746. }
  10747. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10748. this.resetTextureCache();
  10749. texture.isReady = true;
  10750. };
  10751. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  10752. if (compression === void 0) { compression = null; }
  10753. var gl = this._gl;
  10754. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  10755. texture.isCube = true;
  10756. texture.generateMipMaps = generateMipMaps;
  10757. texture.format = format;
  10758. texture.type = type;
  10759. if (!this._doNotHandleContextLost) {
  10760. texture._bufferViewArray = data;
  10761. }
  10762. var textureType = this._getWebGLTextureType(type);
  10763. var internalFormat = this._getInternalFormat(format);
  10764. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10765. var needConversion = false;
  10766. if (internalFormat === gl.RGB) {
  10767. internalFormat = gl.RGBA;
  10768. needConversion = true;
  10769. }
  10770. var width = size;
  10771. var height = width;
  10772. texture.width = width;
  10773. texture.height = height;
  10774. // Double check on POT to generate Mips.
  10775. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10776. if (!isPot) {
  10777. generateMipMaps = false;
  10778. }
  10779. // Upload data if needed. The texture won't be ready until then.
  10780. if (data) {
  10781. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  10782. }
  10783. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10784. // Filters
  10785. if (data && generateMipMaps) {
  10786. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10787. }
  10788. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  10789. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10790. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10791. }
  10792. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  10793. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10794. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10795. }
  10796. else {
  10797. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10798. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10799. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10800. }
  10801. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10802. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10803. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10804. return texture;
  10805. };
  10806. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  10807. var _this = this;
  10808. if (onLoad === void 0) { onLoad = null; }
  10809. if (onError === void 0) { onError = null; }
  10810. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10811. if (invertY === void 0) { invertY = false; }
  10812. var gl = this._gl;
  10813. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  10814. scene._addPendingData(texture);
  10815. texture.url = url;
  10816. this._internalTexturesCache.push(texture);
  10817. var onerror = function (request, exception) {
  10818. scene._removePendingData(texture);
  10819. if (onError) {
  10820. onError(request.status + " " + request.statusText, exception);
  10821. }
  10822. };
  10823. var internalCallback = function (data) {
  10824. var width = texture.width;
  10825. var height = texture.height;
  10826. var faceDataArrays = callback(data);
  10827. if (mipmmapGenerator) {
  10828. var textureType = _this._getWebGLTextureType(type);
  10829. var internalFormat = _this._getInternalFormat(format);
  10830. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  10831. var needConversion = false;
  10832. if (internalFormat === gl.RGB) {
  10833. internalFormat = gl.RGBA;
  10834. needConversion = true;
  10835. }
  10836. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10837. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10838. var mipData = mipmmapGenerator(faceDataArrays);
  10839. for (var level = 0; level < mipData.length; level++) {
  10840. var mipSize = width >> level;
  10841. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10842. var mipFaceData = mipData[level][faceIndex];
  10843. if (needConversion) {
  10844. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10845. }
  10846. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10847. }
  10848. }
  10849. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10850. }
  10851. else {
  10852. texture.generateMipMaps = !noMipmap;
  10853. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  10854. }
  10855. texture.isReady = true;
  10856. _this.resetTextureCache();
  10857. scene._removePendingData(texture);
  10858. if (onLoad) {
  10859. onLoad();
  10860. }
  10861. };
  10862. BABYLON.Tools.LoadFile(url, function (data) {
  10863. internalCallback(data);
  10864. }, undefined, scene.database, true, onerror);
  10865. return texture;
  10866. };
  10867. ;
  10868. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  10869. var gl = this._gl;
  10870. if (!gl) {
  10871. return;
  10872. }
  10873. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  10874. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10875. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10876. if (!noMipmap && !isCompressed) {
  10877. gl.generateMipmap(gl.TEXTURE_2D);
  10878. }
  10879. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10880. this.resetTextureCache();
  10881. if (scene) {
  10882. scene._removePendingData(texture);
  10883. }
  10884. texture.onLoadedObservable.notifyObservers(texture);
  10885. texture.onLoadedObservable.clear();
  10886. };
  10887. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  10888. var _this = this;
  10889. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10890. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  10891. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  10892. var gl = this._gl;
  10893. if (!gl) {
  10894. return;
  10895. }
  10896. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10897. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10898. texture.baseWidth = width;
  10899. texture.baseHeight = height;
  10900. texture.width = potWidth;
  10901. texture.height = potHeight;
  10902. texture.isReady = true;
  10903. if (processFunction(potWidth, potHeight, function () {
  10904. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10905. })) {
  10906. // Returning as texture needs extra async steps
  10907. return;
  10908. }
  10909. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10910. };
  10911. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10912. // Create new RGBA data container.
  10913. var rgbaData;
  10914. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10915. rgbaData = new Float32Array(width * height * 4);
  10916. }
  10917. else {
  10918. rgbaData = new Uint32Array(width * height * 4);
  10919. }
  10920. // Convert each pixel.
  10921. for (var x = 0; x < width; x++) {
  10922. for (var y = 0; y < height; y++) {
  10923. var index = (y * width + x) * 3;
  10924. var newIndex = (y * width + x) * 4;
  10925. // Map Old Value to new value.
  10926. rgbaData[newIndex + 0] = rgbData[index + 0];
  10927. rgbaData[newIndex + 1] = rgbData[index + 1];
  10928. rgbaData[newIndex + 2] = rgbData[index + 2];
  10929. // Add fully opaque alpha channel.
  10930. rgbaData[newIndex + 3] = 1;
  10931. }
  10932. }
  10933. return rgbaData;
  10934. };
  10935. Engine.prototype._releaseFramebufferObjects = function (texture) {
  10936. var gl = this._gl;
  10937. if (texture._framebuffer) {
  10938. gl.deleteFramebuffer(texture._framebuffer);
  10939. texture._framebuffer = null;
  10940. }
  10941. if (texture._depthStencilBuffer) {
  10942. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10943. texture._depthStencilBuffer = null;
  10944. }
  10945. if (texture._MSAAFramebuffer) {
  10946. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10947. texture._MSAAFramebuffer = null;
  10948. }
  10949. if (texture._MSAARenderBuffer) {
  10950. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10951. texture._MSAARenderBuffer = null;
  10952. }
  10953. };
  10954. Engine.prototype._releaseTexture = function (texture) {
  10955. var gl = this._gl;
  10956. this._releaseFramebufferObjects(texture);
  10957. gl.deleteTexture(texture._webGLTexture);
  10958. // Unbind channels
  10959. this.unbindAllTextures();
  10960. var index = this._internalTexturesCache.indexOf(texture);
  10961. if (index !== -1) {
  10962. this._internalTexturesCache.splice(index, 1);
  10963. }
  10964. // Integrated fixed lod samplers.
  10965. if (texture._lodTextureHigh) {
  10966. texture._lodTextureHigh.dispose();
  10967. }
  10968. if (texture._lodTextureMid) {
  10969. texture._lodTextureMid.dispose();
  10970. }
  10971. if (texture._lodTextureLow) {
  10972. texture._lodTextureLow.dispose();
  10973. }
  10974. };
  10975. Engine.prototype.setProgram = function (program) {
  10976. if (this._currentProgram !== program) {
  10977. this._gl.useProgram(program);
  10978. this._currentProgram = program;
  10979. }
  10980. };
  10981. Engine.prototype.bindSamplers = function (effect) {
  10982. this.setProgram(effect.getProgram());
  10983. var samplers = effect.getSamplers();
  10984. for (var index = 0; index < samplers.length; index++) {
  10985. var uniform = effect.getUniform(samplers[index]);
  10986. this._gl.uniform1i(uniform, index);
  10987. }
  10988. this._currentEffect = null;
  10989. };
  10990. Engine.prototype.activateTexture = function (texture) {
  10991. if (this._activeTexture !== texture) {
  10992. this._gl.activeTexture(texture);
  10993. this._activeTexture = texture;
  10994. }
  10995. };
  10996. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10997. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10998. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  10999. this._activeTexturesCache[this._activeTexture] = texture;
  11000. }
  11001. };
  11002. Engine.prototype._bindTexture = function (channel, texture) {
  11003. if (channel < 0) {
  11004. return;
  11005. }
  11006. this.activateTexture(this._gl.TEXTURE0 + channel);
  11007. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11008. };
  11009. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11010. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  11011. };
  11012. Engine.prototype.unbindAllTextures = function () {
  11013. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  11014. this.activateTexture(this._gl["TEXTURE" + channel]);
  11015. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11016. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11017. }
  11018. };
  11019. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11020. if (channel < 0) {
  11021. return;
  11022. }
  11023. this._gl.uniform1i(uniform, channel);
  11024. this._setTexture(channel, texture);
  11025. };
  11026. Engine.prototype._setTexture = function (channel, texture) {
  11027. // Not ready?
  11028. if (!texture) {
  11029. if (this._activeTexturesCache[channel] != null) {
  11030. this.activateTexture(this._gl["TEXTURE" + channel]);
  11031. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11032. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11033. }
  11034. return;
  11035. }
  11036. // Video
  11037. var alreadyActivated = false;
  11038. if (texture.video) {
  11039. this.activateTexture(this._gl["TEXTURE" + channel]);
  11040. alreadyActivated = true;
  11041. texture.update();
  11042. }
  11043. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11044. texture.delayLoad();
  11045. return;
  11046. }
  11047. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  11048. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  11049. if (this._activeTexturesCache[channel] === internalTexture) {
  11050. return;
  11051. }
  11052. if (!alreadyActivated) {
  11053. this.activateTexture(this._gl["TEXTURE" + channel]);
  11054. }
  11055. if (internalTexture.isCube) {
  11056. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  11057. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  11058. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  11059. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  11060. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  11061. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  11062. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  11063. }
  11064. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  11065. }
  11066. else {
  11067. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  11068. if (internalTexture._cachedWrapU !== texture.wrapU) {
  11069. internalTexture._cachedWrapU = texture.wrapU;
  11070. switch (texture.wrapU) {
  11071. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11072. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11073. break;
  11074. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11075. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11076. break;
  11077. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11078. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11079. break;
  11080. }
  11081. }
  11082. if (internalTexture._cachedWrapV !== texture.wrapV) {
  11083. internalTexture._cachedWrapV = texture.wrapV;
  11084. switch (texture.wrapV) {
  11085. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11086. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11087. break;
  11088. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11089. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11090. break;
  11091. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11092. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11093. break;
  11094. }
  11095. }
  11096. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11097. }
  11098. };
  11099. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11100. if (channel < 0) {
  11101. return;
  11102. }
  11103. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11104. this._textureUnits = new Int32Array(textures.length);
  11105. }
  11106. for (var i = 0; i < textures.length; i++) {
  11107. this._textureUnits[i] = channel + i;
  11108. }
  11109. this._gl.uniform1iv(uniform, this._textureUnits);
  11110. for (var index = 0; index < textures.length; index++) {
  11111. this._setTexture(channel + index, textures[index]);
  11112. }
  11113. };
  11114. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11115. var internalTexture = texture.getInternalTexture();
  11116. if (!internalTexture) {
  11117. return;
  11118. }
  11119. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11120. var value = texture.anisotropicFilteringLevel;
  11121. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11122. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11123. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11124. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11125. }
  11126. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11127. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11128. internalTexture._cachedAnisotropicFilteringLevel = value;
  11129. }
  11130. };
  11131. Engine.prototype.readPixels = function (x, y, width, height) {
  11132. var data = new Uint8Array(height * width * 4);
  11133. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11134. return data;
  11135. };
  11136. /**
  11137. * Add an externaly attached data from its key.
  11138. * This method call will fail and return false, if such key already exists.
  11139. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11140. * @param key the unique key that identifies the data
  11141. * @param data the data object to associate to the key for this Engine instance
  11142. * @return true if no such key were already present and the data was added successfully, false otherwise
  11143. */
  11144. Engine.prototype.addExternalData = function (key, data) {
  11145. if (!this._externalData) {
  11146. this._externalData = new BABYLON.StringDictionary();
  11147. }
  11148. return this._externalData.add(key, data);
  11149. };
  11150. /**
  11151. * Get an externaly attached data from its key
  11152. * @param key the unique key that identifies the data
  11153. * @return the associated data, if present (can be null), or undefined if not present
  11154. */
  11155. Engine.prototype.getExternalData = function (key) {
  11156. if (!this._externalData) {
  11157. this._externalData = new BABYLON.StringDictionary();
  11158. }
  11159. return this._externalData.get(key);
  11160. };
  11161. /**
  11162. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11163. * @param key the unique key that identifies the data
  11164. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11165. * @return the associated data, can be null if the factory returned null.
  11166. */
  11167. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11168. if (!this._externalData) {
  11169. this._externalData = new BABYLON.StringDictionary();
  11170. }
  11171. return this._externalData.getOrAddWithFactory(key, factory);
  11172. };
  11173. /**
  11174. * Remove an externaly attached data from the Engine instance
  11175. * @param key the unique key that identifies the data
  11176. * @return true if the data was successfully removed, false if it doesn't exist
  11177. */
  11178. Engine.prototype.removeExternalData = function (key) {
  11179. if (!this._externalData) {
  11180. this._externalData = new BABYLON.StringDictionary();
  11181. }
  11182. return this._externalData.remove(key);
  11183. };
  11184. Engine.prototype.unbindAllAttributes = function () {
  11185. if (this._mustWipeVertexAttributes) {
  11186. this._mustWipeVertexAttributes = false;
  11187. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11188. this._gl.disableVertexAttribArray(i);
  11189. this._vertexAttribArraysEnabled[i] = false;
  11190. this._currentBufferPointers[i].active = false;
  11191. }
  11192. return;
  11193. }
  11194. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11195. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11196. continue;
  11197. }
  11198. this._gl.disableVertexAttribArray(i);
  11199. this._vertexAttribArraysEnabled[i] = false;
  11200. this._currentBufferPointers[i].active = false;
  11201. }
  11202. };
  11203. Engine.prototype.releaseEffects = function () {
  11204. for (var name in this._compiledEffects) {
  11205. this._gl.deleteProgram(this._compiledEffects[name]._program);
  11206. }
  11207. this._compiledEffects = {};
  11208. };
  11209. // Dispose
  11210. Engine.prototype.dispose = function () {
  11211. this.hideLoadingUI();
  11212. this.stopRenderLoop();
  11213. // Release postProcesses
  11214. while (this.postProcesses.length) {
  11215. this.postProcesses[0].dispose();
  11216. }
  11217. // Empty texture
  11218. if (this._emptyTexture) {
  11219. this._releaseTexture(this._emptyTexture);
  11220. this._emptyTexture = null;
  11221. }
  11222. if (this._emptyCubeTexture) {
  11223. this._releaseTexture(this._emptyCubeTexture);
  11224. this._emptyCubeTexture = null;
  11225. }
  11226. // Rescale PP
  11227. if (this._rescalePostProcess) {
  11228. this._rescalePostProcess.dispose();
  11229. }
  11230. // Release scenes
  11231. while (this.scenes.length) {
  11232. this.scenes[0].dispose();
  11233. }
  11234. // Release audio engine
  11235. if (Engine.audioEngine) {
  11236. Engine.audioEngine.dispose();
  11237. }
  11238. // Release effects
  11239. this.releaseEffects();
  11240. // Unbind
  11241. this.unbindAllAttributes();
  11242. if (this._dummyFramebuffer) {
  11243. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11244. }
  11245. this._gl = null;
  11246. //WebVR
  11247. this.disableVR();
  11248. // Events
  11249. window.removeEventListener("blur", this._onBlur);
  11250. window.removeEventListener("focus", this._onFocus);
  11251. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11252. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11253. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11254. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11255. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11256. if (!this._doNotHandleContextLost) {
  11257. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11258. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11259. }
  11260. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11261. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11262. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11263. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11264. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11265. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11266. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11267. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11268. if (this._onVrDisplayConnect) {
  11269. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11270. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11271. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11272. this._onVrDisplayConnect = undefined;
  11273. this._onVrDisplayDisconnect = undefined;
  11274. }
  11275. // Remove from Instances
  11276. var index = Engine.Instances.indexOf(this);
  11277. if (index >= 0) {
  11278. Engine.Instances.splice(index, 1);
  11279. }
  11280. this._workingCanvas = null;
  11281. this._workingContext = null;
  11282. this._currentBufferPointers = null;
  11283. this._renderingCanvas = null;
  11284. this._currentProgram = null;
  11285. this.onResizeObservable.clear();
  11286. this.onCanvasBlurObservable.clear();
  11287. this.onCanvasFocusObservable.clear();
  11288. this.onCanvasPointerOutObservable.clear();
  11289. BABYLON.Effect.ResetCache();
  11290. };
  11291. // Loading screen
  11292. Engine.prototype.displayLoadingUI = function () {
  11293. var loadingScreen = this.loadingScreen;
  11294. if (loadingScreen) {
  11295. loadingScreen.displayLoadingUI();
  11296. }
  11297. };
  11298. Engine.prototype.hideLoadingUI = function () {
  11299. var loadingScreen = this.loadingScreen;
  11300. if (loadingScreen) {
  11301. loadingScreen.hideLoadingUI();
  11302. }
  11303. };
  11304. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11305. get: function () {
  11306. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  11307. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11308. return this._loadingScreen;
  11309. },
  11310. set: function (loadingScreen) {
  11311. this._loadingScreen = loadingScreen;
  11312. },
  11313. enumerable: true,
  11314. configurable: true
  11315. });
  11316. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11317. set: function (text) {
  11318. this.loadingScreen.loadingUIText = text;
  11319. },
  11320. enumerable: true,
  11321. configurable: true
  11322. });
  11323. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11324. set: function (color) {
  11325. this.loadingScreen.loadingUIBackgroundColor = color;
  11326. },
  11327. enumerable: true,
  11328. configurable: true
  11329. });
  11330. Engine.prototype.attachContextLostEvent = function (callback) {
  11331. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11332. };
  11333. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11334. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11335. };
  11336. Engine.prototype.getVertexShaderSource = function (program) {
  11337. var shaders = this._gl.getAttachedShaders(program);
  11338. return this._gl.getShaderSource(shaders[0]);
  11339. };
  11340. Engine.prototype.getFragmentShaderSource = function (program) {
  11341. var shaders = this._gl.getAttachedShaders(program);
  11342. return this._gl.getShaderSource(shaders[1]);
  11343. };
  11344. Engine.prototype.getError = function () {
  11345. return this._gl.getError();
  11346. };
  11347. // FPS
  11348. Engine.prototype.getFps = function () {
  11349. return this._fps;
  11350. };
  11351. Engine.prototype.getDeltaTime = function () {
  11352. return this._deltaTime;
  11353. };
  11354. Engine.prototype._measureFps = function () {
  11355. this._performanceMonitor.sampleFrame();
  11356. this._fps = this._performanceMonitor.averageFPS;
  11357. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11358. };
  11359. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11360. if (faceIndex === void 0) { faceIndex = -1; }
  11361. var gl = this._gl;
  11362. if (!this._dummyFramebuffer) {
  11363. this._dummyFramebuffer = gl.createFramebuffer();
  11364. }
  11365. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11366. if (faceIndex > -1) {
  11367. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11368. }
  11369. else {
  11370. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11371. }
  11372. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11373. var buffer;
  11374. switch (readType) {
  11375. case gl.UNSIGNED_BYTE:
  11376. buffer = new Uint8Array(4 * width * height);
  11377. readType = gl.UNSIGNED_BYTE;
  11378. break;
  11379. default:
  11380. buffer = new Float32Array(4 * width * height);
  11381. readType = gl.FLOAT;
  11382. break;
  11383. }
  11384. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11385. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11386. return buffer;
  11387. };
  11388. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11389. if (this._webGLVersion > 1) {
  11390. return this._caps.colorBufferFloat;
  11391. }
  11392. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11393. };
  11394. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11395. if (this._webGLVersion > 1) {
  11396. return this._caps.colorBufferFloat;
  11397. }
  11398. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11399. };
  11400. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11401. Engine.prototype._canRenderToFramebuffer = function (type) {
  11402. var gl = this._gl;
  11403. //clear existing errors
  11404. while (gl.getError() !== gl.NO_ERROR) { }
  11405. var successful = true;
  11406. var texture = gl.createTexture();
  11407. gl.bindTexture(gl.TEXTURE_2D, texture);
  11408. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11409. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11410. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11411. var fb = gl.createFramebuffer();
  11412. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11413. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11414. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11415. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11416. successful = successful && (gl.getError() === gl.NO_ERROR);
  11417. //try render by clearing frame buffer's color buffer
  11418. if (successful) {
  11419. gl.clear(gl.COLOR_BUFFER_BIT);
  11420. successful = successful && (gl.getError() === gl.NO_ERROR);
  11421. }
  11422. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11423. if (successful) {
  11424. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11425. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11426. var readFormat = gl.RGBA;
  11427. var readType = gl.UNSIGNED_BYTE;
  11428. var buffer = new Uint8Array(4);
  11429. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11430. successful = successful && (gl.getError() === gl.NO_ERROR);
  11431. }
  11432. //clean up
  11433. gl.deleteTexture(texture);
  11434. gl.deleteFramebuffer(fb);
  11435. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11436. //clear accumulated errors
  11437. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11438. return successful;
  11439. };
  11440. Engine.prototype._getWebGLTextureType = function (type) {
  11441. if (type === Engine.TEXTURETYPE_FLOAT) {
  11442. return this._gl.FLOAT;
  11443. }
  11444. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11445. // Add Half Float Constant.
  11446. return this._gl.HALF_FLOAT_OES;
  11447. }
  11448. return this._gl.UNSIGNED_BYTE;
  11449. };
  11450. ;
  11451. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11452. if (this._webGLVersion === 1) {
  11453. return this._gl.RGBA;
  11454. }
  11455. if (type === Engine.TEXTURETYPE_FLOAT) {
  11456. return this._gl.RGBA32F;
  11457. }
  11458. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11459. return this._gl.RGBA16F;
  11460. }
  11461. return this._gl.RGBA;
  11462. };
  11463. ;
  11464. Engine.prototype.createQuery = function () {
  11465. return this._gl.createQuery();
  11466. };
  11467. Engine.prototype.deleteQuery = function (query) {
  11468. this._gl.deleteQuery(query);
  11469. return this;
  11470. };
  11471. Engine.prototype.isQueryResultAvailable = function (query) {
  11472. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11473. };
  11474. Engine.prototype.getQueryResult = function (query) {
  11475. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11476. };
  11477. Engine.prototype.beginQuery = function (algorithmType, query) {
  11478. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11479. this._gl.beginQuery(glAlgorithm, query);
  11480. };
  11481. Engine.prototype.endQuery = function (algorithmType) {
  11482. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11483. this._gl.endQuery(glAlgorithm);
  11484. return this;
  11485. };
  11486. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  11487. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  11488. };
  11489. // Statics
  11490. Engine.isSupported = function () {
  11491. try {
  11492. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  11493. if (navigator.isCocoonJS) {
  11494. return true;
  11495. }
  11496. var tempcanvas = document.createElement("canvas");
  11497. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  11498. return gl != null && !!window.WebGLRenderingContext;
  11499. }
  11500. catch (e) {
  11501. return false;
  11502. }
  11503. };
  11504. Engine.Instances = new Array();
  11505. // Const statics
  11506. Engine._ALPHA_DISABLE = 0;
  11507. Engine._ALPHA_ADD = 1;
  11508. Engine._ALPHA_COMBINE = 2;
  11509. Engine._ALPHA_SUBTRACT = 3;
  11510. Engine._ALPHA_MULTIPLY = 4;
  11511. Engine._ALPHA_MAXIMIZED = 5;
  11512. Engine._ALPHA_ONEONE = 6;
  11513. Engine._ALPHA_PREMULTIPLIED = 7;
  11514. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  11515. Engine._ALPHA_INTERPOLATE = 9;
  11516. Engine._ALPHA_SCREENMODE = 10;
  11517. Engine._DELAYLOADSTATE_NONE = 0;
  11518. Engine._DELAYLOADSTATE_LOADED = 1;
  11519. Engine._DELAYLOADSTATE_LOADING = 2;
  11520. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  11521. Engine._TEXTUREFORMAT_ALPHA = 0;
  11522. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  11523. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  11524. Engine._TEXTUREFORMAT_RGB = 4;
  11525. Engine._TEXTUREFORMAT_RGBA = 5;
  11526. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  11527. Engine._TEXTURETYPE_FLOAT = 1;
  11528. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  11529. // Depht or Stencil test Constants.
  11530. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  11531. 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.
  11532. 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.
  11533. 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.
  11534. 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.
  11535. 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.
  11536. 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.
  11537. 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.
  11538. // Stencil Actions Constants.
  11539. Engine._KEEP = 0x1E00;
  11540. Engine._REPLACE = 0x1E01;
  11541. Engine._INCR = 0x1E02;
  11542. Engine._DECR = 0x1E03;
  11543. Engine._INVERT = 0x150A;
  11544. Engine._INCR_WRAP = 0x8507;
  11545. Engine._DECR_WRAP = 0x8508;
  11546. // Texture rescaling mode
  11547. Engine._SCALEMODE_FLOOR = 1;
  11548. Engine._SCALEMODE_NEAREST = 2;
  11549. Engine._SCALEMODE_CEILING = 3;
  11550. // Updatable statics so stick with vars here
  11551. Engine.CollisionsEpsilon = 0.001;
  11552. Engine.CodeRepository = "src/";
  11553. Engine.ShadersRepository = "src/Shaders/";
  11554. return Engine;
  11555. }());
  11556. BABYLON.Engine = Engine;
  11557. })(BABYLON || (BABYLON = {}));
  11558. //# sourceMappingURL=babylon.engine.js.map
  11559. /// <reference path="Tools\babylon.decorators.ts" />
  11560. var BABYLON;
  11561. (function (BABYLON) {
  11562. /**
  11563. * Node is the basic class for all scene objects (Mesh, Light Camera).
  11564. */
  11565. var Node = (function () {
  11566. /**
  11567. * @constructor
  11568. * @param {string} name - the name and id to be given to this node
  11569. * @param {BABYLON.Scene} the scene this node will be added to
  11570. */
  11571. function Node(name, scene) {
  11572. this.state = "";
  11573. this.metadata = null;
  11574. this.doNotSerialize = false;
  11575. this.animations = new Array();
  11576. this._ranges = {};
  11577. this._childrenFlag = -1;
  11578. this._isEnabled = true;
  11579. this._isReady = true;
  11580. this._currentRenderId = -1;
  11581. this._parentRenderId = -1;
  11582. /**
  11583. * An event triggered when the mesh is disposed.
  11584. * @type {BABYLON.Observable}
  11585. */
  11586. this.onDisposeObservable = new BABYLON.Observable();
  11587. // Behaviors
  11588. this._behaviors = new Array();
  11589. this.name = name;
  11590. this.id = name;
  11591. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  11592. this.uniqueId = this._scene.getUniqueId();
  11593. this._initCache();
  11594. }
  11595. Object.defineProperty(Node.prototype, "parent", {
  11596. get: function () {
  11597. return this._parentNode;
  11598. },
  11599. set: function (parent) {
  11600. if (this._parentNode === parent) {
  11601. return;
  11602. }
  11603. if (this._parentNode) {
  11604. var index = this._parentNode._children.indexOf(this);
  11605. if (index !== -1) {
  11606. this._parentNode._children.splice(index, 1);
  11607. }
  11608. }
  11609. this._parentNode = parent;
  11610. if (this._parentNode) {
  11611. if (!this._parentNode._children) {
  11612. this._parentNode._children = new Array();
  11613. }
  11614. this._parentNode._children.push(this);
  11615. }
  11616. },
  11617. enumerable: true,
  11618. configurable: true
  11619. });
  11620. Node.prototype.getClassName = function () {
  11621. return "Node";
  11622. };
  11623. Object.defineProperty(Node.prototype, "onDispose", {
  11624. set: function (callback) {
  11625. if (this._onDisposeObserver) {
  11626. this.onDisposeObservable.remove(this._onDisposeObserver);
  11627. }
  11628. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  11629. },
  11630. enumerable: true,
  11631. configurable: true
  11632. });
  11633. Node.prototype.getScene = function () {
  11634. return this._scene;
  11635. };
  11636. Node.prototype.getEngine = function () {
  11637. return this._scene.getEngine();
  11638. };
  11639. Node.prototype.addBehavior = function (behavior) {
  11640. var index = this._behaviors.indexOf(behavior);
  11641. if (index !== -1) {
  11642. return;
  11643. }
  11644. behavior.attach(this);
  11645. this._behaviors.push(behavior);
  11646. return this;
  11647. };
  11648. Node.prototype.removeBehavior = function (behavior) {
  11649. var index = this._behaviors.indexOf(behavior);
  11650. if (index === -1) {
  11651. return;
  11652. }
  11653. this._behaviors[index].detach();
  11654. this._behaviors.splice(index, 1);
  11655. return this;
  11656. };
  11657. Object.defineProperty(Node.prototype, "behaviors", {
  11658. get: function () {
  11659. return this._behaviors;
  11660. },
  11661. enumerable: true,
  11662. configurable: true
  11663. });
  11664. Node.prototype.getBehaviorByName = function (name) {
  11665. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11666. var behavior = _a[_i];
  11667. if (behavior.name === name) {
  11668. return behavior;
  11669. }
  11670. }
  11671. return null;
  11672. };
  11673. // override it in derived class
  11674. Node.prototype.getWorldMatrix = function () {
  11675. return BABYLON.Matrix.Identity();
  11676. };
  11677. // override it in derived class if you add new variables to the cache
  11678. // and call the parent class method
  11679. Node.prototype._initCache = function () {
  11680. this._cache = {};
  11681. this._cache.parent = undefined;
  11682. };
  11683. Node.prototype.updateCache = function (force) {
  11684. if (!force && this.isSynchronized())
  11685. return;
  11686. this._cache.parent = this.parent;
  11687. this._updateCache();
  11688. };
  11689. // override it in derived class if you add new variables to the cache
  11690. // and call the parent class method if !ignoreParentClass
  11691. Node.prototype._updateCache = function (ignoreParentClass) {
  11692. };
  11693. // override it in derived class if you add new variables to the cache
  11694. Node.prototype._isSynchronized = function () {
  11695. return true;
  11696. };
  11697. Node.prototype._markSyncedWithParent = function () {
  11698. this._parentRenderId = this.parent._currentRenderId;
  11699. };
  11700. Node.prototype.isSynchronizedWithParent = function () {
  11701. if (!this.parent) {
  11702. return true;
  11703. }
  11704. if (this._parentRenderId !== this.parent._currentRenderId) {
  11705. return false;
  11706. }
  11707. return this.parent.isSynchronized();
  11708. };
  11709. Node.prototype.isSynchronized = function (updateCache) {
  11710. var check = this.hasNewParent();
  11711. check = check || !this.isSynchronizedWithParent();
  11712. check = check || !this._isSynchronized();
  11713. if (updateCache)
  11714. this.updateCache(true);
  11715. return !check;
  11716. };
  11717. Node.prototype.hasNewParent = function (update) {
  11718. if (this._cache.parent === this.parent)
  11719. return false;
  11720. if (update)
  11721. this._cache.parent = this.parent;
  11722. return true;
  11723. };
  11724. /**
  11725. * Is this node ready to be used/rendered
  11726. * @return {boolean} is it ready
  11727. */
  11728. Node.prototype.isReady = function () {
  11729. return this._isReady;
  11730. };
  11731. /**
  11732. * Is this node enabled.
  11733. * If the node has a parent and is enabled, the parent will be inspected as well.
  11734. * @return {boolean} whether this node (and its parent) is enabled.
  11735. * @see setEnabled
  11736. */
  11737. Node.prototype.isEnabled = function () {
  11738. if (!this._isEnabled) {
  11739. return false;
  11740. }
  11741. if (this.parent) {
  11742. return this.parent.isEnabled();
  11743. }
  11744. return true;
  11745. };
  11746. /**
  11747. * Set the enabled state of this node.
  11748. * @param {boolean} value - the new enabled state
  11749. * @see isEnabled
  11750. */
  11751. Node.prototype.setEnabled = function (value) {
  11752. this._isEnabled = value;
  11753. };
  11754. /**
  11755. * Is this node a descendant of the given node.
  11756. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  11757. * @param {BABYLON.Node} ancestor - The parent node to inspect
  11758. * @see parent
  11759. */
  11760. Node.prototype.isDescendantOf = function (ancestor) {
  11761. if (this.parent) {
  11762. if (this.parent === ancestor) {
  11763. return true;
  11764. }
  11765. return this.parent.isDescendantOf(ancestor);
  11766. }
  11767. return false;
  11768. };
  11769. /**
  11770. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  11771. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  11772. * @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.
  11773. * @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.
  11774. */
  11775. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  11776. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  11777. if (!this._children) {
  11778. return;
  11779. }
  11780. for (var index = 0; index < this._children.length; index++) {
  11781. var item = this._children[index];
  11782. if (!predicate || predicate(item)) {
  11783. results.push(item);
  11784. }
  11785. if (!directDescendantsOnly) {
  11786. item._getDescendants(results, false, predicate);
  11787. }
  11788. }
  11789. };
  11790. /**
  11791. * Will return all nodes that have this node as ascendant.
  11792. * @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.
  11793. * @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.
  11794. * @return {BABYLON.Node[]} all children nodes of all types.
  11795. */
  11796. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  11797. var results = new Array();
  11798. this._getDescendants(results, directDescendantsOnly, predicate);
  11799. return results;
  11800. };
  11801. /**
  11802. * Get all child-meshes of this node.
  11803. */
  11804. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  11805. var results = [];
  11806. this._getDescendants(results, directDecendantsOnly, function (node) {
  11807. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  11808. });
  11809. return results;
  11810. };
  11811. /**
  11812. * Get all direct children of this node.
  11813. */
  11814. Node.prototype.getChildren = function (predicate) {
  11815. return this.getDescendants(true, predicate);
  11816. };
  11817. Node.prototype._setReady = function (state) {
  11818. if (state === this._isReady) {
  11819. return;
  11820. }
  11821. if (!state) {
  11822. this._isReady = false;
  11823. return;
  11824. }
  11825. this._isReady = true;
  11826. if (this.onReady) {
  11827. this.onReady(this);
  11828. }
  11829. };
  11830. Node.prototype.getAnimationByName = function (name) {
  11831. for (var i = 0; i < this.animations.length; i++) {
  11832. var animation = this.animations[i];
  11833. if (animation.name === name) {
  11834. return animation;
  11835. }
  11836. }
  11837. return null;
  11838. };
  11839. Node.prototype.createAnimationRange = function (name, from, to) {
  11840. // check name not already in use
  11841. if (!this._ranges[name]) {
  11842. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11843. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11844. if (this.animations[i]) {
  11845. this.animations[i].createRange(name, from, to);
  11846. }
  11847. }
  11848. }
  11849. };
  11850. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11851. if (deleteFrames === void 0) { deleteFrames = true; }
  11852. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11853. if (this.animations[i]) {
  11854. this.animations[i].deleteRange(name, deleteFrames);
  11855. }
  11856. }
  11857. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11858. };
  11859. Node.prototype.getAnimationRange = function (name) {
  11860. return this._ranges[name];
  11861. };
  11862. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11863. var range = this.getAnimationRange(name);
  11864. if (!range) {
  11865. return null;
  11866. }
  11867. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11868. };
  11869. Node.prototype.serializeAnimationRanges = function () {
  11870. var serializationRanges = [];
  11871. for (var name in this._ranges) {
  11872. var range = {};
  11873. range.name = name;
  11874. range.from = this._ranges[name].from;
  11875. range.to = this._ranges[name].to;
  11876. serializationRanges.push(range);
  11877. }
  11878. return serializationRanges;
  11879. };
  11880. Node.prototype.dispose = function () {
  11881. this.parent = null;
  11882. // Callback
  11883. this.onDisposeObservable.notifyObservers(this);
  11884. this.onDisposeObservable.clear();
  11885. // Behaviors
  11886. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11887. var behavior = _a[_i];
  11888. behavior.detach();
  11889. }
  11890. this._behaviors = [];
  11891. };
  11892. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11893. if (parsedNode.ranges) {
  11894. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11895. var data = parsedNode.ranges[index];
  11896. node.createAnimationRange(data.name, data.from, data.to);
  11897. }
  11898. }
  11899. };
  11900. __decorate([
  11901. BABYLON.serialize()
  11902. ], Node.prototype, "name", void 0);
  11903. __decorate([
  11904. BABYLON.serialize()
  11905. ], Node.prototype, "id", void 0);
  11906. __decorate([
  11907. BABYLON.serialize()
  11908. ], Node.prototype, "uniqueId", void 0);
  11909. __decorate([
  11910. BABYLON.serialize()
  11911. ], Node.prototype, "state", void 0);
  11912. __decorate([
  11913. BABYLON.serialize()
  11914. ], Node.prototype, "metadata", void 0);
  11915. return Node;
  11916. }());
  11917. BABYLON.Node = Node;
  11918. })(BABYLON || (BABYLON = {}));
  11919. //# sourceMappingURL=babylon.node.js.map
  11920. var BABYLON;
  11921. (function (BABYLON) {
  11922. var BoundingSphere = (function () {
  11923. function BoundingSphere(minimum, maximum) {
  11924. this.minimum = minimum;
  11925. this.maximum = maximum;
  11926. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11927. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11928. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11929. this.radius = distance * 0.5;
  11930. this.centerWorld = BABYLON.Vector3.Zero();
  11931. this._update(BABYLON.Matrix.Identity());
  11932. }
  11933. // Methods
  11934. BoundingSphere.prototype._update = function (world) {
  11935. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11936. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11937. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11938. };
  11939. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11940. for (var i = 0; i < 6; i++) {
  11941. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11942. return false;
  11943. }
  11944. return true;
  11945. };
  11946. BoundingSphere.prototype.intersectsPoint = function (point) {
  11947. var x = this.centerWorld.x - point.x;
  11948. var y = this.centerWorld.y - point.y;
  11949. var z = this.centerWorld.z - point.z;
  11950. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11951. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11952. return false;
  11953. return true;
  11954. };
  11955. // Statics
  11956. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11957. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11958. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11959. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11960. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11961. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11962. return false;
  11963. return true;
  11964. };
  11965. return BoundingSphere;
  11966. }());
  11967. BABYLON.BoundingSphere = BoundingSphere;
  11968. })(BABYLON || (BABYLON = {}));
  11969. //# sourceMappingURL=babylon.boundingSphere.js.map
  11970. var BABYLON;
  11971. (function (BABYLON) {
  11972. var BoundingBox = (function () {
  11973. function BoundingBox(minimum, maximum) {
  11974. this.minimum = minimum;
  11975. this.maximum = maximum;
  11976. this.vectors = new Array();
  11977. this.vectorsWorld = new Array();
  11978. // Bounding vectors
  11979. this.vectors.push(this.minimum.clone());
  11980. this.vectors.push(this.maximum.clone());
  11981. this.vectors.push(this.minimum.clone());
  11982. this.vectors[2].x = this.maximum.x;
  11983. this.vectors.push(this.minimum.clone());
  11984. this.vectors[3].y = this.maximum.y;
  11985. this.vectors.push(this.minimum.clone());
  11986. this.vectors[4].z = this.maximum.z;
  11987. this.vectors.push(this.maximum.clone());
  11988. this.vectors[5].z = this.minimum.z;
  11989. this.vectors.push(this.maximum.clone());
  11990. this.vectors[6].x = this.minimum.x;
  11991. this.vectors.push(this.maximum.clone());
  11992. this.vectors[7].y = this.minimum.y;
  11993. // OBB
  11994. this.center = this.maximum.add(this.minimum).scale(0.5);
  11995. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11996. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11997. // World
  11998. for (var index = 0; index < this.vectors.length; index++) {
  11999. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  12000. }
  12001. this.minimumWorld = BABYLON.Vector3.Zero();
  12002. this.maximumWorld = BABYLON.Vector3.Zero();
  12003. this.centerWorld = BABYLON.Vector3.Zero();
  12004. this.extendSizeWorld = BABYLON.Vector3.Zero();
  12005. this._update(BABYLON.Matrix.Identity());
  12006. }
  12007. // Methods
  12008. BoundingBox.prototype.getWorldMatrix = function () {
  12009. return this._worldMatrix;
  12010. };
  12011. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  12012. this._worldMatrix.copyFrom(matrix);
  12013. return this;
  12014. };
  12015. BoundingBox.prototype._update = function (world) {
  12016. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  12017. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  12018. for (var index = 0; index < this.vectors.length; index++) {
  12019. var v = this.vectorsWorld[index];
  12020. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  12021. if (v.x < this.minimumWorld.x)
  12022. this.minimumWorld.x = v.x;
  12023. if (v.y < this.minimumWorld.y)
  12024. this.minimumWorld.y = v.y;
  12025. if (v.z < this.minimumWorld.z)
  12026. this.minimumWorld.z = v.z;
  12027. if (v.x > this.maximumWorld.x)
  12028. this.maximumWorld.x = v.x;
  12029. if (v.y > this.maximumWorld.y)
  12030. this.maximumWorld.y = v.y;
  12031. if (v.z > this.maximumWorld.z)
  12032. this.maximumWorld.z = v.z;
  12033. }
  12034. // Extend
  12035. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  12036. this.extendSizeWorld.scaleInPlace(0.5);
  12037. // OBB
  12038. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  12039. this.centerWorld.scaleInPlace(0.5);
  12040. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  12041. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  12042. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  12043. this._worldMatrix = world;
  12044. };
  12045. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  12046. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  12047. };
  12048. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12049. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  12050. };
  12051. BoundingBox.prototype.intersectsPoint = function (point) {
  12052. var delta = -BABYLON.Epsilon;
  12053. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  12054. return false;
  12055. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  12056. return false;
  12057. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  12058. return false;
  12059. return true;
  12060. };
  12061. BoundingBox.prototype.intersectsSphere = function (sphere) {
  12062. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  12063. };
  12064. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  12065. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  12066. return false;
  12067. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  12068. return false;
  12069. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  12070. return false;
  12071. return true;
  12072. };
  12073. // Statics
  12074. BoundingBox.Intersects = function (box0, box1) {
  12075. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  12076. return false;
  12077. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  12078. return false;
  12079. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  12080. return false;
  12081. return true;
  12082. };
  12083. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  12084. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  12085. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  12086. return (num <= (sphereRadius * sphereRadius));
  12087. };
  12088. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  12089. for (var p = 0; p < 6; p++) {
  12090. for (var i = 0; i < 8; i++) {
  12091. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12092. return false;
  12093. }
  12094. }
  12095. }
  12096. return true;
  12097. };
  12098. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  12099. for (var p = 0; p < 6; p++) {
  12100. var inCount = 8;
  12101. for (var i = 0; i < 8; i++) {
  12102. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12103. --inCount;
  12104. }
  12105. else {
  12106. break;
  12107. }
  12108. }
  12109. if (inCount === 0)
  12110. return false;
  12111. }
  12112. return true;
  12113. };
  12114. return BoundingBox;
  12115. }());
  12116. BABYLON.BoundingBox = BoundingBox;
  12117. })(BABYLON || (BABYLON = {}));
  12118. //# sourceMappingURL=babylon.boundingBox.js.map
  12119. var BABYLON;
  12120. (function (BABYLON) {
  12121. var computeBoxExtents = function (axis, box) {
  12122. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  12123. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  12124. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  12125. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  12126. var r = r0 + r1 + r2;
  12127. return {
  12128. min: p - r,
  12129. max: p + r
  12130. };
  12131. };
  12132. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  12133. var axisOverlap = function (axis, box0, box1) {
  12134. var result0 = computeBoxExtents(axis, box0);
  12135. var result1 = computeBoxExtents(axis, box1);
  12136. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  12137. };
  12138. var BoundingInfo = (function () {
  12139. function BoundingInfo(minimum, maximum) {
  12140. this.minimum = minimum;
  12141. this.maximum = maximum;
  12142. this._isLocked = false;
  12143. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  12144. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  12145. }
  12146. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  12147. get: function () {
  12148. return this._isLocked;
  12149. },
  12150. set: function (value) {
  12151. this._isLocked = value;
  12152. },
  12153. enumerable: true,
  12154. configurable: true
  12155. });
  12156. // Methods
  12157. BoundingInfo.prototype.update = function (world) {
  12158. if (this._isLocked) {
  12159. return;
  12160. }
  12161. this.boundingBox._update(world);
  12162. this.boundingSphere._update(world);
  12163. };
  12164. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12165. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12166. return false;
  12167. return this.boundingBox.isInFrustum(frustumPlanes);
  12168. };
  12169. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12170. /**
  12171. * Gets the world distance between the min and max points of the bounding box
  12172. */
  12173. get: function () {
  12174. var boundingBox = this.boundingBox;
  12175. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12176. return size.length();
  12177. },
  12178. enumerable: true,
  12179. configurable: true
  12180. });
  12181. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12182. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12183. };
  12184. BoundingInfo.prototype._checkCollision = function (collider) {
  12185. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12186. };
  12187. BoundingInfo.prototype.intersectsPoint = function (point) {
  12188. if (!this.boundingSphere.centerWorld) {
  12189. return false;
  12190. }
  12191. if (!this.boundingSphere.intersectsPoint(point)) {
  12192. return false;
  12193. }
  12194. if (!this.boundingBox.intersectsPoint(point)) {
  12195. return false;
  12196. }
  12197. return true;
  12198. };
  12199. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12200. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12201. return false;
  12202. }
  12203. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12204. return false;
  12205. }
  12206. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12207. return false;
  12208. }
  12209. if (!precise) {
  12210. return true;
  12211. }
  12212. var box0 = this.boundingBox;
  12213. var box1 = boundingInfo.boundingBox;
  12214. if (!axisOverlap(box0.directions[0], box0, box1))
  12215. return false;
  12216. if (!axisOverlap(box0.directions[1], box0, box1))
  12217. return false;
  12218. if (!axisOverlap(box0.directions[2], box0, box1))
  12219. return false;
  12220. if (!axisOverlap(box1.directions[0], box0, box1))
  12221. return false;
  12222. if (!axisOverlap(box1.directions[1], box0, box1))
  12223. return false;
  12224. if (!axisOverlap(box1.directions[2], box0, box1))
  12225. return false;
  12226. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12227. return false;
  12228. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12229. return false;
  12230. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12231. return false;
  12232. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12233. return false;
  12234. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12235. return false;
  12236. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12237. return false;
  12238. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12239. return false;
  12240. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12241. return false;
  12242. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12243. return false;
  12244. return true;
  12245. };
  12246. return BoundingInfo;
  12247. }());
  12248. BABYLON.BoundingInfo = BoundingInfo;
  12249. })(BABYLON || (BABYLON = {}));
  12250. //# sourceMappingURL=babylon.boundingInfo.js.map
  12251. var BABYLON;
  12252. (function (BABYLON) {
  12253. var AbstractMesh = (function (_super) {
  12254. __extends(AbstractMesh, _super);
  12255. // Constructor
  12256. function AbstractMesh(name, scene) {
  12257. var _this = _super.call(this, name, scene) || this;
  12258. _this._facetNb = 0; // facet number
  12259. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12260. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12261. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12262. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12263. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12264. _this._subDiv = {
  12265. max: 1,
  12266. X: 1,
  12267. Y: 1,
  12268. Z: 1
  12269. };
  12270. // Events
  12271. /**
  12272. * An event triggered when this mesh collides with another one
  12273. * @type {BABYLON.Observable}
  12274. */
  12275. _this.onCollideObservable = new BABYLON.Observable();
  12276. /**
  12277. * An event triggered when the collision's position changes
  12278. * @type {BABYLON.Observable}
  12279. */
  12280. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12281. /**
  12282. * An event triggered after the world matrix is updated
  12283. * @type {BABYLON.Observable}
  12284. */
  12285. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12286. /**
  12287. * An event triggered when material is changed
  12288. * @type {BABYLON.Observable}
  12289. */
  12290. _this.onMaterialChangedObservable = new BABYLON.Observable();
  12291. // Properties
  12292. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12293. _this.position = BABYLON.Vector3.Zero();
  12294. /**
  12295. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  12296. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  12297. * or
  12298. * 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.
  12299. * for more info check WebGl documentations
  12300. */
  12301. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  12302. /**
  12303. * 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:
  12304. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  12305. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  12306. * 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.
  12307. */
  12308. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  12309. /**
  12310. * 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.
  12311. * The default value is -1 which means don't break the query and wait till the result.
  12312. */
  12313. _this.occlusionRetryCount = -1;
  12314. _this._occlusionInternalRetryCounter = 0;
  12315. _this._isOccluded = false;
  12316. _this._isOcclusionQueryInProgress = false;
  12317. _this._rotation = BABYLON.Vector3.Zero();
  12318. _this._scaling = BABYLON.Vector3.One();
  12319. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12320. _this.visibility = 1.0;
  12321. _this.alphaIndex = Number.MAX_VALUE;
  12322. _this.infiniteDistance = false;
  12323. _this.isVisible = true;
  12324. _this.isPickable = true;
  12325. _this.showBoundingBox = false;
  12326. _this.showSubMeshesBoundingBox = false;
  12327. _this.isBlocker = false;
  12328. _this.enablePointerMoveEvents = false;
  12329. _this.renderingGroupId = 0;
  12330. _this._receiveShadows = false;
  12331. _this.renderOutline = false;
  12332. _this.outlineColor = BABYLON.Color3.Red();
  12333. _this.outlineWidth = 0.02;
  12334. _this.renderOverlay = false;
  12335. _this.overlayColor = BABYLON.Color3.Red();
  12336. _this.overlayAlpha = 0.5;
  12337. _this._hasVertexAlpha = false;
  12338. _this._useVertexColors = true;
  12339. _this._computeBonesUsingShaders = true;
  12340. _this._numBoneInfluencers = 4;
  12341. _this._applyFog = true;
  12342. _this.scalingDeterminant = 1;
  12343. _this.useOctreeForRenderingSelection = true;
  12344. _this.useOctreeForPicking = true;
  12345. _this.useOctreeForCollisions = true;
  12346. _this._layerMask = 0x0FFFFFFF;
  12347. /**
  12348. * True if the mesh must be rendered in any case.
  12349. */
  12350. _this.alwaysSelectAsActiveMesh = false;
  12351. // Collisions
  12352. _this._checkCollisions = false;
  12353. _this._collisionMask = -1;
  12354. _this._collisionGroup = -1;
  12355. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12356. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12357. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12358. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12359. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12360. // Edges
  12361. _this.edgesWidth = 1;
  12362. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12363. // Cache
  12364. _this._localWorld = BABYLON.Matrix.Zero();
  12365. _this._worldMatrix = BABYLON.Matrix.Zero();
  12366. _this._absolutePosition = BABYLON.Vector3.Zero();
  12367. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12368. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12369. _this._isDirty = false;
  12370. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12371. _this._postMultiplyPivotMatrix = false;
  12372. _this._isDisposed = false;
  12373. _this._renderId = 0;
  12374. _this._intersectionsInProgress = new Array();
  12375. _this._isWorldMatrixFrozen = false;
  12376. _this._unIndexed = false;
  12377. _this._lightSources = new Array();
  12378. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12379. if (collidedMesh === void 0) { collidedMesh = null; }
  12380. //TODO move this to the collision coordinator!
  12381. if (_this.getScene().workerCollisions)
  12382. newPosition.multiplyInPlace(_this._collider.radius);
  12383. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12384. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12385. _this.position.addInPlace(_this._diffPositionForCollisions);
  12386. }
  12387. if (collidedMesh) {
  12388. _this.onCollideObservable.notifyObservers(collidedMesh);
  12389. }
  12390. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12391. };
  12392. _this.getScene().addMesh(_this);
  12393. _this._resyncLightSources();
  12394. return _this;
  12395. }
  12396. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12397. get: function () {
  12398. return AbstractMesh._BILLBOARDMODE_NONE;
  12399. },
  12400. enumerable: true,
  12401. configurable: true
  12402. });
  12403. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12404. get: function () {
  12405. return AbstractMesh._BILLBOARDMODE_X;
  12406. },
  12407. enumerable: true,
  12408. configurable: true
  12409. });
  12410. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12411. get: function () {
  12412. return AbstractMesh._BILLBOARDMODE_Y;
  12413. },
  12414. enumerable: true,
  12415. configurable: true
  12416. });
  12417. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12418. get: function () {
  12419. return AbstractMesh._BILLBOARDMODE_Z;
  12420. },
  12421. enumerable: true,
  12422. configurable: true
  12423. });
  12424. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12425. get: function () {
  12426. return AbstractMesh._BILLBOARDMODE_ALL;
  12427. },
  12428. enumerable: true,
  12429. configurable: true
  12430. });
  12431. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12432. /**
  12433. * Read-only : the number of facets in the mesh
  12434. */
  12435. get: function () {
  12436. return this._facetNb;
  12437. },
  12438. enumerable: true,
  12439. configurable: true
  12440. });
  12441. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12442. /**
  12443. * The number (integer) of subdivisions per axis in the partioning space
  12444. */
  12445. get: function () {
  12446. return this._partitioningSubdivisions;
  12447. },
  12448. set: function (nb) {
  12449. this._partitioningSubdivisions = nb;
  12450. },
  12451. enumerable: true,
  12452. configurable: true
  12453. });
  12454. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12455. /**
  12456. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12457. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12458. */
  12459. get: function () {
  12460. return this._partitioningBBoxRatio;
  12461. },
  12462. set: function (ratio) {
  12463. this._partitioningBBoxRatio = ratio;
  12464. },
  12465. enumerable: true,
  12466. configurable: true
  12467. });
  12468. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12469. /**
  12470. * Read-only boolean : is the feature facetData enabled ?
  12471. */
  12472. get: function () {
  12473. return this._facetDataEnabled;
  12474. },
  12475. enumerable: true,
  12476. configurable: true
  12477. });
  12478. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12479. set: function (callback) {
  12480. if (this._onCollideObserver) {
  12481. this.onCollideObservable.remove(this._onCollideObserver);
  12482. }
  12483. this._onCollideObserver = this.onCollideObservable.add(callback);
  12484. },
  12485. enumerable: true,
  12486. configurable: true
  12487. });
  12488. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12489. set: function (callback) {
  12490. if (this._onCollisionPositionChangeObserver) {
  12491. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12492. }
  12493. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12494. },
  12495. enumerable: true,
  12496. configurable: true
  12497. });
  12498. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  12499. /**
  12500. * 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.
  12501. */
  12502. get: function () {
  12503. return this._isOccluded;
  12504. },
  12505. set: function (value) {
  12506. this._isOccluded = value;
  12507. },
  12508. enumerable: true,
  12509. configurable: true
  12510. });
  12511. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  12512. /**
  12513. * Flag to check the progress status of the query
  12514. */
  12515. get: function () {
  12516. return this._isOcclusionQueryInProgress;
  12517. },
  12518. enumerable: true,
  12519. configurable: true
  12520. });
  12521. Object.defineProperty(AbstractMesh.prototype, "material", {
  12522. get: function () {
  12523. return this._material;
  12524. },
  12525. set: function (value) {
  12526. if (this._material === value) {
  12527. return;
  12528. }
  12529. this._material = value;
  12530. if (this.onMaterialChangedObservable.hasObservers) {
  12531. this.onMaterialChangedObservable.notifyObservers(this);
  12532. }
  12533. if (!this.subMeshes) {
  12534. return;
  12535. }
  12536. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12537. var subMesh = _a[_i];
  12538. subMesh.setEffect(null);
  12539. }
  12540. },
  12541. enumerable: true,
  12542. configurable: true
  12543. });
  12544. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  12545. get: function () {
  12546. return this._receiveShadows;
  12547. },
  12548. set: function (value) {
  12549. if (this._receiveShadows === value) {
  12550. return;
  12551. }
  12552. this._receiveShadows = value;
  12553. this._markSubMeshesAsLightDirty();
  12554. },
  12555. enumerable: true,
  12556. configurable: true
  12557. });
  12558. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  12559. get: function () {
  12560. return this._hasVertexAlpha;
  12561. },
  12562. set: function (value) {
  12563. if (this._hasVertexAlpha === value) {
  12564. return;
  12565. }
  12566. this._hasVertexAlpha = value;
  12567. this._markSubMeshesAsAttributesDirty();
  12568. },
  12569. enumerable: true,
  12570. configurable: true
  12571. });
  12572. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  12573. get: function () {
  12574. return this._useVertexColors;
  12575. },
  12576. set: function (value) {
  12577. if (this._useVertexColors === value) {
  12578. return;
  12579. }
  12580. this._useVertexColors = value;
  12581. this._markSubMeshesAsAttributesDirty();
  12582. },
  12583. enumerable: true,
  12584. configurable: true
  12585. });
  12586. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  12587. get: function () {
  12588. return this._computeBonesUsingShaders;
  12589. },
  12590. set: function (value) {
  12591. if (this._computeBonesUsingShaders === value) {
  12592. return;
  12593. }
  12594. this._computeBonesUsingShaders = value;
  12595. this._markSubMeshesAsAttributesDirty();
  12596. },
  12597. enumerable: true,
  12598. configurable: true
  12599. });
  12600. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  12601. get: function () {
  12602. return this._numBoneInfluencers;
  12603. },
  12604. set: function (value) {
  12605. if (this._numBoneInfluencers === value) {
  12606. return;
  12607. }
  12608. this._numBoneInfluencers = value;
  12609. this._markSubMeshesAsAttributesDirty();
  12610. },
  12611. enumerable: true,
  12612. configurable: true
  12613. });
  12614. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  12615. get: function () {
  12616. return this._applyFog;
  12617. },
  12618. set: function (value) {
  12619. if (this._applyFog === value) {
  12620. return;
  12621. }
  12622. this._applyFog = value;
  12623. this._markSubMeshesAsMiscDirty();
  12624. },
  12625. enumerable: true,
  12626. configurable: true
  12627. });
  12628. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  12629. get: function () {
  12630. return this._layerMask;
  12631. },
  12632. set: function (value) {
  12633. if (value === this._layerMask) {
  12634. return;
  12635. }
  12636. this._layerMask = value;
  12637. this._resyncLightSources();
  12638. },
  12639. enumerable: true,
  12640. configurable: true
  12641. });
  12642. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12643. get: function () {
  12644. return this._collisionMask;
  12645. },
  12646. set: function (mask) {
  12647. this._collisionMask = !isNaN(mask) ? mask : -1;
  12648. },
  12649. enumerable: true,
  12650. configurable: true
  12651. });
  12652. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12653. get: function () {
  12654. return this._collisionGroup;
  12655. },
  12656. set: function (mask) {
  12657. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12658. },
  12659. enumerable: true,
  12660. configurable: true
  12661. });
  12662. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  12663. get: function () {
  12664. return null;
  12665. },
  12666. enumerable: true,
  12667. configurable: true
  12668. });
  12669. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12670. get: function () {
  12671. return this._skeleton;
  12672. },
  12673. set: function (value) {
  12674. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12675. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12676. }
  12677. if (value && value.needInitialSkinMatrix) {
  12678. value._registerMeshWithPoseMatrix(this);
  12679. }
  12680. this._skeleton = value;
  12681. if (!this._skeleton) {
  12682. this._bonesTransformMatrices = null;
  12683. }
  12684. this._markSubMeshesAsAttributesDirty();
  12685. },
  12686. enumerable: true,
  12687. configurable: true
  12688. });
  12689. /**
  12690. * Boolean : true if the mesh has been disposed.
  12691. */
  12692. AbstractMesh.prototype.isDisposed = function () {
  12693. return this._isDisposed;
  12694. };
  12695. /**
  12696. * Returns the string "AbstractMesh"
  12697. */
  12698. AbstractMesh.prototype.getClassName = function () {
  12699. return "AbstractMesh";
  12700. };
  12701. /**
  12702. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12703. */
  12704. AbstractMesh.prototype.toString = function (fullDetails) {
  12705. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12706. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12707. if (this._skeleton) {
  12708. ret += ", skeleton: " + this._skeleton.name;
  12709. }
  12710. if (fullDetails) {
  12711. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12712. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12713. }
  12714. return ret;
  12715. };
  12716. AbstractMesh.prototype._rebuild = function () {
  12717. if (this._occlusionQuery) {
  12718. this._occlusionQuery = null;
  12719. }
  12720. if (this._edgesRenderer) {
  12721. this._edgesRenderer._rebuild();
  12722. }
  12723. if (!this.subMeshes) {
  12724. return;
  12725. }
  12726. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12727. var subMesh = _a[_i];
  12728. subMesh._rebuild();
  12729. }
  12730. };
  12731. AbstractMesh.prototype._resyncLightSources = function () {
  12732. this._lightSources.length = 0;
  12733. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  12734. var light = _a[_i];
  12735. if (!light.isEnabled()) {
  12736. continue;
  12737. }
  12738. if (light.canAffectMesh(this)) {
  12739. this._lightSources.push(light);
  12740. }
  12741. }
  12742. this._markSubMeshesAsLightDirty();
  12743. };
  12744. AbstractMesh.prototype._resyncLighSource = function (light) {
  12745. var isIn = light.isEnabled() && light.canAffectMesh(this);
  12746. var index = this._lightSources.indexOf(light);
  12747. if (index === -1) {
  12748. if (!isIn) {
  12749. return;
  12750. }
  12751. this._lightSources.push(light);
  12752. }
  12753. else {
  12754. if (isIn) {
  12755. return;
  12756. }
  12757. this._lightSources.splice(index, 1);
  12758. }
  12759. this._markSubMeshesAsLightDirty();
  12760. };
  12761. AbstractMesh.prototype._removeLightSource = function (light) {
  12762. var index = this._lightSources.indexOf(light);
  12763. if (index === -1) {
  12764. return;
  12765. }
  12766. this._lightSources.splice(index, 1);
  12767. };
  12768. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  12769. if (!this.subMeshes) {
  12770. return;
  12771. }
  12772. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12773. var subMesh = _a[_i];
  12774. if (subMesh._materialDefines) {
  12775. func(subMesh._materialDefines);
  12776. }
  12777. }
  12778. };
  12779. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  12780. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  12781. };
  12782. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  12783. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  12784. };
  12785. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  12786. if (!this.subMeshes) {
  12787. return;
  12788. }
  12789. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12790. var subMesh = _a[_i];
  12791. var material = subMesh.getMaterial();
  12792. if (material) {
  12793. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  12794. }
  12795. }
  12796. };
  12797. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12798. /**
  12799. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12800. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12801. * Default : (0.0, 0.0, 0.0)
  12802. */
  12803. get: function () {
  12804. return this._rotation;
  12805. },
  12806. set: function (newRotation) {
  12807. this._rotation = newRotation;
  12808. },
  12809. enumerable: true,
  12810. configurable: true
  12811. });
  12812. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12813. /**
  12814. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12815. * Default : (1.0, 1.0, 1.0)
  12816. */
  12817. get: function () {
  12818. return this._scaling;
  12819. },
  12820. set: function (newScaling) {
  12821. this._scaling = newScaling;
  12822. if (this.physicsImpostor) {
  12823. this.physicsImpostor.forceUpdate();
  12824. }
  12825. },
  12826. enumerable: true,
  12827. configurable: true
  12828. });
  12829. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12830. /**
  12831. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12832. * It's null by default.
  12833. * 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)
  12834. */
  12835. get: function () {
  12836. return this._rotationQuaternion;
  12837. },
  12838. set: function (quaternion) {
  12839. this._rotationQuaternion = quaternion;
  12840. //reset the rotation vector.
  12841. if (quaternion && this.rotation.length()) {
  12842. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12843. }
  12844. },
  12845. enumerable: true,
  12846. configurable: true
  12847. });
  12848. // Methods
  12849. /**
  12850. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12851. * Returns the AbstractMesh.
  12852. */
  12853. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12854. this._poseMatrix.copyFrom(matrix);
  12855. return this;
  12856. };
  12857. /**
  12858. * Returns the mesh Pose matrix.
  12859. * Returned object : Matrix
  12860. */
  12861. AbstractMesh.prototype.getPoseMatrix = function () {
  12862. return this._poseMatrix;
  12863. };
  12864. /**
  12865. * Disables the mesh edger rendering mode.
  12866. * Returns the AbstractMesh.
  12867. */
  12868. AbstractMesh.prototype.disableEdgesRendering = function () {
  12869. if (this._edgesRenderer !== undefined) {
  12870. this._edgesRenderer.dispose();
  12871. this._edgesRenderer = undefined;
  12872. }
  12873. return this;
  12874. };
  12875. /**
  12876. * Enables the edge rendering mode on the mesh.
  12877. * This mode makes the mesh edges visible.
  12878. * Returns the AbstractMesh.
  12879. */
  12880. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12881. if (epsilon === void 0) { epsilon = 0.95; }
  12882. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12883. this.disableEdgesRendering();
  12884. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12885. return this;
  12886. };
  12887. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12888. /**
  12889. * Returns true if the mesh is blocked. Used by the class Mesh.
  12890. * Returns the boolean `false` by default.
  12891. */
  12892. get: function () {
  12893. return false;
  12894. },
  12895. enumerable: true,
  12896. configurable: true
  12897. });
  12898. /**
  12899. * Returns the mesh itself by default, used by the class Mesh.
  12900. * Returned type : AbstractMesh
  12901. */
  12902. AbstractMesh.prototype.getLOD = function (camera) {
  12903. return this;
  12904. };
  12905. /**
  12906. * Returns 0 by default, used by the class Mesh.
  12907. * Returns an integer.
  12908. */
  12909. AbstractMesh.prototype.getTotalVertices = function () {
  12910. return 0;
  12911. };
  12912. /**
  12913. * Returns null by default, used by the class Mesh.
  12914. * Returned type : integer array
  12915. */
  12916. AbstractMesh.prototype.getIndices = function () {
  12917. return null;
  12918. };
  12919. /**
  12920. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12921. * Returned type : float array or Float32Array
  12922. */
  12923. AbstractMesh.prototype.getVerticesData = function (kind) {
  12924. return null;
  12925. };
  12926. /**
  12927. * Sets the vertex data of the mesh geometry for the requested `kind`.
  12928. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  12929. * The `data` are either a numeric array either a Float32Array.
  12930. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  12931. * 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).
  12932. * Note that a new underlying VertexBuffer object is created each call.
  12933. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  12934. *
  12935. * Possible `kind` values :
  12936. * - BABYLON.VertexBuffer.PositionKind
  12937. * - BABYLON.VertexBuffer.UVKind
  12938. * - BABYLON.VertexBuffer.UV2Kind
  12939. * - BABYLON.VertexBuffer.UV3Kind
  12940. * - BABYLON.VertexBuffer.UV4Kind
  12941. * - BABYLON.VertexBuffer.UV5Kind
  12942. * - BABYLON.VertexBuffer.UV6Kind
  12943. * - BABYLON.VertexBuffer.ColorKind
  12944. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12945. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12946. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12947. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12948. *
  12949. * Returns the Mesh.
  12950. */
  12951. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  12952. return null;
  12953. };
  12954. /**
  12955. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  12956. * If the mesh has no geometry, it is simply returned as it is.
  12957. * The `data` are either a numeric array either a Float32Array.
  12958. * No new underlying VertexBuffer object is created.
  12959. * 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.
  12960. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  12961. *
  12962. * Possible `kind` values :
  12963. * - BABYLON.VertexBuffer.PositionKind
  12964. * - BABYLON.VertexBuffer.UVKind
  12965. * - BABYLON.VertexBuffer.UV2Kind
  12966. * - BABYLON.VertexBuffer.UV3Kind
  12967. * - BABYLON.VertexBuffer.UV4Kind
  12968. * - BABYLON.VertexBuffer.UV5Kind
  12969. * - BABYLON.VertexBuffer.UV6Kind
  12970. * - BABYLON.VertexBuffer.ColorKind
  12971. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12972. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12973. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12974. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12975. *
  12976. * Returns the Mesh.
  12977. */
  12978. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  12979. return null;
  12980. };
  12981. /**
  12982. * Sets the mesh indices.
  12983. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  12984. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  12985. * This method creates a new index buffer each call.
  12986. * Returns the Mesh.
  12987. */
  12988. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  12989. return null;
  12990. };
  12991. /** Returns false by default, used by the class Mesh.
  12992. * Returns a boolean
  12993. */
  12994. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12995. return false;
  12996. };
  12997. /**
  12998. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12999. * Returns a BoundingInfo
  13000. */
  13001. AbstractMesh.prototype.getBoundingInfo = function () {
  13002. if (this._masterMesh) {
  13003. return this._masterMesh.getBoundingInfo();
  13004. }
  13005. if (!this._boundingInfo) {
  13006. this._updateBoundingInfo();
  13007. }
  13008. return this._boundingInfo;
  13009. };
  13010. /**
  13011. * Sets a mesh new object BoundingInfo.
  13012. * Returns the AbstractMesh.
  13013. */
  13014. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  13015. this._boundingInfo = boundingInfo;
  13016. return this;
  13017. };
  13018. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  13019. get: function () {
  13020. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  13021. },
  13022. enumerable: true,
  13023. configurable: true
  13024. });
  13025. AbstractMesh.prototype._preActivate = function () {
  13026. };
  13027. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  13028. };
  13029. AbstractMesh.prototype._activate = function (renderId) {
  13030. this._renderId = renderId;
  13031. };
  13032. /**
  13033. * Returns the last update of the World matrix
  13034. * Returns a Matrix.
  13035. */
  13036. AbstractMesh.prototype.getWorldMatrix = function () {
  13037. if (this._masterMesh) {
  13038. return this._masterMesh.getWorldMatrix();
  13039. }
  13040. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  13041. this.computeWorldMatrix();
  13042. }
  13043. return this._worldMatrix;
  13044. };
  13045. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  13046. /**
  13047. * Returns directly the last state of the mesh World matrix.
  13048. * A Matrix is returned.
  13049. */
  13050. get: function () {
  13051. return this._worldMatrix;
  13052. },
  13053. enumerable: true,
  13054. configurable: true
  13055. });
  13056. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  13057. /**
  13058. * Returns the current mesh absolute position.
  13059. * Retuns a Vector3.
  13060. */
  13061. get: function () {
  13062. return this._absolutePosition;
  13063. },
  13064. enumerable: true,
  13065. configurable: true
  13066. });
  13067. /**
  13068. * Prevents the World matrix to be computed any longer.
  13069. * Returns the AbstractMesh.
  13070. */
  13071. AbstractMesh.prototype.freezeWorldMatrix = function () {
  13072. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13073. this.computeWorldMatrix(true);
  13074. this._isWorldMatrixFrozen = true;
  13075. return this;
  13076. };
  13077. /**
  13078. * Allows back the World matrix computation.
  13079. * Returns the AbstractMesh.
  13080. */
  13081. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  13082. this._isWorldMatrixFrozen = false;
  13083. this.computeWorldMatrix(true);
  13084. return this;
  13085. };
  13086. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  13087. /**
  13088. * True if the World matrix has been frozen.
  13089. * Returns a boolean.
  13090. */
  13091. get: function () {
  13092. return this._isWorldMatrixFrozen;
  13093. },
  13094. enumerable: true,
  13095. configurable: true
  13096. });
  13097. /**
  13098. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13099. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13100. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13101. * The passed axis is also normalized.
  13102. * Returns the AbstractMesh.
  13103. */
  13104. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  13105. axis.normalize();
  13106. if (!this.rotationQuaternion) {
  13107. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13108. this.rotation = BABYLON.Vector3.Zero();
  13109. }
  13110. var rotationQuaternion;
  13111. if (!space || space === BABYLON.Space.LOCAL) {
  13112. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13113. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13114. }
  13115. else {
  13116. if (this.parent) {
  13117. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13118. invertParentWorldMatrix.invert();
  13119. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13120. }
  13121. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13122. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13123. }
  13124. return this;
  13125. };
  13126. /**
  13127. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13128. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13129. * The passed axis is also normalized.
  13130. * Returns the AbstractMesh.
  13131. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13132. */
  13133. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  13134. axis.normalize();
  13135. if (!this.rotationQuaternion) {
  13136. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13137. this.rotation.copyFromFloats(0, 0, 0);
  13138. }
  13139. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13140. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13141. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13142. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13143. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13144. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13145. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13146. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13147. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13148. return this;
  13149. };
  13150. /**
  13151. * Translates the mesh along the axis vector for the passed distance in the given space.
  13152. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13153. * Returns the AbstractMesh.
  13154. */
  13155. AbstractMesh.prototype.translate = function (axis, distance, space) {
  13156. var displacementVector = axis.scale(distance);
  13157. if (!space || space === BABYLON.Space.LOCAL) {
  13158. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13159. this.setPositionWithLocalVector(tempV3);
  13160. }
  13161. else {
  13162. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13163. }
  13164. return this;
  13165. };
  13166. /**
  13167. * Adds a rotation step to the mesh current rotation.
  13168. * x, y, z are Euler angles expressed in radians.
  13169. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13170. * This means this rotation is made in the mesh local space only.
  13171. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13172. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13173. * ```javascript
  13174. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13175. * ```
  13176. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13177. * 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.
  13178. * Returns the AbstractMesh.
  13179. */
  13180. AbstractMesh.prototype.addRotation = function (x, y, z) {
  13181. var rotationQuaternion;
  13182. if (this.rotationQuaternion) {
  13183. rotationQuaternion = this.rotationQuaternion;
  13184. }
  13185. else {
  13186. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13187. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13188. }
  13189. var accumulation = BABYLON.Tmp.Quaternion[0];
  13190. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13191. rotationQuaternion.multiplyInPlace(accumulation);
  13192. if (!this.rotationQuaternion) {
  13193. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13194. }
  13195. return this;
  13196. };
  13197. /**
  13198. * Retuns the mesh absolute position in the World.
  13199. * Returns a Vector3.
  13200. */
  13201. AbstractMesh.prototype.getAbsolutePosition = function () {
  13202. this.computeWorldMatrix();
  13203. return this._absolutePosition;
  13204. };
  13205. /**
  13206. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13207. * Returns the AbstractMesh.
  13208. */
  13209. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  13210. if (!absolutePosition) {
  13211. return;
  13212. }
  13213. var absolutePositionX;
  13214. var absolutePositionY;
  13215. var absolutePositionZ;
  13216. if (absolutePosition.x === undefined) {
  13217. if (arguments.length < 3) {
  13218. return;
  13219. }
  13220. absolutePositionX = arguments[0];
  13221. absolutePositionY = arguments[1];
  13222. absolutePositionZ = arguments[2];
  13223. }
  13224. else {
  13225. absolutePositionX = absolutePosition.x;
  13226. absolutePositionY = absolutePosition.y;
  13227. absolutePositionZ = absolutePosition.z;
  13228. }
  13229. if (this.parent) {
  13230. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13231. invertParentWorldMatrix.invert();
  13232. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13233. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13234. }
  13235. else {
  13236. this.position.x = absolutePositionX;
  13237. this.position.y = absolutePositionY;
  13238. this.position.z = absolutePositionZ;
  13239. }
  13240. return this;
  13241. };
  13242. // ================================== Point of View Movement =================================
  13243. /**
  13244. * Perform relative position change from the point of view of behind the front of the mesh.
  13245. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13246. * Supports definition of mesh facing forward or backward.
  13247. * @param {number} amountRight
  13248. * @param {number} amountUp
  13249. * @param {number} amountForward
  13250. *
  13251. * Returns the AbstractMesh.
  13252. */
  13253. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  13254. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  13255. return this;
  13256. };
  13257. /**
  13258. * Calculate relative position change from the point of view of behind the front of the mesh.
  13259. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13260. * Supports definition of mesh facing forward or backward.
  13261. * @param {number} amountRight
  13262. * @param {number} amountUp
  13263. * @param {number} amountForward
  13264. *
  13265. * Returns a new Vector3.
  13266. */
  13267. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  13268. var rotMatrix = new BABYLON.Matrix();
  13269. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13270. rotQuaternion.toRotationMatrix(rotMatrix);
  13271. var translationDelta = BABYLON.Vector3.Zero();
  13272. var defForwardMult = this.definedFacingForward ? -1 : 1;
  13273. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  13274. return translationDelta;
  13275. };
  13276. // ================================== Point of View Rotation =================================
  13277. /**
  13278. * Perform relative rotation change from the point of view of behind the front of the mesh.
  13279. * Supports definition of mesh facing forward or backward.
  13280. * @param {number} flipBack
  13281. * @param {number} twirlClockwise
  13282. * @param {number} tiltRight
  13283. *
  13284. * Returns the AbstractMesh.
  13285. */
  13286. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13287. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  13288. return this;
  13289. };
  13290. /**
  13291. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  13292. * Supports definition of mesh facing forward or backward.
  13293. * @param {number} flipBack
  13294. * @param {number} twirlClockwise
  13295. * @param {number} tiltRight
  13296. *
  13297. * Returns a new Vector3.
  13298. */
  13299. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13300. var defForwardMult = this.definedFacingForward ? 1 : -1;
  13301. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  13302. };
  13303. /**
  13304. * Sets a new pivot matrix to the mesh.
  13305. * Returns the AbstractMesh.
  13306. */
  13307. AbstractMesh.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13308. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13309. this._pivotMatrix = matrix.clone();
  13310. this._cache.pivotMatrixUpdated = true;
  13311. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13312. if (this._postMultiplyPivotMatrix) {
  13313. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13314. }
  13315. return this;
  13316. };
  13317. /**
  13318. * Returns the mesh pivot matrix.
  13319. * Default : Identity.
  13320. * A Matrix is returned.
  13321. */
  13322. AbstractMesh.prototype.getPivotMatrix = function () {
  13323. return this._pivotMatrix;
  13324. };
  13325. AbstractMesh.prototype._isSynchronized = function () {
  13326. if (this._isDirty) {
  13327. return false;
  13328. }
  13329. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  13330. return false;
  13331. if (this._cache.pivotMatrixUpdated) {
  13332. return false;
  13333. }
  13334. if (this.infiniteDistance) {
  13335. return false;
  13336. }
  13337. if (!this._cache.position.equals(this.position))
  13338. return false;
  13339. if (this.rotationQuaternion) {
  13340. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13341. return false;
  13342. }
  13343. if (!this._cache.rotation.equals(this.rotation))
  13344. return false;
  13345. if (!this._cache.scaling.equals(this.scaling))
  13346. return false;
  13347. return true;
  13348. };
  13349. AbstractMesh.prototype._initCache = function () {
  13350. _super.prototype._initCache.call(this);
  13351. this._cache.localMatrixUpdated = false;
  13352. this._cache.position = BABYLON.Vector3.Zero();
  13353. this._cache.scaling = BABYLON.Vector3.Zero();
  13354. this._cache.rotation = BABYLON.Vector3.Zero();
  13355. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13356. this._cache.billboardMode = -1;
  13357. };
  13358. AbstractMesh.prototype.markAsDirty = function (property) {
  13359. if (property === "rotation") {
  13360. this.rotationQuaternion = null;
  13361. }
  13362. this._currentRenderId = Number.MAX_VALUE;
  13363. this._isDirty = true;
  13364. return this;
  13365. };
  13366. /**
  13367. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  13368. */
  13369. AbstractMesh.prototype.getHierarchyBoundingVectors = function () {
  13370. this.computeWorldMatrix(true);
  13371. var min;
  13372. var max;
  13373. if (!this.subMeshes) {
  13374. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13375. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13376. }
  13377. else {
  13378. min = this.getBoundingInfo().boundingBox.minimumWorld;
  13379. max = this.getBoundingInfo().boundingBox.maximumWorld;
  13380. }
  13381. var descendants = this.getDescendants(false);
  13382. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  13383. var descendant = descendants_1[_i];
  13384. var childMesh = descendant;
  13385. childMesh.computeWorldMatrix(true);
  13386. if (childMesh.getTotalVertices() === 0) {
  13387. continue;
  13388. }
  13389. var boundingBox = childMesh.getBoundingInfo().boundingBox;
  13390. var minBox = boundingBox.minimumWorld;
  13391. var maxBox = boundingBox.maximumWorld;
  13392. BABYLON.Tools.CheckExtends(minBox, min, max);
  13393. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13394. }
  13395. return {
  13396. min: min,
  13397. max: max
  13398. };
  13399. };
  13400. /**
  13401. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  13402. * Returns the AbstractMesh.
  13403. */
  13404. AbstractMesh.prototype._updateBoundingInfo = function () {
  13405. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  13406. this._boundingInfo.update(this.worldMatrixFromCache);
  13407. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13408. return this;
  13409. };
  13410. /**
  13411. * Update a mesh's children BoundingInfo objects only.
  13412. * Returns the AbstractMesh.
  13413. */
  13414. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  13415. if (!this.subMeshes) {
  13416. return;
  13417. }
  13418. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  13419. var subMesh = this.subMeshes[subIndex];
  13420. if (!subMesh.IsGlobal) {
  13421. subMesh.updateBoundingInfo(matrix);
  13422. }
  13423. }
  13424. return this;
  13425. };
  13426. /**
  13427. * Computes the mesh World matrix and returns it.
  13428. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13429. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13430. * If the parameter `force`is set to `true`, the actual computation is done.
  13431. * Returns the mesh World Matrix.
  13432. */
  13433. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  13434. if (this._isWorldMatrixFrozen) {
  13435. return this._worldMatrix;
  13436. }
  13437. if (!force && this.isSynchronized(true)) {
  13438. this._currentRenderId = this.getScene().getRenderId();
  13439. return this._worldMatrix;
  13440. }
  13441. this._cache.position.copyFrom(this.position);
  13442. this._cache.scaling.copyFrom(this.scaling);
  13443. this._cache.pivotMatrixUpdated = false;
  13444. this._cache.billboardMode = this.billboardMode;
  13445. this._currentRenderId = this.getScene().getRenderId();
  13446. this._isDirty = false;
  13447. // Scaling
  13448. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13449. // Rotation
  13450. //rotate, if quaternion is set and rotation was used
  13451. if (this.rotationQuaternion) {
  13452. var len = this.rotation.length();
  13453. if (len) {
  13454. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13455. this.rotation.copyFromFloats(0, 0, 0);
  13456. }
  13457. }
  13458. if (this.rotationQuaternion) {
  13459. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13460. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13461. }
  13462. else {
  13463. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13464. this._cache.rotation.copyFrom(this.rotation);
  13465. }
  13466. // Translation
  13467. if (this.infiniteDistance && !this.parent) {
  13468. var camera = this.getScene().activeCamera;
  13469. if (camera) {
  13470. var cameraWorldMatrix = camera.getWorldMatrix();
  13471. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13472. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13473. }
  13474. }
  13475. else {
  13476. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13477. }
  13478. // Composing transformations
  13479. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13480. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13481. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13482. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  13483. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  13484. // Need to decompose each rotation here
  13485. var currentPosition = BABYLON.Tmp.Vector3[3];
  13486. if (this.parent && this.parent.getWorldMatrix) {
  13487. if (this._meshToBoneReferal) {
  13488. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13489. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13490. }
  13491. else {
  13492. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13493. }
  13494. }
  13495. else {
  13496. currentPosition.copyFrom(this.position);
  13497. }
  13498. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  13499. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13500. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  13501. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13502. }
  13503. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  13504. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13505. }
  13506. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  13507. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13508. }
  13509. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13510. }
  13511. else {
  13512. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  13513. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13514. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13515. }
  13516. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13517. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13518. }
  13519. // Local world
  13520. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13521. // Parent
  13522. if (this.parent && this.parent.getWorldMatrix) {
  13523. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  13524. if (this._meshToBoneReferal) {
  13525. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13526. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13527. }
  13528. else {
  13529. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13530. }
  13531. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13532. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13533. this._worldMatrix.copyFrom(this._localWorld);
  13534. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13535. }
  13536. else {
  13537. if (this._meshToBoneReferal) {
  13538. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13539. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13540. }
  13541. else {
  13542. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13543. }
  13544. }
  13545. this._markSyncedWithParent();
  13546. }
  13547. else {
  13548. this._worldMatrix.copyFrom(this._localWorld);
  13549. }
  13550. // Post multiply inverse of pivotMatrix
  13551. if (this._postMultiplyPivotMatrix) {
  13552. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  13553. }
  13554. // Bounding info
  13555. this._updateBoundingInfo();
  13556. // Absolute position
  13557. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13558. // Callbacks
  13559. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13560. if (!this._poseMatrix) {
  13561. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13562. }
  13563. return this._worldMatrix;
  13564. };
  13565. /**
  13566. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13567. * @param func: callback function to add
  13568. *
  13569. * Returns the AbstractMesh.
  13570. */
  13571. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13572. this.onAfterWorldMatrixUpdateObservable.add(func);
  13573. return this;
  13574. };
  13575. /**
  13576. * Removes a registered callback function.
  13577. * Returns the AbstractMesh.
  13578. */
  13579. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13580. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13581. return this;
  13582. };
  13583. /**
  13584. * Sets the mesh position in its local space.
  13585. * Returns the AbstractMesh.
  13586. */
  13587. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  13588. this.computeWorldMatrix();
  13589. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13590. return this;
  13591. };
  13592. /**
  13593. * Returns the mesh position in the local space from the current World matrix values.
  13594. * Returns a new Vector3.
  13595. */
  13596. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  13597. this.computeWorldMatrix();
  13598. var invLocalWorldMatrix = this._localWorld.clone();
  13599. invLocalWorldMatrix.invert();
  13600. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13601. };
  13602. /**
  13603. * Translates the mesh along the passed Vector3 in its local space.
  13604. * Returns the AbstractMesh.
  13605. */
  13606. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  13607. this.computeWorldMatrix(true);
  13608. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13609. return this;
  13610. };
  13611. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13612. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13613. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13614. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13615. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13616. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13617. /// <returns>Mesh oriented towards targetMesh</returns>
  13618. if (yawCor === void 0) { yawCor = 0; }
  13619. if (pitchCor === void 0) { pitchCor = 0; }
  13620. if (rollCor === void 0) { rollCor = 0; }
  13621. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13622. var dv = AbstractMesh._lookAtVectorCache;
  13623. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13624. targetPoint.subtractToRef(pos, dv);
  13625. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13626. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13627. var pitch = Math.atan2(dv.y, len);
  13628. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13629. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13630. return this;
  13631. };
  13632. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13633. this._meshToBoneReferal = affectedMesh;
  13634. this.parent = bone;
  13635. if (bone.getWorldMatrix().determinant() < 0) {
  13636. this.scalingDeterminant *= -1;
  13637. }
  13638. return this;
  13639. };
  13640. AbstractMesh.prototype.detachFromBone = function () {
  13641. if (this.parent.getWorldMatrix().determinant() < 0) {
  13642. this.scalingDeterminant *= -1;
  13643. }
  13644. this._meshToBoneReferal = null;
  13645. this.parent = null;
  13646. return this;
  13647. };
  13648. /**
  13649. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13650. * A mesh is in the frustum if its bounding box intersects the frustum.
  13651. * Boolean returned.
  13652. */
  13653. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13654. return this._boundingInfo.isInFrustum(frustumPlanes);
  13655. };
  13656. /**
  13657. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13658. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13659. * Boolean returned.
  13660. */
  13661. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13662. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13663. ;
  13664. };
  13665. /**
  13666. * True if the mesh intersects another mesh or a SolidParticle object.
  13667. * 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)
  13668. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  13669. * Returns a boolean.
  13670. */
  13671. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  13672. if (!this._boundingInfo || !mesh._boundingInfo) {
  13673. return false;
  13674. }
  13675. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  13676. return true;
  13677. }
  13678. if (includeDescendants) {
  13679. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  13680. var child = _a[_i];
  13681. if (child.intersectsMesh(mesh, precise, true)) {
  13682. return true;
  13683. }
  13684. }
  13685. }
  13686. return false;
  13687. };
  13688. /**
  13689. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13690. * Returns a boolean.
  13691. */
  13692. AbstractMesh.prototype.intersectsPoint = function (point) {
  13693. if (!this._boundingInfo) {
  13694. return false;
  13695. }
  13696. return this._boundingInfo.intersectsPoint(point);
  13697. };
  13698. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13699. return this.physicsImpostor;
  13700. };
  13701. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13702. if (!camera) {
  13703. camera = this.getScene().activeCamera;
  13704. }
  13705. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13706. };
  13707. /**
  13708. * Returns the distance from the mesh to the active camera.
  13709. * Returns a float.
  13710. */
  13711. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13712. if (!camera) {
  13713. camera = this.getScene().activeCamera;
  13714. }
  13715. return this.absolutePosition.subtract(camera.position).length();
  13716. };
  13717. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13718. if (!this.physicsImpostor) {
  13719. return;
  13720. }
  13721. this.physicsImpostor.applyImpulse(force, contactPoint);
  13722. return this;
  13723. };
  13724. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13725. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13726. return;
  13727. }
  13728. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13729. mainPivot: pivot1,
  13730. connectedPivot: pivot2,
  13731. nativeParams: options
  13732. });
  13733. return this;
  13734. };
  13735. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13736. // Collisions
  13737. /**
  13738. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13739. * Default `false`.
  13740. */
  13741. get: function () {
  13742. return this._checkCollisions;
  13743. },
  13744. set: function (collisionEnabled) {
  13745. this._checkCollisions = collisionEnabled;
  13746. if (this.getScene().workerCollisions) {
  13747. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13748. }
  13749. },
  13750. enumerable: true,
  13751. configurable: true
  13752. });
  13753. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  13754. var globalPosition = this.getAbsolutePosition();
  13755. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13756. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13757. if (!this._collider) {
  13758. this._collider = new BABYLON.Collider();
  13759. }
  13760. this._collider.radius = this.ellipsoid;
  13761. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13762. return this;
  13763. };
  13764. // Submeshes octree
  13765. /**
  13766. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13767. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13768. * Returns an Octree of submeshes.
  13769. */
  13770. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13771. if (maxCapacity === void 0) { maxCapacity = 64; }
  13772. if (maxDepth === void 0) { maxDepth = 2; }
  13773. if (!this._submeshesOctree) {
  13774. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13775. }
  13776. this.computeWorldMatrix(true);
  13777. // Update octree
  13778. var bbox = this.getBoundingInfo().boundingBox;
  13779. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13780. return this._submeshesOctree;
  13781. };
  13782. // Collisions
  13783. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13784. this._generatePointsArray();
  13785. // Transformation
  13786. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13787. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13788. subMesh._lastColliderWorldVertices = [];
  13789. subMesh._trianglePlanes = [];
  13790. var start = subMesh.verticesStart;
  13791. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13792. for (var i = start; i < end; i++) {
  13793. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13794. }
  13795. }
  13796. // Collide
  13797. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13798. if (collider.collisionFound) {
  13799. collider.collidedMesh = this;
  13800. }
  13801. return this;
  13802. };
  13803. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13804. var subMeshes;
  13805. var len;
  13806. // Octrees
  13807. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13808. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13809. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13810. len = intersections.length;
  13811. subMeshes = intersections.data;
  13812. }
  13813. else {
  13814. subMeshes = this.subMeshes;
  13815. len = subMeshes.length;
  13816. }
  13817. for (var index = 0; index < len; index++) {
  13818. var subMesh = subMeshes[index];
  13819. // Bounding test
  13820. if (len > 1 && !subMesh._checkCollision(collider))
  13821. continue;
  13822. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13823. }
  13824. return this;
  13825. };
  13826. AbstractMesh.prototype._checkCollision = function (collider) {
  13827. // Bounding box test
  13828. if (!this._boundingInfo._checkCollision(collider))
  13829. return this;
  13830. // Transformation matrix
  13831. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13832. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13833. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13834. return this;
  13835. };
  13836. // Picking
  13837. AbstractMesh.prototype._generatePointsArray = function () {
  13838. return false;
  13839. };
  13840. /**
  13841. * Checks if the passed Ray intersects with the mesh.
  13842. * Returns an object PickingInfo.
  13843. */
  13844. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13845. var pickingInfo = new BABYLON.PickingInfo();
  13846. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13847. return pickingInfo;
  13848. }
  13849. if (!this._generatePointsArray()) {
  13850. return pickingInfo;
  13851. }
  13852. var intersectInfo = null;
  13853. // Octrees
  13854. var subMeshes;
  13855. var len;
  13856. if (this._submeshesOctree && this.useOctreeForPicking) {
  13857. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13858. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13859. len = intersections.length;
  13860. subMeshes = intersections.data;
  13861. }
  13862. else {
  13863. subMeshes = this.subMeshes;
  13864. len = subMeshes.length;
  13865. }
  13866. for (var index = 0; index < len; index++) {
  13867. var subMesh = subMeshes[index];
  13868. // Bounding test
  13869. if (len > 1 && !subMesh.canIntersects(ray))
  13870. continue;
  13871. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13872. if (currentIntersectInfo) {
  13873. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13874. intersectInfo = currentIntersectInfo;
  13875. intersectInfo.subMeshId = index;
  13876. if (fastCheck) {
  13877. break;
  13878. }
  13879. }
  13880. }
  13881. }
  13882. if (intersectInfo) {
  13883. // Get picked point
  13884. var world = this.getWorldMatrix();
  13885. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13886. var direction = ray.direction.clone();
  13887. direction = direction.scale(intersectInfo.distance);
  13888. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13889. var pickedPoint = worldOrigin.add(worldDirection);
  13890. // Return result
  13891. pickingInfo.hit = true;
  13892. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13893. pickingInfo.pickedPoint = pickedPoint;
  13894. pickingInfo.pickedMesh = this;
  13895. pickingInfo.bu = intersectInfo.bu;
  13896. pickingInfo.bv = intersectInfo.bv;
  13897. pickingInfo.faceId = intersectInfo.faceId;
  13898. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13899. return pickingInfo;
  13900. }
  13901. return pickingInfo;
  13902. };
  13903. /**
  13904. * Clones the mesh, used by the class Mesh.
  13905. * Just returns `null` for an AbstractMesh.
  13906. */
  13907. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13908. return null;
  13909. };
  13910. /**
  13911. * Disposes all the mesh submeshes.
  13912. * Returns the AbstractMesh.
  13913. */
  13914. AbstractMesh.prototype.releaseSubMeshes = function () {
  13915. if (this.subMeshes) {
  13916. while (this.subMeshes.length) {
  13917. this.subMeshes[0].dispose();
  13918. }
  13919. }
  13920. else {
  13921. this.subMeshes = new Array();
  13922. }
  13923. return this;
  13924. };
  13925. /**
  13926. * Disposes the AbstractMesh.
  13927. * Some internal references are kept for further use.
  13928. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13929. * Returns nothing.
  13930. */
  13931. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13932. var _this = this;
  13933. var index;
  13934. // Action manager
  13935. if (this.actionManager) {
  13936. this.actionManager.dispose();
  13937. this.actionManager = null;
  13938. }
  13939. // Skeleton
  13940. this.skeleton = null;
  13941. // Animations
  13942. this.getScene().stopAnimation(this);
  13943. // Physics
  13944. if (this.physicsImpostor) {
  13945. this.physicsImpostor.dispose();
  13946. }
  13947. // Intersections in progress
  13948. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13949. var other = this._intersectionsInProgress[index];
  13950. var pos = other._intersectionsInProgress.indexOf(this);
  13951. other._intersectionsInProgress.splice(pos, 1);
  13952. }
  13953. this._intersectionsInProgress = [];
  13954. // Lights
  13955. var lights = this.getScene().lights;
  13956. lights.forEach(function (light) {
  13957. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13958. if (meshIndex !== -1) {
  13959. light.includedOnlyMeshes.splice(meshIndex, 1);
  13960. }
  13961. meshIndex = light.excludedMeshes.indexOf(_this);
  13962. if (meshIndex !== -1) {
  13963. light.excludedMeshes.splice(meshIndex, 1);
  13964. }
  13965. // Shadow generators
  13966. var generator = light.getShadowGenerator();
  13967. if (generator) {
  13968. var shadowMap = generator.getShadowMap();
  13969. meshIndex = shadowMap.renderList.indexOf(_this);
  13970. if (meshIndex !== -1) {
  13971. shadowMap.renderList.splice(meshIndex, 1);
  13972. }
  13973. }
  13974. });
  13975. // Edges
  13976. if (this._edgesRenderer) {
  13977. this._edgesRenderer.dispose();
  13978. this._edgesRenderer = null;
  13979. }
  13980. // SubMeshes
  13981. if (this.getClassName() !== "InstancedMesh") {
  13982. this.releaseSubMeshes();
  13983. }
  13984. // Octree
  13985. var sceneOctree = this.getScene().selectionOctree;
  13986. if (sceneOctree) {
  13987. var index = sceneOctree.dynamicContent.indexOf(this);
  13988. if (index !== -1) {
  13989. sceneOctree.dynamicContent.splice(index, 1);
  13990. }
  13991. }
  13992. // Query
  13993. var engine = this.getScene().getEngine();
  13994. if (this._occlusionQuery) {
  13995. this._isOcclusionQueryInProgress = false;
  13996. engine.deleteQuery(this._occlusionQuery);
  13997. this._occlusionQuery = null;
  13998. }
  13999. // Engine
  14000. engine.wipeCaches();
  14001. // Remove from scene
  14002. this.getScene().removeMesh(this);
  14003. if (!doNotRecurse) {
  14004. // Particles
  14005. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  14006. if (this.getScene().particleSystems[index].emitter === this) {
  14007. this.getScene().particleSystems[index].dispose();
  14008. index--;
  14009. }
  14010. }
  14011. // Children
  14012. var objects = this.getDescendants(true);
  14013. for (index = 0; index < objects.length; index++) {
  14014. objects[index].dispose();
  14015. }
  14016. }
  14017. else {
  14018. var childMeshes = this.getChildMeshes(true);
  14019. for (index = 0; index < childMeshes.length; index++) {
  14020. var child = childMeshes[index];
  14021. child.parent = null;
  14022. child.computeWorldMatrix(true);
  14023. }
  14024. }
  14025. // facet data
  14026. if (this._facetDataEnabled) {
  14027. this.disableFacetData();
  14028. }
  14029. this.onAfterWorldMatrixUpdateObservable.clear();
  14030. this.onCollideObservable.clear();
  14031. this.onCollisionPositionChangeObservable.clear();
  14032. this._isDisposed = true;
  14033. _super.prototype.dispose.call(this);
  14034. };
  14035. /**
  14036. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14037. * This Vector3 is expressed in the World space.
  14038. */
  14039. AbstractMesh.prototype.getDirection = function (localAxis) {
  14040. var result = BABYLON.Vector3.Zero();
  14041. this.getDirectionToRef(localAxis, result);
  14042. return result;
  14043. };
  14044. /**
  14045. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14046. * localAxis is expressed in the mesh local space.
  14047. * result is computed in the Wordl space from the mesh World matrix.
  14048. * Returns the AbstractMesh.
  14049. */
  14050. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  14051. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14052. return this;
  14053. };
  14054. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  14055. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14056. if (this.getScene().getRenderId() == 0) {
  14057. this.computeWorldMatrix(true);
  14058. }
  14059. var wm = this.getWorldMatrix();
  14060. if (space == BABYLON.Space.WORLD) {
  14061. var tmat = BABYLON.Tmp.Matrix[0];
  14062. wm.invertToRef(tmat);
  14063. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14064. }
  14065. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14066. this._pivotMatrix.m[12] = -point.x;
  14067. this._pivotMatrix.m[13] = -point.y;
  14068. this._pivotMatrix.m[14] = -point.z;
  14069. this._cache.pivotMatrixUpdated = true;
  14070. return this;
  14071. };
  14072. /**
  14073. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14074. */
  14075. AbstractMesh.prototype.getPivotPoint = function () {
  14076. var point = BABYLON.Vector3.Zero();
  14077. this.getPivotPointToRef(point);
  14078. return point;
  14079. };
  14080. /**
  14081. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14082. * Returns the AbstractMesh.
  14083. */
  14084. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  14085. result.x = -this._pivotMatrix.m[12];
  14086. result.y = -this._pivotMatrix.m[13];
  14087. result.z = -this._pivotMatrix.m[14];
  14088. return this;
  14089. };
  14090. /**
  14091. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14092. */
  14093. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  14094. var point = BABYLON.Vector3.Zero();
  14095. this.getAbsolutePivotPointToRef(point);
  14096. return point;
  14097. };
  14098. /**
  14099. * Defines the passed mesh as the parent of the current mesh.
  14100. * Returns the AbstractMesh.
  14101. */
  14102. AbstractMesh.prototype.setParent = function (mesh) {
  14103. var child = this;
  14104. var parent = mesh;
  14105. if (mesh == null) {
  14106. var rotation = BABYLON.Tmp.Quaternion[0];
  14107. var position = BABYLON.Tmp.Vector3[0];
  14108. var scale = BABYLON.Tmp.Vector3[1];
  14109. child.getWorldMatrix().decompose(scale, rotation, position);
  14110. if (child.rotationQuaternion) {
  14111. child.rotationQuaternion.copyFrom(rotation);
  14112. }
  14113. else {
  14114. rotation.toEulerAnglesToRef(child.rotation);
  14115. }
  14116. child.position.x = position.x;
  14117. child.position.y = position.y;
  14118. child.position.z = position.z;
  14119. }
  14120. else {
  14121. var position = BABYLON.Tmp.Vector3[0];
  14122. var m1 = BABYLON.Tmp.Matrix[0];
  14123. parent.getWorldMatrix().invertToRef(m1);
  14124. BABYLON.Vector3.TransformCoordinatesToRef(child.position, m1, position);
  14125. child.position.copyFrom(position);
  14126. }
  14127. child.parent = parent;
  14128. return this;
  14129. };
  14130. /**
  14131. * Adds the passed mesh as a child to the current mesh.
  14132. * Returns the AbstractMesh.
  14133. */
  14134. AbstractMesh.prototype.addChild = function (mesh) {
  14135. mesh.setParent(this);
  14136. return this;
  14137. };
  14138. /**
  14139. * Removes the passed mesh from the current mesh children list.
  14140. * Returns the AbstractMesh.
  14141. */
  14142. AbstractMesh.prototype.removeChild = function (mesh) {
  14143. mesh.setParent(null);
  14144. return this;
  14145. };
  14146. /**
  14147. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14148. * Returns the AbstractMesh.
  14149. */
  14150. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  14151. result.x = this._pivotMatrix.m[12];
  14152. result.y = this._pivotMatrix.m[13];
  14153. result.z = this._pivotMatrix.m[14];
  14154. this.getPivotPointToRef(result);
  14155. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14156. return this;
  14157. };
  14158. // Facet data
  14159. /**
  14160. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  14161. * Returns the AbstractMesh.
  14162. */
  14163. AbstractMesh.prototype._initFacetData = function () {
  14164. if (!this._facetNormals) {
  14165. this._facetNormals = new Array();
  14166. }
  14167. if (!this._facetPositions) {
  14168. this._facetPositions = new Array();
  14169. }
  14170. if (!this._facetPartitioning) {
  14171. this._facetPartitioning = new Array();
  14172. }
  14173. this._facetNb = this.getIndices().length / 3;
  14174. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  14175. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  14176. for (var f = 0; f < this._facetNb; f++) {
  14177. this._facetNormals[f] = BABYLON.Vector3.Zero();
  14178. this._facetPositions[f] = BABYLON.Vector3.Zero();
  14179. }
  14180. this._facetDataEnabled = true;
  14181. return this;
  14182. };
  14183. /**
  14184. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  14185. * This method can be called within the render loop.
  14186. * 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.
  14187. * Returns the AbstractMesh.
  14188. */
  14189. AbstractMesh.prototype.updateFacetData = function () {
  14190. if (!this._facetDataEnabled) {
  14191. this._initFacetData();
  14192. }
  14193. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14194. var indices = this.getIndices();
  14195. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14196. var bInfo = this.getBoundingInfo();
  14197. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  14198. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  14199. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  14200. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  14201. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  14202. this._subDiv.max = this._partitioningSubdivisions;
  14203. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  14204. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  14205. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  14206. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  14207. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  14208. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  14209. // set the parameters for ComputeNormals()
  14210. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  14211. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  14212. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  14213. this._facetParameters.bInfo = bInfo;
  14214. this._facetParameters.bbSize = this._bbSize;
  14215. this._facetParameters.subDiv = this._subDiv;
  14216. this._facetParameters.ratio = this.partitioningBBoxRatio;
  14217. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  14218. return this;
  14219. };
  14220. /**
  14221. * Returns the facetLocalNormals array.
  14222. * The normals are expressed in the mesh local space.
  14223. */
  14224. AbstractMesh.prototype.getFacetLocalNormals = function () {
  14225. if (!this._facetNormals) {
  14226. this.updateFacetData();
  14227. }
  14228. return this._facetNormals;
  14229. };
  14230. /**
  14231. * Returns the facetLocalPositions array.
  14232. * The facet positions are expressed in the mesh local space.
  14233. */
  14234. AbstractMesh.prototype.getFacetLocalPositions = function () {
  14235. if (!this._facetPositions) {
  14236. this.updateFacetData();
  14237. }
  14238. return this._facetPositions;
  14239. };
  14240. /**
  14241. * Returns the facetLocalPartioning array.
  14242. */
  14243. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  14244. if (!this._facetPartitioning) {
  14245. this.updateFacetData();
  14246. }
  14247. return this._facetPartitioning;
  14248. };
  14249. /**
  14250. * Returns the i-th facet position in the world system.
  14251. * This method allocates a new Vector3 per call.
  14252. */
  14253. AbstractMesh.prototype.getFacetPosition = function (i) {
  14254. var pos = BABYLON.Vector3.Zero();
  14255. this.getFacetPositionToRef(i, pos);
  14256. return pos;
  14257. };
  14258. /**
  14259. * Sets the reference Vector3 with the i-th facet position in the world system.
  14260. * Returns the AbstractMesh.
  14261. */
  14262. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  14263. var localPos = (this.getFacetLocalPositions())[i];
  14264. var world = this.getWorldMatrix();
  14265. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  14266. return this;
  14267. };
  14268. /**
  14269. * Returns the i-th facet normal in the world system.
  14270. * This method allocates a new Vector3 per call.
  14271. */
  14272. AbstractMesh.prototype.getFacetNormal = function (i) {
  14273. var norm = BABYLON.Vector3.Zero();
  14274. this.getFacetNormalToRef(i, norm);
  14275. return norm;
  14276. };
  14277. /**
  14278. * Sets the reference Vector3 with the i-th facet normal in the world system.
  14279. * Returns the AbstractMesh.
  14280. */
  14281. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  14282. var localNorm = (this.getFacetLocalNormals())[i];
  14283. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  14284. return this;
  14285. };
  14286. /**
  14287. * 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).
  14288. */
  14289. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  14290. var bInfo = this.getBoundingInfo();
  14291. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  14292. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  14293. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  14294. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  14295. return null;
  14296. }
  14297. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  14298. };
  14299. /**
  14300. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  14301. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  14302. * 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.
  14303. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14304. * 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.
  14305. */
  14306. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  14307. if (checkFace === void 0) { checkFace = false; }
  14308. if (facing === void 0) { facing = true; }
  14309. var world = this.getWorldMatrix();
  14310. var invMat = BABYLON.Tmp.Matrix[5];
  14311. world.invertToRef(invMat);
  14312. var invVect = BABYLON.Tmp.Vector3[8];
  14313. var closest = null;
  14314. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  14315. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  14316. if (projected) {
  14317. // tranform the local computed projected vector to world coordinates
  14318. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  14319. }
  14320. return closest;
  14321. };
  14322. /**
  14323. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  14324. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  14325. * 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.
  14326. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14327. * 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.
  14328. */
  14329. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  14330. if (checkFace === void 0) { checkFace = false; }
  14331. if (facing === void 0) { facing = true; }
  14332. var closest = null;
  14333. var tmpx = 0.0;
  14334. var tmpy = 0.0;
  14335. var tmpz = 0.0;
  14336. var d = 0.0; // tmp dot facet normal * facet position
  14337. var t0 = 0.0;
  14338. var projx = 0.0;
  14339. var projy = 0.0;
  14340. var projz = 0.0;
  14341. // Get all the facets in the same partitioning block than (x, y, z)
  14342. var facetPositions = this.getFacetLocalPositions();
  14343. var facetNormals = this.getFacetLocalNormals();
  14344. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  14345. if (!facetsInBlock) {
  14346. return null;
  14347. }
  14348. // Get the closest facet to (x, y, z)
  14349. var shortest = Number.MAX_VALUE; // init distance vars
  14350. var tmpDistance = shortest;
  14351. var fib; // current facet in the block
  14352. var norm; // current facet normal
  14353. var p0; // current facet barycenter position
  14354. // loop on all the facets in the current partitioning block
  14355. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  14356. fib = facetsInBlock[idx];
  14357. norm = facetNormals[fib];
  14358. p0 = facetPositions[fib];
  14359. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  14360. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  14361. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  14362. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  14363. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  14364. projx = x + norm.x * t0;
  14365. projy = y + norm.y * t0;
  14366. projz = z + norm.z * t0;
  14367. tmpx = projx - x;
  14368. tmpy = projy - y;
  14369. tmpz = projz - z;
  14370. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  14371. if (tmpDistance < shortest) {
  14372. shortest = tmpDistance;
  14373. closest = fib;
  14374. if (projected) {
  14375. projected.x = projx;
  14376. projected.y = projy;
  14377. projected.z = projz;
  14378. }
  14379. }
  14380. }
  14381. }
  14382. return closest;
  14383. };
  14384. /**
  14385. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  14386. */
  14387. AbstractMesh.prototype.getFacetDataParameters = function () {
  14388. return this._facetParameters;
  14389. };
  14390. /**
  14391. * Disables the feature FacetData and frees the related memory.
  14392. * Returns the AbstractMesh.
  14393. */
  14394. AbstractMesh.prototype.disableFacetData = function () {
  14395. if (this._facetDataEnabled) {
  14396. this._facetDataEnabled = false;
  14397. this._facetPositions = null;
  14398. this._facetNormals = null;
  14399. this._facetPartitioning = null;
  14400. this._facetParameters = null;
  14401. }
  14402. return this;
  14403. };
  14404. /**
  14405. * Creates new normals data for the mesh.
  14406. * @param updatable.
  14407. */
  14408. AbstractMesh.prototype.createNormals = function (updatable) {
  14409. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14410. var indices = this.getIndices();
  14411. var normals;
  14412. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14413. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14414. }
  14415. else {
  14416. normals = [];
  14417. }
  14418. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  14419. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  14420. };
  14421. AbstractMesh.prototype.checkOcclusionQuery = function () {
  14422. var engine = this.getEngine();
  14423. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  14424. this._isOccluded = false;
  14425. return;
  14426. }
  14427. if (this.isOcclusionQueryInProgress) {
  14428. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  14429. if (isOcclusionQueryAvailable) {
  14430. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  14431. this._isOcclusionQueryInProgress = false;
  14432. this._occlusionInternalRetryCounter = 0;
  14433. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  14434. }
  14435. else {
  14436. this._occlusionInternalRetryCounter++;
  14437. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  14438. this._isOcclusionQueryInProgress = false;
  14439. this._occlusionInternalRetryCounter = 0;
  14440. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  14441. // if strict continue the last state of the object.
  14442. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  14443. }
  14444. else {
  14445. return;
  14446. }
  14447. }
  14448. }
  14449. var scene = this.getScene();
  14450. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  14451. if (!this._occlusionQuery) {
  14452. this._occlusionQuery = engine.createQuery();
  14453. }
  14454. engine.beginQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  14455. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  14456. engine.endQuery(this.occlusionQueryAlgorithmType);
  14457. this._isOcclusionQueryInProgress = true;
  14458. };
  14459. // Statics
  14460. AbstractMesh._BILLBOARDMODE_NONE = 0;
  14461. AbstractMesh._BILLBOARDMODE_X = 1;
  14462. AbstractMesh._BILLBOARDMODE_Y = 2;
  14463. AbstractMesh._BILLBOARDMODE_Z = 4;
  14464. AbstractMesh._BILLBOARDMODE_ALL = 7;
  14465. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  14466. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  14467. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  14468. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  14469. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  14470. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  14471. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14472. return AbstractMesh;
  14473. }(BABYLON.Node));
  14474. BABYLON.AbstractMesh = AbstractMesh;
  14475. })(BABYLON || (BABYLON = {}));
  14476. //# sourceMappingURL=babylon.abstractMesh.js.map
  14477. var BABYLON;
  14478. (function (BABYLON) {
  14479. var Light = (function (_super) {
  14480. __extends(Light, _super);
  14481. /**
  14482. * Creates a Light object in the scene.
  14483. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14484. */
  14485. function Light(name, scene) {
  14486. var _this = _super.call(this, name, scene) || this;
  14487. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  14488. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  14489. _this.intensity = 1.0;
  14490. _this.range = Number.MAX_VALUE;
  14491. /**
  14492. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  14493. * of light.
  14494. */
  14495. _this._photometricScale = 1.0;
  14496. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  14497. _this._radius = 0.00001;
  14498. _this.renderPriority = 0;
  14499. /**
  14500. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  14501. * the current shadow generator.
  14502. */
  14503. _this.shadowEnabled = true;
  14504. _this._excludeWithLayerMask = 0;
  14505. _this._includeOnlyWithLayerMask = 0;
  14506. _this._lightmapMode = 0;
  14507. _this._excludedMeshesIds = new Array();
  14508. _this._includedOnlyMeshesIds = new Array();
  14509. _this.getScene().addLight(_this);
  14510. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  14511. _this._buildUniformLayout();
  14512. _this.includedOnlyMeshes = new Array();
  14513. _this.excludedMeshes = new Array();
  14514. _this._resyncMeshes();
  14515. return _this;
  14516. }
  14517. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  14518. /**
  14519. * If every light affecting the material is in this lightmapMode,
  14520. * material.lightmapTexture adds or multiplies
  14521. * (depends on material.useLightmapAsShadowmap)
  14522. * after every other light calculations.
  14523. */
  14524. get: function () {
  14525. return Light._LIGHTMAP_DEFAULT;
  14526. },
  14527. enumerable: true,
  14528. configurable: true
  14529. });
  14530. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  14531. /**
  14532. * material.lightmapTexture as only diffuse lighting from this light
  14533. * adds pnly specular lighting from this light
  14534. * adds dynamic shadows
  14535. */
  14536. get: function () {
  14537. return Light._LIGHTMAP_SPECULAR;
  14538. },
  14539. enumerable: true,
  14540. configurable: true
  14541. });
  14542. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  14543. /**
  14544. * material.lightmapTexture as only lighting
  14545. * no light calculation from this light
  14546. * only adds dynamic shadows from this light
  14547. */
  14548. get: function () {
  14549. return Light._LIGHTMAP_SHADOWSONLY;
  14550. },
  14551. enumerable: true,
  14552. configurable: true
  14553. });
  14554. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  14555. /**
  14556. * Each light type uses the default quantity according to its type:
  14557. * point/spot lights use luminous intensity
  14558. * directional lights use illuminance
  14559. */
  14560. get: function () {
  14561. return Light._INTENSITYMODE_AUTOMATIC;
  14562. },
  14563. enumerable: true,
  14564. configurable: true
  14565. });
  14566. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  14567. /**
  14568. * lumen (lm)
  14569. */
  14570. get: function () {
  14571. return Light._INTENSITYMODE_LUMINOUSPOWER;
  14572. },
  14573. enumerable: true,
  14574. configurable: true
  14575. });
  14576. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  14577. /**
  14578. * candela (lm/sr)
  14579. */
  14580. get: function () {
  14581. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  14582. },
  14583. enumerable: true,
  14584. configurable: true
  14585. });
  14586. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  14587. /**
  14588. * lux (lm/m^2)
  14589. */
  14590. get: function () {
  14591. return Light._INTENSITYMODE_ILLUMINANCE;
  14592. },
  14593. enumerable: true,
  14594. configurable: true
  14595. });
  14596. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  14597. /**
  14598. * nit (cd/m^2)
  14599. */
  14600. get: function () {
  14601. return Light._INTENSITYMODE_LUMINANCE;
  14602. },
  14603. enumerable: true,
  14604. configurable: true
  14605. });
  14606. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  14607. /**
  14608. * Light type const id of the point light.
  14609. */
  14610. get: function () {
  14611. return Light._LIGHTTYPEID_POINTLIGHT;
  14612. },
  14613. enumerable: true,
  14614. configurable: true
  14615. });
  14616. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  14617. /**
  14618. * Light type const id of the directional light.
  14619. */
  14620. get: function () {
  14621. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  14622. },
  14623. enumerable: true,
  14624. configurable: true
  14625. });
  14626. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  14627. /**
  14628. * Light type const id of the spot light.
  14629. */
  14630. get: function () {
  14631. return Light._LIGHTTYPEID_SPOTLIGHT;
  14632. },
  14633. enumerable: true,
  14634. configurable: true
  14635. });
  14636. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  14637. /**
  14638. * Light type const id of the hemispheric light.
  14639. */
  14640. get: function () {
  14641. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  14642. },
  14643. enumerable: true,
  14644. configurable: true
  14645. });
  14646. Object.defineProperty(Light.prototype, "intensityMode", {
  14647. /**
  14648. * Gets the photometric scale used to interpret the intensity.
  14649. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14650. */
  14651. get: function () {
  14652. return this._intensityMode;
  14653. },
  14654. /**
  14655. * Sets the photometric scale used to interpret the intensity.
  14656. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14657. */
  14658. set: function (value) {
  14659. this._intensityMode = value;
  14660. this._computePhotometricScale();
  14661. },
  14662. enumerable: true,
  14663. configurable: true
  14664. });
  14665. ;
  14666. ;
  14667. Object.defineProperty(Light.prototype, "radius", {
  14668. /**
  14669. * Gets the light radius used by PBR Materials to simulate soft area lights.
  14670. */
  14671. get: function () {
  14672. return this._radius;
  14673. },
  14674. /**
  14675. * sets the light radius used by PBR Materials to simulate soft area lights.
  14676. */
  14677. set: function (value) {
  14678. this._radius = value;
  14679. this._computePhotometricScale();
  14680. },
  14681. enumerable: true,
  14682. configurable: true
  14683. });
  14684. ;
  14685. ;
  14686. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  14687. get: function () {
  14688. return this._includedOnlyMeshes;
  14689. },
  14690. set: function (value) {
  14691. this._includedOnlyMeshes = value;
  14692. this._hookArrayForIncludedOnly(value);
  14693. },
  14694. enumerable: true,
  14695. configurable: true
  14696. });
  14697. Object.defineProperty(Light.prototype, "excludedMeshes", {
  14698. get: function () {
  14699. return this._excludedMeshes;
  14700. },
  14701. set: function (value) {
  14702. this._excludedMeshes = value;
  14703. this._hookArrayForExcluded(value);
  14704. },
  14705. enumerable: true,
  14706. configurable: true
  14707. });
  14708. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  14709. get: function () {
  14710. return this._excludeWithLayerMask;
  14711. },
  14712. set: function (value) {
  14713. this._excludeWithLayerMask = value;
  14714. this._resyncMeshes();
  14715. },
  14716. enumerable: true,
  14717. configurable: true
  14718. });
  14719. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  14720. get: function () {
  14721. return this._includeOnlyWithLayerMask;
  14722. },
  14723. set: function (value) {
  14724. this._includeOnlyWithLayerMask = value;
  14725. this._resyncMeshes();
  14726. },
  14727. enumerable: true,
  14728. configurable: true
  14729. });
  14730. Object.defineProperty(Light.prototype, "lightmapMode", {
  14731. get: function () {
  14732. return this._lightmapMode;
  14733. },
  14734. set: function (value) {
  14735. if (this._lightmapMode === value) {
  14736. return;
  14737. }
  14738. this._lightmapMode = value;
  14739. this._markMeshesAsLightDirty();
  14740. },
  14741. enumerable: true,
  14742. configurable: true
  14743. });
  14744. Light.prototype._buildUniformLayout = function () {
  14745. // Overridden
  14746. };
  14747. /**
  14748. * Returns the string "Light".
  14749. */
  14750. Light.prototype.getClassName = function () {
  14751. return "Light";
  14752. };
  14753. /**
  14754. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14755. */
  14756. Light.prototype.toString = function (fullDetails) {
  14757. var ret = "Name: " + this.name;
  14758. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  14759. if (this.animations) {
  14760. for (var i = 0; i < this.animations.length; i++) {
  14761. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14762. }
  14763. }
  14764. if (fullDetails) {
  14765. }
  14766. return ret;
  14767. };
  14768. /**
  14769. * Set the enabled state of this node.
  14770. * @param {boolean} value - the new enabled state
  14771. * @see isEnabled
  14772. */
  14773. Light.prototype.setEnabled = function (value) {
  14774. _super.prototype.setEnabled.call(this, value);
  14775. this._resyncMeshes();
  14776. };
  14777. /**
  14778. * Returns the Light associated shadow generator.
  14779. */
  14780. Light.prototype.getShadowGenerator = function () {
  14781. return this._shadowGenerator;
  14782. };
  14783. /**
  14784. * Returns a Vector3, the absolute light position in the World.
  14785. */
  14786. Light.prototype.getAbsolutePosition = function () {
  14787. return BABYLON.Vector3.Zero();
  14788. };
  14789. Light.prototype.transferToEffect = function (effect, lightIndex) {
  14790. };
  14791. Light.prototype._getWorldMatrix = function () {
  14792. return BABYLON.Matrix.Identity();
  14793. };
  14794. /**
  14795. * Boolean : True if the light will affect the passed mesh.
  14796. */
  14797. Light.prototype.canAffectMesh = function (mesh) {
  14798. if (!mesh) {
  14799. return true;
  14800. }
  14801. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  14802. return false;
  14803. }
  14804. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  14805. return false;
  14806. }
  14807. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  14808. return false;
  14809. }
  14810. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  14811. return false;
  14812. }
  14813. return true;
  14814. };
  14815. /**
  14816. * Returns the light World matrix.
  14817. */
  14818. Light.prototype.getWorldMatrix = function () {
  14819. this._currentRenderId = this.getScene().getRenderId();
  14820. var worldMatrix = this._getWorldMatrix();
  14821. if (this.parent && this.parent.getWorldMatrix) {
  14822. if (!this._parentedWorldMatrix) {
  14823. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  14824. }
  14825. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  14826. this._markSyncedWithParent();
  14827. return this._parentedWorldMatrix;
  14828. }
  14829. return worldMatrix;
  14830. };
  14831. /**
  14832. * Sort function to order lights for rendering.
  14833. * @param a First Light object to compare to second.
  14834. * @param b Second Light object to compare first.
  14835. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  14836. */
  14837. Light.compareLightsPriority = function (a, b) {
  14838. //shadow-casting lights have priority over non-shadow-casting lights
  14839. //the renderPrioirty is a secondary sort criterion
  14840. if (a.shadowEnabled !== b.shadowEnabled) {
  14841. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  14842. }
  14843. return b.renderPriority - a.renderPriority;
  14844. };
  14845. /**
  14846. * Disposes the light.
  14847. */
  14848. Light.prototype.dispose = function () {
  14849. if (this._shadowGenerator) {
  14850. this._shadowGenerator.dispose();
  14851. this._shadowGenerator = null;
  14852. }
  14853. // Animations
  14854. this.getScene().stopAnimation(this);
  14855. // Remove from meshes
  14856. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14857. var mesh = _a[_i];
  14858. mesh._removeLightSource(this);
  14859. }
  14860. this._uniformBuffer.dispose();
  14861. // Remove from scene
  14862. this.getScene().removeLight(this);
  14863. _super.prototype.dispose.call(this);
  14864. };
  14865. /**
  14866. * Returns the light type ID (integer).
  14867. */
  14868. Light.prototype.getTypeID = function () {
  14869. return 0;
  14870. };
  14871. /**
  14872. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  14873. */
  14874. Light.prototype.getScaledIntensity = function () {
  14875. return this._photometricScale * this.intensity;
  14876. };
  14877. /**
  14878. * Returns a new Light object, named "name", from the current one.
  14879. */
  14880. Light.prototype.clone = function (name) {
  14881. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  14882. };
  14883. /**
  14884. * Serializes the current light into a Serialization object.
  14885. * Returns the serialized object.
  14886. */
  14887. Light.prototype.serialize = function () {
  14888. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14889. // Type
  14890. serializationObject.type = this.getTypeID();
  14891. // Parent
  14892. if (this.parent) {
  14893. serializationObject.parentId = this.parent.id;
  14894. }
  14895. // Inclusion / exclusions
  14896. if (this.excludedMeshes.length > 0) {
  14897. serializationObject.excludedMeshesIds = [];
  14898. this.excludedMeshes.forEach(function (mesh) {
  14899. serializationObject.excludedMeshesIds.push(mesh.id);
  14900. });
  14901. }
  14902. if (this.includedOnlyMeshes.length > 0) {
  14903. serializationObject.includedOnlyMeshesIds = [];
  14904. this.includedOnlyMeshes.forEach(function (mesh) {
  14905. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  14906. });
  14907. }
  14908. // Animations
  14909. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14910. serializationObject.ranges = this.serializeAnimationRanges();
  14911. return serializationObject;
  14912. };
  14913. /**
  14914. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  14915. * This new light is named "name" and added to the passed scene.
  14916. */
  14917. Light.GetConstructorFromName = function (type, name, scene) {
  14918. switch (type) {
  14919. case 0:
  14920. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  14921. case 1:
  14922. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  14923. case 2:
  14924. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14925. case 3:
  14926. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14927. }
  14928. };
  14929. /**
  14930. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14931. */
  14932. Light.Parse = function (parsedLight, scene) {
  14933. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14934. // Inclusion / exclusions
  14935. if (parsedLight.excludedMeshesIds) {
  14936. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14937. }
  14938. if (parsedLight.includedOnlyMeshesIds) {
  14939. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14940. }
  14941. // Parent
  14942. if (parsedLight.parentId) {
  14943. light._waitingParentId = parsedLight.parentId;
  14944. }
  14945. // Animations
  14946. if (parsedLight.animations) {
  14947. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14948. var parsedAnimation = parsedLight.animations[animationIndex];
  14949. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14950. }
  14951. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14952. }
  14953. if (parsedLight.autoAnimate) {
  14954. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14955. }
  14956. return light;
  14957. };
  14958. Light.prototype._hookArrayForExcluded = function (array) {
  14959. var _this = this;
  14960. var oldPush = array.push;
  14961. array.push = function () {
  14962. var items = [];
  14963. for (var _i = 0; _i < arguments.length; _i++) {
  14964. items[_i] = arguments[_i];
  14965. }
  14966. var result = oldPush.apply(array, items);
  14967. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  14968. var item = items_1[_a];
  14969. item._resyncLighSource(_this);
  14970. }
  14971. return result;
  14972. };
  14973. var oldSplice = array.splice;
  14974. array.splice = function (index, deleteCount) {
  14975. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14976. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  14977. var item = deleted_1[_i];
  14978. item._resyncLighSource(_this);
  14979. }
  14980. return deleted;
  14981. };
  14982. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  14983. var item = array_1[_i];
  14984. item._resyncLighSource(this);
  14985. }
  14986. };
  14987. Light.prototype._hookArrayForIncludedOnly = function (array) {
  14988. var _this = this;
  14989. var oldPush = array.push;
  14990. array.push = function () {
  14991. var items = [];
  14992. for (var _i = 0; _i < arguments.length; _i++) {
  14993. items[_i] = arguments[_i];
  14994. }
  14995. var result = oldPush.apply(array, items);
  14996. _this._resyncMeshes();
  14997. return result;
  14998. };
  14999. var oldSplice = array.splice;
  15000. array.splice = function (index, deleteCount) {
  15001. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15002. _this._resyncMeshes();
  15003. return deleted;
  15004. };
  15005. this._resyncMeshes();
  15006. };
  15007. Light.prototype._resyncMeshes = function () {
  15008. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15009. var mesh = _a[_i];
  15010. mesh._resyncLighSource(this);
  15011. }
  15012. };
  15013. Light.prototype._markMeshesAsLightDirty = function () {
  15014. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15015. var mesh = _a[_i];
  15016. if (mesh._lightSources.indexOf(this) !== -1) {
  15017. mesh._markSubMeshesAsLightDirty();
  15018. }
  15019. }
  15020. };
  15021. /**
  15022. * Recomputes the cached photometric scale if needed.
  15023. */
  15024. Light.prototype._computePhotometricScale = function () {
  15025. this._photometricScale = this._getPhotometricScale();
  15026. this.getScene().resetCachedMaterial();
  15027. };
  15028. /**
  15029. * Returns the Photometric Scale according to the light type and intensity mode.
  15030. */
  15031. Light.prototype._getPhotometricScale = function () {
  15032. var photometricScale = 0.0;
  15033. var lightTypeID = this.getTypeID();
  15034. //get photometric mode
  15035. var photometricMode = this.intensityMode;
  15036. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  15037. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  15038. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  15039. }
  15040. else {
  15041. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  15042. }
  15043. }
  15044. //compute photometric scale
  15045. switch (lightTypeID) {
  15046. case Light.LIGHTTYPEID_POINTLIGHT:
  15047. case Light.LIGHTTYPEID_SPOTLIGHT:
  15048. switch (photometricMode) {
  15049. case Light.INTENSITYMODE_LUMINOUSPOWER:
  15050. photometricScale = 1.0 / (4.0 * Math.PI);
  15051. break;
  15052. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  15053. photometricScale = 1.0;
  15054. break;
  15055. case Light.INTENSITYMODE_LUMINANCE:
  15056. photometricScale = this.radius * this.radius;
  15057. break;
  15058. }
  15059. break;
  15060. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  15061. switch (photometricMode) {
  15062. case Light.INTENSITYMODE_ILLUMINANCE:
  15063. photometricScale = 1.0;
  15064. break;
  15065. case Light.INTENSITYMODE_LUMINANCE:
  15066. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  15067. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  15068. var apexAngleRadians = this.radius;
  15069. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  15070. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  15071. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  15072. photometricScale = solidAngle;
  15073. break;
  15074. }
  15075. break;
  15076. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  15077. // No fall off in hemisperic light.
  15078. photometricScale = 1.0;
  15079. break;
  15080. }
  15081. return photometricScale;
  15082. };
  15083. Light.prototype._reorderLightsInScene = function () {
  15084. var scene = this.getScene();
  15085. if (this.renderPriority != 0) {
  15086. scene.requireLightSorting = true;
  15087. }
  15088. this.getScene().sortLightsByPriority();
  15089. };
  15090. //lightmapMode Consts
  15091. Light._LIGHTMAP_DEFAULT = 0;
  15092. Light._LIGHTMAP_SPECULAR = 1;
  15093. Light._LIGHTMAP_SHADOWSONLY = 2;
  15094. // Intensity Mode Consts
  15095. Light._INTENSITYMODE_AUTOMATIC = 0;
  15096. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  15097. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  15098. Light._INTENSITYMODE_ILLUMINANCE = 3;
  15099. Light._INTENSITYMODE_LUMINANCE = 4;
  15100. // Light types ids const.
  15101. Light._LIGHTTYPEID_POINTLIGHT = 0;
  15102. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  15103. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  15104. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  15105. __decorate([
  15106. BABYLON.serializeAsColor3()
  15107. ], Light.prototype, "diffuse", void 0);
  15108. __decorate([
  15109. BABYLON.serializeAsColor3()
  15110. ], Light.prototype, "specular", void 0);
  15111. __decorate([
  15112. BABYLON.serialize()
  15113. ], Light.prototype, "intensity", void 0);
  15114. __decorate([
  15115. BABYLON.serialize()
  15116. ], Light.prototype, "range", void 0);
  15117. __decorate([
  15118. BABYLON.serialize()
  15119. ], Light.prototype, "intensityMode", null);
  15120. __decorate([
  15121. BABYLON.serialize()
  15122. ], Light.prototype, "radius", null);
  15123. __decorate([
  15124. BABYLON.serialize()
  15125. ], Light.prototype, "_renderPriority", void 0);
  15126. __decorate([
  15127. BABYLON.expandToProperty("_reorderLightsInScene")
  15128. ], Light.prototype, "renderPriority", void 0);
  15129. __decorate([
  15130. BABYLON.serialize()
  15131. ], Light.prototype, "shadowEnabled", void 0);
  15132. __decorate([
  15133. BABYLON.serialize("excludeWithLayerMask")
  15134. ], Light.prototype, "_excludeWithLayerMask", void 0);
  15135. __decorate([
  15136. BABYLON.serialize("includeOnlyWithLayerMask")
  15137. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  15138. __decorate([
  15139. BABYLON.serialize("lightmapMode")
  15140. ], Light.prototype, "_lightmapMode", void 0);
  15141. return Light;
  15142. }(BABYLON.Node));
  15143. BABYLON.Light = Light;
  15144. })(BABYLON || (BABYLON = {}));
  15145. //# sourceMappingURL=babylon.light.js.map
  15146. var BABYLON;
  15147. (function (BABYLON) {
  15148. var Camera = (function (_super) {
  15149. __extends(Camera, _super);
  15150. function Camera(name, position, scene) {
  15151. var _this = _super.call(this, name, scene) || this;
  15152. _this.upVector = BABYLON.Vector3.Up();
  15153. _this.orthoLeft = null;
  15154. _this.orthoRight = null;
  15155. _this.orthoBottom = null;
  15156. _this.orthoTop = null;
  15157. _this.fov = 0.8;
  15158. _this.minZ = 1;
  15159. _this.maxZ = 10000.0;
  15160. _this.inertia = 0.9;
  15161. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15162. _this.isIntermediate = false;
  15163. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15164. _this.layerMask = 0x0FFFFFFF;
  15165. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15166. // Camera rig members
  15167. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15168. _this._rigCameras = new Array();
  15169. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15170. _this._skipRendering = false;
  15171. _this.customRenderTargets = new Array();
  15172. // Observables
  15173. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  15174. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  15175. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  15176. _this.onRestoreStateObservable = new BABYLON.Observable();
  15177. // Cache
  15178. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15179. _this._projectionMatrix = new BABYLON.Matrix();
  15180. _this._doNotComputeProjectionMatrix = false;
  15181. _this._postProcesses = new Array();
  15182. _this._transformMatrix = BABYLON.Matrix.Zero();
  15183. _this._activeMeshes = new BABYLON.SmartArray(256);
  15184. _this._globalPosition = BABYLON.Vector3.Zero();
  15185. _this._refreshFrustumPlanes = true;
  15186. _this.getScene().addCamera(_this);
  15187. if (!_this.getScene().activeCamera) {
  15188. _this.getScene().activeCamera = _this;
  15189. }
  15190. _this.position = position;
  15191. return _this;
  15192. }
  15193. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15194. get: function () {
  15195. return Camera._PERSPECTIVE_CAMERA;
  15196. },
  15197. enumerable: true,
  15198. configurable: true
  15199. });
  15200. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15201. get: function () {
  15202. return Camera._ORTHOGRAPHIC_CAMERA;
  15203. },
  15204. enumerable: true,
  15205. configurable: true
  15206. });
  15207. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15208. get: function () {
  15209. return Camera._FOVMODE_VERTICAL_FIXED;
  15210. },
  15211. enumerable: true,
  15212. configurable: true
  15213. });
  15214. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15215. get: function () {
  15216. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15217. },
  15218. enumerable: true,
  15219. configurable: true
  15220. });
  15221. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15222. get: function () {
  15223. return Camera._RIG_MODE_NONE;
  15224. },
  15225. enumerable: true,
  15226. configurable: true
  15227. });
  15228. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15229. get: function () {
  15230. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15231. },
  15232. enumerable: true,
  15233. configurable: true
  15234. });
  15235. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15236. get: function () {
  15237. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15238. },
  15239. enumerable: true,
  15240. configurable: true
  15241. });
  15242. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15243. get: function () {
  15244. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15245. },
  15246. enumerable: true,
  15247. configurable: true
  15248. });
  15249. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15250. get: function () {
  15251. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15252. },
  15253. enumerable: true,
  15254. configurable: true
  15255. });
  15256. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15257. get: function () {
  15258. return Camera._RIG_MODE_VR;
  15259. },
  15260. enumerable: true,
  15261. configurable: true
  15262. });
  15263. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15264. get: function () {
  15265. return Camera._RIG_MODE_WEBVR;
  15266. },
  15267. enumerable: true,
  15268. configurable: true
  15269. });
  15270. /**
  15271. * Store current camera state (fov, position, etc..)
  15272. */
  15273. Camera.prototype.storeState = function () {
  15274. this._stateStored = true;
  15275. this._storedFov = this.fov;
  15276. return this;
  15277. };
  15278. /**
  15279. * Restores the camera state values if it has been stored. You must call storeState() first
  15280. */
  15281. Camera.prototype._restoreStateValues = function () {
  15282. if (!this._stateStored) {
  15283. return false;
  15284. }
  15285. this.fov = this._storedFov;
  15286. return true;
  15287. };
  15288. /**
  15289. * Restored camera state. You must call storeState() first
  15290. */
  15291. Camera.prototype.restoreState = function () {
  15292. if (this._restoreStateValues()) {
  15293. this.onRestoreStateObservable.notifyObservers(this);
  15294. return true;
  15295. }
  15296. return false;
  15297. };
  15298. Camera.prototype.getClassName = function () {
  15299. return "Camera";
  15300. };
  15301. /**
  15302. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15303. */
  15304. Camera.prototype.toString = function (fullDetails) {
  15305. var ret = "Name: " + this.name;
  15306. ret += ", type: " + this.getClassName();
  15307. if (this.animations) {
  15308. for (var i = 0; i < this.animations.length; i++) {
  15309. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15310. }
  15311. }
  15312. if (fullDetails) {
  15313. }
  15314. return ret;
  15315. };
  15316. Object.defineProperty(Camera.prototype, "globalPosition", {
  15317. get: function () {
  15318. return this._globalPosition;
  15319. },
  15320. enumerable: true,
  15321. configurable: true
  15322. });
  15323. Camera.prototype.getActiveMeshes = function () {
  15324. return this._activeMeshes;
  15325. };
  15326. Camera.prototype.isActiveMesh = function (mesh) {
  15327. return (this._activeMeshes.indexOf(mesh) !== -1);
  15328. };
  15329. //Cache
  15330. Camera.prototype._initCache = function () {
  15331. _super.prototype._initCache.call(this);
  15332. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15333. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15334. this._cache.mode = undefined;
  15335. this._cache.minZ = undefined;
  15336. this._cache.maxZ = undefined;
  15337. this._cache.fov = undefined;
  15338. this._cache.fovMode = undefined;
  15339. this._cache.aspectRatio = undefined;
  15340. this._cache.orthoLeft = undefined;
  15341. this._cache.orthoRight = undefined;
  15342. this._cache.orthoBottom = undefined;
  15343. this._cache.orthoTop = undefined;
  15344. this._cache.renderWidth = undefined;
  15345. this._cache.renderHeight = undefined;
  15346. };
  15347. Camera.prototype._updateCache = function (ignoreParentClass) {
  15348. if (!ignoreParentClass) {
  15349. _super.prototype._updateCache.call(this);
  15350. }
  15351. var engine = this.getEngine();
  15352. this._cache.position.copyFrom(this.position);
  15353. this._cache.upVector.copyFrom(this.upVector);
  15354. };
  15355. // Synchronized
  15356. Camera.prototype._isSynchronized = function () {
  15357. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15358. };
  15359. Camera.prototype._isSynchronizedViewMatrix = function () {
  15360. if (!_super.prototype._isSynchronized.call(this))
  15361. return false;
  15362. return this._cache.position.equals(this.position)
  15363. && this._cache.upVector.equals(this.upVector)
  15364. && this.isSynchronizedWithParent();
  15365. };
  15366. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15367. var check = this._cache.mode === this.mode
  15368. && this._cache.minZ === this.minZ
  15369. && this._cache.maxZ === this.maxZ;
  15370. if (!check) {
  15371. return false;
  15372. }
  15373. var engine = this.getEngine();
  15374. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15375. check = this._cache.fov === this.fov
  15376. && this._cache.fovMode === this.fovMode
  15377. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15378. }
  15379. else {
  15380. check = this._cache.orthoLeft === this.orthoLeft
  15381. && this._cache.orthoRight === this.orthoRight
  15382. && this._cache.orthoBottom === this.orthoBottom
  15383. && this._cache.orthoTop === this.orthoTop
  15384. && this._cache.renderWidth === engine.getRenderWidth()
  15385. && this._cache.renderHeight === engine.getRenderHeight();
  15386. }
  15387. return check;
  15388. };
  15389. // Controls
  15390. Camera.prototype.attachControl = function (element, noPreventDefault) {
  15391. };
  15392. Camera.prototype.detachControl = function (element) {
  15393. };
  15394. Camera.prototype.update = function () {
  15395. this._checkInputs();
  15396. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15397. this._updateRigCameras();
  15398. }
  15399. };
  15400. Camera.prototype._checkInputs = function () {
  15401. this.onAfterCheckInputsObservable.notifyObservers(this);
  15402. };
  15403. Object.defineProperty(Camera.prototype, "rigCameras", {
  15404. get: function () {
  15405. return this._rigCameras;
  15406. },
  15407. enumerable: true,
  15408. configurable: true
  15409. });
  15410. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  15411. get: function () {
  15412. return this._rigPostProcess;
  15413. },
  15414. enumerable: true,
  15415. configurable: true
  15416. });
  15417. Camera.prototype._cascadePostProcessesToRigCams = function () {
  15418. // invalidate framebuffer
  15419. if (this._postProcesses.length > 0) {
  15420. this._postProcesses[0].markTextureDirty();
  15421. }
  15422. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  15423. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  15424. var cam = this._rigCameras[i];
  15425. var rigPostProcess = cam._rigPostProcess;
  15426. // for VR rig, there does not have to be a post process
  15427. if (rigPostProcess) {
  15428. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  15429. if (isPass) {
  15430. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  15431. cam.isIntermediate = this._postProcesses.length === 0;
  15432. }
  15433. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  15434. rigPostProcess.markTextureDirty();
  15435. }
  15436. else {
  15437. cam._postProcesses = this._postProcesses.slice(0);
  15438. }
  15439. }
  15440. };
  15441. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15442. if (insertAt === void 0) { insertAt = null; }
  15443. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15444. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15445. return 0;
  15446. }
  15447. if (insertAt == null || insertAt < 0) {
  15448. this._postProcesses.push(postProcess);
  15449. }
  15450. else {
  15451. this._postProcesses.splice(insertAt, 0, postProcess);
  15452. }
  15453. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15454. return this._postProcesses.indexOf(postProcess);
  15455. };
  15456. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15457. if (atIndices === void 0) { atIndices = null; }
  15458. var result = [];
  15459. var i;
  15460. var index;
  15461. if (!atIndices) {
  15462. var idx = this._postProcesses.indexOf(postProcess);
  15463. if (idx !== -1) {
  15464. this._postProcesses.splice(idx, 1);
  15465. }
  15466. }
  15467. else {
  15468. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  15469. // iterate descending, so can just splice as we go
  15470. for (i = atIndices.length - 1; i >= 0; i--) {
  15471. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15472. result.push(i);
  15473. continue;
  15474. }
  15475. index = atIndices[i];
  15476. this._postProcesses.splice(index, 1);
  15477. }
  15478. }
  15479. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15480. return result;
  15481. };
  15482. Camera.prototype.getWorldMatrix = function () {
  15483. if (!this._worldMatrix) {
  15484. this._worldMatrix = BABYLON.Matrix.Identity();
  15485. }
  15486. var viewMatrix = this.getViewMatrix();
  15487. viewMatrix.invertToRef(this._worldMatrix);
  15488. return this._worldMatrix;
  15489. };
  15490. Camera.prototype._getViewMatrix = function () {
  15491. return BABYLON.Matrix.Identity();
  15492. };
  15493. Camera.prototype.getViewMatrix = function (force) {
  15494. if (!force && this._isSynchronizedViewMatrix()) {
  15495. return this._computedViewMatrix;
  15496. }
  15497. this.updateCache();
  15498. this._computedViewMatrix = this._getViewMatrix();
  15499. this._currentRenderId = this.getScene().getRenderId();
  15500. this._refreshFrustumPlanes = true;
  15501. if (!this.parent || !this.parent.getWorldMatrix) {
  15502. this._globalPosition.copyFrom(this.position);
  15503. }
  15504. else {
  15505. if (!this._worldMatrix) {
  15506. this._worldMatrix = BABYLON.Matrix.Identity();
  15507. }
  15508. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15509. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15510. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15511. this._computedViewMatrix.invert();
  15512. this._markSyncedWithParent();
  15513. }
  15514. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15515. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15516. }
  15517. this.onViewMatrixChangedObservable.notifyObservers(this);
  15518. return this._computedViewMatrix;
  15519. };
  15520. Camera.prototype.freezeProjectionMatrix = function (projection) {
  15521. this._doNotComputeProjectionMatrix = true;
  15522. if (projection !== undefined) {
  15523. this._projectionMatrix = projection;
  15524. }
  15525. };
  15526. ;
  15527. Camera.prototype.unfreezeProjectionMatrix = function () {
  15528. this._doNotComputeProjectionMatrix = false;
  15529. };
  15530. ;
  15531. Camera.prototype.getProjectionMatrix = function (force) {
  15532. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  15533. return this._projectionMatrix;
  15534. }
  15535. // Cache
  15536. this._cache.mode = this.mode;
  15537. this._cache.minZ = this.minZ;
  15538. this._cache.maxZ = this.maxZ;
  15539. // Matrix
  15540. this._refreshFrustumPlanes = true;
  15541. var engine = this.getEngine();
  15542. var scene = this.getScene();
  15543. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15544. this._cache.fov = this.fov;
  15545. this._cache.fovMode = this.fovMode;
  15546. this._cache.aspectRatio = engine.getAspectRatio(this);
  15547. if (this.minZ <= 0) {
  15548. this.minZ = 0.1;
  15549. }
  15550. if (scene.useRightHandedSystem) {
  15551. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15552. }
  15553. else {
  15554. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15555. }
  15556. }
  15557. else {
  15558. var halfWidth = engine.getRenderWidth() / 2.0;
  15559. var halfHeight = engine.getRenderHeight() / 2.0;
  15560. if (scene.useRightHandedSystem) {
  15561. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15562. }
  15563. else {
  15564. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15565. }
  15566. this._cache.orthoLeft = this.orthoLeft;
  15567. this._cache.orthoRight = this.orthoRight;
  15568. this._cache.orthoBottom = this.orthoBottom;
  15569. this._cache.orthoTop = this.orthoTop;
  15570. this._cache.renderWidth = engine.getRenderWidth();
  15571. this._cache.renderHeight = engine.getRenderHeight();
  15572. }
  15573. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  15574. return this._projectionMatrix;
  15575. };
  15576. Camera.prototype.getTranformationMatrix = function () {
  15577. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15578. return this._transformMatrix;
  15579. };
  15580. Camera.prototype.updateFrustumPlanes = function () {
  15581. if (!this._refreshFrustumPlanes) {
  15582. return;
  15583. }
  15584. this.getTranformationMatrix();
  15585. if (!this._frustumPlanes) {
  15586. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15587. }
  15588. else {
  15589. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15590. }
  15591. this._refreshFrustumPlanes = false;
  15592. };
  15593. Camera.prototype.isInFrustum = function (target) {
  15594. this.updateFrustumPlanes();
  15595. return target.isInFrustum(this._frustumPlanes);
  15596. };
  15597. Camera.prototype.isCompletelyInFrustum = function (target) {
  15598. this.updateFrustumPlanes();
  15599. return target.isCompletelyInFrustum(this._frustumPlanes);
  15600. };
  15601. Camera.prototype.getForwardRay = function (length, transform, origin) {
  15602. if (length === void 0) { length = 100; }
  15603. if (!transform) {
  15604. transform = this.getWorldMatrix();
  15605. }
  15606. if (!origin) {
  15607. origin = this.position;
  15608. }
  15609. var forward = new BABYLON.Vector3(0, 0, 1);
  15610. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  15611. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  15612. return new BABYLON.Ray(origin, direction, length);
  15613. };
  15614. Camera.prototype.dispose = function () {
  15615. // Observables
  15616. this.onViewMatrixChangedObservable.clear();
  15617. this.onProjectionMatrixChangedObservable.clear();
  15618. this.onAfterCheckInputsObservable.clear();
  15619. this.onRestoreStateObservable.clear();
  15620. // Inputs
  15621. if (this.inputs) {
  15622. this.inputs.clear();
  15623. }
  15624. // Animations
  15625. this.getScene().stopAnimation(this);
  15626. // Remove from scene
  15627. this.getScene().removeCamera(this);
  15628. while (this._rigCameras.length > 0) {
  15629. this._rigCameras.pop().dispose();
  15630. }
  15631. // Postprocesses
  15632. if (this._rigPostProcess) {
  15633. this._rigPostProcess.dispose(this);
  15634. this._rigPostProcess = null;
  15635. this._postProcesses = [];
  15636. }
  15637. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15638. this._rigPostProcess = null;
  15639. this._postProcesses = [];
  15640. }
  15641. else {
  15642. var i = this._postProcesses.length;
  15643. while (--i >= 0) {
  15644. this._postProcesses[i].dispose(this);
  15645. }
  15646. }
  15647. // Render targets
  15648. var i = this.customRenderTargets.length;
  15649. while (--i >= 0) {
  15650. this.customRenderTargets[i].dispose();
  15651. }
  15652. this.customRenderTargets = [];
  15653. // Active Meshes
  15654. this._activeMeshes.dispose();
  15655. _super.prototype.dispose.call(this);
  15656. };
  15657. Object.defineProperty(Camera.prototype, "leftCamera", {
  15658. // ---- Camera rigs section ----
  15659. get: function () {
  15660. if (this._rigCameras.length < 1) {
  15661. return undefined;
  15662. }
  15663. return this._rigCameras[0];
  15664. },
  15665. enumerable: true,
  15666. configurable: true
  15667. });
  15668. Object.defineProperty(Camera.prototype, "rightCamera", {
  15669. get: function () {
  15670. if (this._rigCameras.length < 2) {
  15671. return undefined;
  15672. }
  15673. return this._rigCameras[1];
  15674. },
  15675. enumerable: true,
  15676. configurable: true
  15677. });
  15678. Camera.prototype.getLeftTarget = function () {
  15679. if (this._rigCameras.length < 1) {
  15680. return undefined;
  15681. }
  15682. return this._rigCameras[0].getTarget();
  15683. };
  15684. Camera.prototype.getRightTarget = function () {
  15685. if (this._rigCameras.length < 2) {
  15686. return undefined;
  15687. }
  15688. return this._rigCameras[1].getTarget();
  15689. };
  15690. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  15691. if (this.cameraRigMode === mode) {
  15692. return;
  15693. }
  15694. while (this._rigCameras.length > 0) {
  15695. this._rigCameras.pop().dispose();
  15696. }
  15697. this.cameraRigMode = mode;
  15698. this._cameraRigParams = {};
  15699. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  15700. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  15701. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  15702. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  15703. // create the rig cameras, unless none
  15704. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15705. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  15706. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  15707. }
  15708. switch (this.cameraRigMode) {
  15709. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15710. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15711. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  15712. break;
  15713. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15714. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15715. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15716. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15717. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15718. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  15719. break;
  15720. case Camera.RIG_MODE_VR:
  15721. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  15722. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  15723. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15724. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15725. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  15726. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  15727. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  15728. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  15729. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15730. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15731. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  15732. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  15733. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  15734. if (metrics.compensateDistortion) {
  15735. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  15736. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  15737. }
  15738. break;
  15739. case Camera.RIG_MODE_WEBVR:
  15740. if (rigParams.vrDisplay) {
  15741. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  15742. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  15743. //Left eye
  15744. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15745. this._rigCameras[0].setCameraRigParameter("left", true);
  15746. //leaving this for future reference
  15747. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  15748. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  15749. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  15750. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15751. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15752. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15753. this._rigCameras[0].parent = this;
  15754. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  15755. //Right eye
  15756. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15757. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  15758. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  15759. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  15760. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15761. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15762. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15763. this._rigCameras[1].parent = this;
  15764. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  15765. if (Camera.UseAlternateWebVRRendering) {
  15766. this._rigCameras[1]._skipRendering = true;
  15767. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  15768. }
  15769. }
  15770. break;
  15771. }
  15772. this._cascadePostProcessesToRigCams();
  15773. this.update();
  15774. };
  15775. Camera.prototype._getVRProjectionMatrix = function () {
  15776. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  15777. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  15778. return this._projectionMatrix;
  15779. };
  15780. Camera.prototype._updateCameraRotationMatrix = function () {
  15781. //Here for WebVR
  15782. };
  15783. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  15784. //Here for WebVR
  15785. };
  15786. /**
  15787. * This function MUST be overwritten by the different WebVR cameras available.
  15788. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15789. */
  15790. Camera.prototype._getWebVRProjectionMatrix = function () {
  15791. return BABYLON.Matrix.Identity();
  15792. };
  15793. /**
  15794. * This function MUST be overwritten by the different WebVR cameras available.
  15795. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15796. */
  15797. Camera.prototype._getWebVRViewMatrix = function () {
  15798. return BABYLON.Matrix.Identity();
  15799. };
  15800. Camera.prototype.setCameraRigParameter = function (name, value) {
  15801. if (!this._cameraRigParams) {
  15802. this._cameraRigParams = {};
  15803. }
  15804. this._cameraRigParams[name] = value;
  15805. //provisionnally:
  15806. if (name === "interaxialDistance") {
  15807. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  15808. }
  15809. };
  15810. /**
  15811. * needs to be overridden by children so sub has required properties to be copied
  15812. */
  15813. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  15814. return null;
  15815. };
  15816. /**
  15817. * May need to be overridden by children
  15818. */
  15819. Camera.prototype._updateRigCameras = function () {
  15820. for (var i = 0; i < this._rigCameras.length; i++) {
  15821. this._rigCameras[i].minZ = this.minZ;
  15822. this._rigCameras[i].maxZ = this.maxZ;
  15823. this._rigCameras[i].fov = this.fov;
  15824. }
  15825. // only update viewport when ANAGLYPH
  15826. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  15827. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  15828. }
  15829. };
  15830. Camera.prototype._setupInputs = function () {
  15831. };
  15832. Camera.prototype.serialize = function () {
  15833. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15834. // Type
  15835. serializationObject.type = this.getClassName();
  15836. // Parent
  15837. if (this.parent) {
  15838. serializationObject.parentId = this.parent.id;
  15839. }
  15840. if (this.inputs) {
  15841. this.inputs.serialize(serializationObject);
  15842. }
  15843. // Animations
  15844. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15845. serializationObject.ranges = this.serializeAnimationRanges();
  15846. return serializationObject;
  15847. };
  15848. Camera.prototype.clone = function (name) {
  15849. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  15850. };
  15851. Camera.prototype.getDirection = function (localAxis) {
  15852. var result = BABYLON.Vector3.Zero();
  15853. this.getDirectionToRef(localAxis, result);
  15854. return result;
  15855. };
  15856. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  15857. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15858. };
  15859. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  15860. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  15861. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  15862. switch (type) {
  15863. case "ArcRotateCamera":
  15864. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  15865. case "DeviceOrientationCamera":
  15866. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  15867. case "FollowCamera":
  15868. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  15869. case "ArcFollowCamera":
  15870. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  15871. case "GamepadCamera":
  15872. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15873. case "TouchCamera":
  15874. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  15875. case "VirtualJoysticksCamera":
  15876. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  15877. case "WebVRFreeCamera":
  15878. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15879. case "WebVRGamepadCamera":
  15880. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15881. case "VRDeviceOrientationFreeCamera":
  15882. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15883. case "VRDeviceOrientationGamepadCamera":
  15884. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15885. case "AnaglyphArcRotateCamera":
  15886. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15887. case "AnaglyphFreeCamera":
  15888. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15889. case "AnaglyphGamepadCamera":
  15890. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15891. case "AnaglyphUniversalCamera":
  15892. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15893. case "StereoscopicArcRotateCamera":
  15894. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15895. case "StereoscopicFreeCamera":
  15896. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15897. case "StereoscopicGamepadCamera":
  15898. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15899. case "StereoscopicUniversalCamera":
  15900. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15901. case "FreeCamera":// Forcing Universal here
  15902. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15903. default:// Universal Camera is the default value
  15904. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15905. }
  15906. };
  15907. Camera.Parse = function (parsedCamera, scene) {
  15908. var type = parsedCamera.type;
  15909. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  15910. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  15911. // Parent
  15912. if (parsedCamera.parentId) {
  15913. camera._waitingParentId = parsedCamera.parentId;
  15914. }
  15915. //If camera has an input manager, let it parse inputs settings
  15916. if (camera.inputs) {
  15917. camera.inputs.parse(parsedCamera);
  15918. camera._setupInputs();
  15919. }
  15920. if (camera.setPosition) {
  15921. camera.position.copyFromFloats(0, 0, 0);
  15922. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  15923. }
  15924. // Target
  15925. if (parsedCamera.target) {
  15926. if (camera.setTarget) {
  15927. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15928. }
  15929. }
  15930. // Apply 3d rig, when found
  15931. if (parsedCamera.cameraRigMode) {
  15932. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  15933. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  15934. }
  15935. // Animations
  15936. if (parsedCamera.animations) {
  15937. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15938. var parsedAnimation = parsedCamera.animations[animationIndex];
  15939. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15940. }
  15941. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  15942. }
  15943. if (parsedCamera.autoAnimate) {
  15944. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  15945. }
  15946. return camera;
  15947. };
  15948. // Statics
  15949. Camera._PERSPECTIVE_CAMERA = 0;
  15950. Camera._ORTHOGRAPHIC_CAMERA = 1;
  15951. Camera._FOVMODE_VERTICAL_FIXED = 0;
  15952. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  15953. Camera._RIG_MODE_NONE = 0;
  15954. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  15955. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  15956. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  15957. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  15958. Camera._RIG_MODE_VR = 20;
  15959. Camera._RIG_MODE_WEBVR = 21;
  15960. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  15961. Camera.UseAlternateWebVRRendering = false;
  15962. __decorate([
  15963. BABYLON.serializeAsVector3()
  15964. ], Camera.prototype, "position", void 0);
  15965. __decorate([
  15966. BABYLON.serializeAsVector3()
  15967. ], Camera.prototype, "upVector", void 0);
  15968. __decorate([
  15969. BABYLON.serialize()
  15970. ], Camera.prototype, "orthoLeft", void 0);
  15971. __decorate([
  15972. BABYLON.serialize()
  15973. ], Camera.prototype, "orthoRight", void 0);
  15974. __decorate([
  15975. BABYLON.serialize()
  15976. ], Camera.prototype, "orthoBottom", void 0);
  15977. __decorate([
  15978. BABYLON.serialize()
  15979. ], Camera.prototype, "orthoTop", void 0);
  15980. __decorate([
  15981. BABYLON.serialize()
  15982. ], Camera.prototype, "fov", void 0);
  15983. __decorate([
  15984. BABYLON.serialize()
  15985. ], Camera.prototype, "minZ", void 0);
  15986. __decorate([
  15987. BABYLON.serialize()
  15988. ], Camera.prototype, "maxZ", void 0);
  15989. __decorate([
  15990. BABYLON.serialize()
  15991. ], Camera.prototype, "inertia", void 0);
  15992. __decorate([
  15993. BABYLON.serialize()
  15994. ], Camera.prototype, "mode", void 0);
  15995. __decorate([
  15996. BABYLON.serialize()
  15997. ], Camera.prototype, "layerMask", void 0);
  15998. __decorate([
  15999. BABYLON.serialize()
  16000. ], Camera.prototype, "fovMode", void 0);
  16001. __decorate([
  16002. BABYLON.serialize()
  16003. ], Camera.prototype, "cameraRigMode", void 0);
  16004. __decorate([
  16005. BABYLON.serialize()
  16006. ], Camera.prototype, "interaxialDistance", void 0);
  16007. __decorate([
  16008. BABYLON.serialize()
  16009. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  16010. return Camera;
  16011. }(BABYLON.Node));
  16012. BABYLON.Camera = Camera;
  16013. })(BABYLON || (BABYLON = {}));
  16014. //# sourceMappingURL=babylon.camera.js.map
  16015. var BABYLON;
  16016. (function (BABYLON) {
  16017. var RenderingManager = (function () {
  16018. function RenderingManager(scene) {
  16019. this._renderingGroups = new Array();
  16020. this._autoClearDepthStencil = {};
  16021. this._customOpaqueSortCompareFn = {};
  16022. this._customAlphaTestSortCompareFn = {};
  16023. this._customTransparentSortCompareFn = {};
  16024. this._renderinGroupInfo = null;
  16025. this._scene = scene;
  16026. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16027. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  16028. }
  16029. }
  16030. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  16031. if (depth === void 0) { depth = true; }
  16032. if (stencil === void 0) { stencil = true; }
  16033. if (this._depthStencilBufferAlreadyCleaned) {
  16034. return;
  16035. }
  16036. this._scene.getEngine().clear(null, false, depth, stencil);
  16037. this._depthStencilBufferAlreadyCleaned = true;
  16038. };
  16039. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16040. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16041. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16042. var info = null;
  16043. if (observable) {
  16044. if (!this._renderinGroupInfo) {
  16045. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16046. }
  16047. info = this._renderinGroupInfo;
  16048. info.scene = this._scene;
  16049. info.camera = this._scene.activeCamera;
  16050. }
  16051. // Dispatch sprites
  16052. if (renderSprites) {
  16053. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  16054. var manager = this._scene.spriteManagers[index];
  16055. this.dispatchSprites(manager);
  16056. }
  16057. }
  16058. // Render
  16059. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16060. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16061. var renderingGroup = this._renderingGroups[index];
  16062. if (!renderingGroup && !observable)
  16063. continue;
  16064. this._currentIndex = index;
  16065. var renderingGroupMask = 0;
  16066. // Fire PRECLEAR stage
  16067. if (observable) {
  16068. renderingGroupMask = Math.pow(2, index);
  16069. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16070. info.renderingGroupId = index;
  16071. observable.notifyObservers(info, renderingGroupMask);
  16072. }
  16073. // Clear depth/stencil if needed
  16074. if (RenderingManager.AUTOCLEAR) {
  16075. var autoClear = this._autoClearDepthStencil[index];
  16076. if (autoClear && autoClear.autoClear) {
  16077. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  16078. }
  16079. }
  16080. if (observable) {
  16081. // Fire PREOPAQUE stage
  16082. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16083. observable.notifyObservers(info, renderingGroupMask);
  16084. // Fire PRETRANSPARENT stage
  16085. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16086. observable.notifyObservers(info, renderingGroupMask);
  16087. }
  16088. if (renderingGroup)
  16089. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  16090. // Fire POSTTRANSPARENT stage
  16091. if (observable) {
  16092. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16093. observable.notifyObservers(info, renderingGroupMask);
  16094. }
  16095. }
  16096. };
  16097. RenderingManager.prototype.reset = function () {
  16098. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16099. var renderingGroup = this._renderingGroups[index];
  16100. if (renderingGroup) {
  16101. renderingGroup.prepare();
  16102. }
  16103. }
  16104. };
  16105. RenderingManager.prototype.dispose = function () {
  16106. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16107. var renderingGroup = this._renderingGroups[index];
  16108. if (renderingGroup) {
  16109. renderingGroup.dispose();
  16110. }
  16111. }
  16112. this._renderingGroups.length = 0;
  16113. };
  16114. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  16115. if (!this._renderingGroups[renderingGroupId]) {
  16116. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16117. }
  16118. };
  16119. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  16120. var renderingGroupId = spriteManager.renderingGroupId || 0;
  16121. this._prepareRenderingGroup(renderingGroupId);
  16122. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  16123. };
  16124. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  16125. var renderingGroupId = particleSystem.renderingGroupId || 0;
  16126. this._prepareRenderingGroup(renderingGroupId);
  16127. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  16128. };
  16129. RenderingManager.prototype.dispatch = function (subMesh) {
  16130. var mesh = subMesh.getMesh();
  16131. var renderingGroupId = mesh.renderingGroupId || 0;
  16132. this._prepareRenderingGroup(renderingGroupId);
  16133. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16134. };
  16135. /**
  16136. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16137. * This allowed control for front to back rendering or reversly depending of the special needs.
  16138. *
  16139. * @param renderingGroupId The rendering group id corresponding to its index
  16140. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16141. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16142. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16143. */
  16144. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16145. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16146. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16147. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16148. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16149. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16150. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16151. if (this._renderingGroups[renderingGroupId]) {
  16152. var group = this._renderingGroups[renderingGroupId];
  16153. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16154. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16155. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16156. }
  16157. };
  16158. /**
  16159. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16160. *
  16161. * @param renderingGroupId The rendering group id corresponding to its index
  16162. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16163. * @param depth Automatically clears depth between groups if true and autoClear is true.
  16164. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  16165. */
  16166. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  16167. if (depth === void 0) { depth = true; }
  16168. if (stencil === void 0) { stencil = true; }
  16169. this._autoClearDepthStencil[renderingGroupId] = {
  16170. autoClear: autoClearDepthStencil,
  16171. depth: depth,
  16172. stencil: stencil
  16173. };
  16174. };
  16175. /**
  16176. * The max id used for rendering groups (not included)
  16177. */
  16178. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16179. /**
  16180. * The min id used for rendering groups (included)
  16181. */
  16182. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16183. /**
  16184. * Used to globally prevent autoclearing scenes.
  16185. */
  16186. RenderingManager.AUTOCLEAR = true;
  16187. return RenderingManager;
  16188. }());
  16189. BABYLON.RenderingManager = RenderingManager;
  16190. })(BABYLON || (BABYLON = {}));
  16191. //# sourceMappingURL=babylon.renderingManager.js.map
  16192. var BABYLON;
  16193. (function (BABYLON) {
  16194. var RenderingGroup = (function () {
  16195. /**
  16196. * Creates a new rendering group.
  16197. * @param index The rendering group index
  16198. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16199. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16200. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16201. */
  16202. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16203. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16204. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16205. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16206. this.index = index;
  16207. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16208. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16209. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16210. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  16211. this._particleSystems = new BABYLON.SmartArray(256);
  16212. this._spriteManagers = new BABYLON.SmartArray(256);
  16213. this._edgesRenderers = new BABYLON.SmartArray(16);
  16214. this._scene = scene;
  16215. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16216. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16217. this.transparentSortCompareFn = transparentSortCompareFn;
  16218. }
  16219. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16220. /**
  16221. * Set the opaque sort comparison function.
  16222. * If null the sub meshes will be render in the order they were created
  16223. */
  16224. set: function (value) {
  16225. this._opaqueSortCompareFn = value;
  16226. if (value) {
  16227. this._renderOpaque = this.renderOpaqueSorted;
  16228. }
  16229. else {
  16230. this._renderOpaque = RenderingGroup.renderUnsorted;
  16231. }
  16232. },
  16233. enumerable: true,
  16234. configurable: true
  16235. });
  16236. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16237. /**
  16238. * Set the alpha test sort comparison function.
  16239. * If null the sub meshes will be render in the order they were created
  16240. */
  16241. set: function (value) {
  16242. this._alphaTestSortCompareFn = value;
  16243. if (value) {
  16244. this._renderAlphaTest = this.renderAlphaTestSorted;
  16245. }
  16246. else {
  16247. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16248. }
  16249. },
  16250. enumerable: true,
  16251. configurable: true
  16252. });
  16253. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16254. /**
  16255. * Set the transparent sort comparison function.
  16256. * If null the sub meshes will be render in the order they were created
  16257. */
  16258. set: function (value) {
  16259. if (value) {
  16260. this._transparentSortCompareFn = value;
  16261. }
  16262. else {
  16263. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16264. }
  16265. this._renderTransparent = this.renderTransparentSorted;
  16266. },
  16267. enumerable: true,
  16268. configurable: true
  16269. });
  16270. /**
  16271. * Render all the sub meshes contained in the group.
  16272. * @param customRenderFunction Used to override the default render behaviour of the group.
  16273. * @returns true if rendered some submeshes.
  16274. */
  16275. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16276. if (customRenderFunction) {
  16277. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  16278. return;
  16279. }
  16280. var engine = this._scene.getEngine();
  16281. // Depth only
  16282. if (this._depthOnlySubMeshes.length !== 0) {
  16283. engine.setAlphaTesting(true);
  16284. engine.setColorWrite(false);
  16285. this._renderAlphaTest(this._depthOnlySubMeshes);
  16286. engine.setAlphaTesting(false);
  16287. engine.setColorWrite(true);
  16288. }
  16289. // Opaque
  16290. if (this._opaqueSubMeshes.length !== 0) {
  16291. this._renderOpaque(this._opaqueSubMeshes);
  16292. }
  16293. // Alpha test
  16294. if (this._alphaTestSubMeshes.length !== 0) {
  16295. engine.setAlphaTesting(true);
  16296. this._renderAlphaTest(this._alphaTestSubMeshes);
  16297. engine.setAlphaTesting(false);
  16298. }
  16299. var stencilState = engine.getStencilBuffer();
  16300. engine.setStencilBuffer(false);
  16301. // Sprites
  16302. if (renderSprites) {
  16303. this._renderSprites();
  16304. }
  16305. // Particles
  16306. if (renderParticles) {
  16307. this._renderParticles(activeMeshes);
  16308. }
  16309. if (this.onBeforeTransparentRendering) {
  16310. this.onBeforeTransparentRendering();
  16311. }
  16312. // Transparent
  16313. if (this._transparentSubMeshes.length !== 0) {
  16314. this._renderTransparent(this._transparentSubMeshes);
  16315. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16316. }
  16317. // Set back stencil to false in case it changes before the edge renderer.
  16318. engine.setStencilBuffer(false);
  16319. // Edges
  16320. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16321. this._edgesRenderers.data[edgesRendererIndex].render();
  16322. }
  16323. // Restore Stencil state.
  16324. engine.setStencilBuffer(stencilState);
  16325. };
  16326. /**
  16327. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16328. * @param subMeshes The submeshes to render
  16329. */
  16330. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16331. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16332. };
  16333. /**
  16334. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16335. * @param subMeshes The submeshes to render
  16336. */
  16337. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16338. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16339. };
  16340. /**
  16341. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16342. * @param subMeshes The submeshes to render
  16343. */
  16344. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16345. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  16346. };
  16347. /**
  16348. * Renders the submeshes in a specified order.
  16349. * @param subMeshes The submeshes to sort before render
  16350. * @param sortCompareFn The comparison function use to sort
  16351. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16352. * @param transparent Specifies to activate blending if true
  16353. */
  16354. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  16355. var subIndex = 0;
  16356. var subMesh;
  16357. for (; subIndex < subMeshes.length; subIndex++) {
  16358. subMesh = subMeshes.data[subIndex];
  16359. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16360. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16361. }
  16362. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16363. sortedArray.sort(sortCompareFn);
  16364. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16365. subMesh = sortedArray[subIndex];
  16366. if (transparent) {
  16367. var material = subMesh.getMaterial();
  16368. if (material.needDepthPrePass) {
  16369. var engine = material.getScene().getEngine();
  16370. engine.setColorWrite(false);
  16371. engine.setAlphaTesting(true);
  16372. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16373. subMesh.render(false);
  16374. engine.setAlphaTesting(false);
  16375. engine.setColorWrite(true);
  16376. }
  16377. }
  16378. subMesh.render(transparent);
  16379. }
  16380. };
  16381. /**
  16382. * Renders the submeshes in the order they were dispatched (no sort applied).
  16383. * @param subMeshes The submeshes to render
  16384. */
  16385. RenderingGroup.renderUnsorted = function (subMeshes) {
  16386. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16387. var submesh = subMeshes.data[subIndex];
  16388. submesh.render(false);
  16389. }
  16390. };
  16391. /**
  16392. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16393. * are rendered back to front if in the same alpha index.
  16394. *
  16395. * @param a The first submesh
  16396. * @param b The second submesh
  16397. * @returns The result of the comparison
  16398. */
  16399. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16400. // Alpha index first
  16401. if (a._alphaIndex > b._alphaIndex) {
  16402. return 1;
  16403. }
  16404. if (a._alphaIndex < b._alphaIndex) {
  16405. return -1;
  16406. }
  16407. // Then distance to camera
  16408. return RenderingGroup.backToFrontSortCompare(a, b);
  16409. };
  16410. /**
  16411. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16412. * are rendered back to front.
  16413. *
  16414. * @param a The first submesh
  16415. * @param b The second submesh
  16416. * @returns The result of the comparison
  16417. */
  16418. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16419. // Then distance to camera
  16420. if (a._distanceToCamera < b._distanceToCamera) {
  16421. return 1;
  16422. }
  16423. if (a._distanceToCamera > b._distanceToCamera) {
  16424. return -1;
  16425. }
  16426. return 0;
  16427. };
  16428. /**
  16429. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16430. * are rendered front to back (prevent overdraw).
  16431. *
  16432. * @param a The first submesh
  16433. * @param b The second submesh
  16434. * @returns The result of the comparison
  16435. */
  16436. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16437. // Then distance to camera
  16438. if (a._distanceToCamera < b._distanceToCamera) {
  16439. return -1;
  16440. }
  16441. if (a._distanceToCamera > b._distanceToCamera) {
  16442. return 1;
  16443. }
  16444. return 0;
  16445. };
  16446. /**
  16447. * Resets the different lists of submeshes to prepare a new frame.
  16448. */
  16449. RenderingGroup.prototype.prepare = function () {
  16450. this._opaqueSubMeshes.reset();
  16451. this._transparentSubMeshes.reset();
  16452. this._alphaTestSubMeshes.reset();
  16453. this._depthOnlySubMeshes.reset();
  16454. this._particleSystems.reset();
  16455. this._spriteManagers.reset();
  16456. this._edgesRenderers.reset();
  16457. };
  16458. RenderingGroup.prototype.dispose = function () {
  16459. this._opaqueSubMeshes.dispose();
  16460. this._transparentSubMeshes.dispose();
  16461. this._alphaTestSubMeshes.dispose();
  16462. this._depthOnlySubMeshes.dispose();
  16463. this._particleSystems.dispose();
  16464. this._spriteManagers.dispose();
  16465. this._edgesRenderers.dispose();
  16466. };
  16467. /**
  16468. * Inserts the submesh in its correct queue depending on its material.
  16469. * @param subMesh The submesh to dispatch
  16470. */
  16471. RenderingGroup.prototype.dispatch = function (subMesh) {
  16472. var material = subMesh.getMaterial();
  16473. var mesh = subMesh.getMesh();
  16474. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16475. this._transparentSubMeshes.push(subMesh);
  16476. }
  16477. else if (material.needAlphaTesting()) {
  16478. if (material.needDepthPrePass) {
  16479. this._depthOnlySubMeshes.push(subMesh);
  16480. }
  16481. this._alphaTestSubMeshes.push(subMesh);
  16482. }
  16483. else {
  16484. if (material.needDepthPrePass) {
  16485. this._depthOnlySubMeshes.push(subMesh);
  16486. }
  16487. this._opaqueSubMeshes.push(subMesh); // Opaque
  16488. }
  16489. if (mesh._edgesRenderer) {
  16490. this._edgesRenderers.push(mesh._edgesRenderer);
  16491. }
  16492. };
  16493. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  16494. this._spriteManagers.push(spriteManager);
  16495. };
  16496. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  16497. this._particleSystems.push(particleSystem);
  16498. };
  16499. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  16500. if (this._particleSystems.length === 0) {
  16501. return;
  16502. }
  16503. // Particles
  16504. var activeCamera = this._scene.activeCamera;
  16505. this._scene._particlesDuration.beginMonitoring();
  16506. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  16507. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16508. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16509. continue;
  16510. }
  16511. var emitter = particleSystem.emitter;
  16512. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  16513. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16514. }
  16515. }
  16516. this._scene._particlesDuration.endMonitoring(false);
  16517. };
  16518. RenderingGroup.prototype._renderSprites = function () {
  16519. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  16520. return;
  16521. }
  16522. // Sprites
  16523. var activeCamera = this._scene.activeCamera;
  16524. this._scene._spritesDuration.beginMonitoring();
  16525. for (var id = 0; id < this._spriteManagers.length; id++) {
  16526. var spriteManager = this._spriteManagers.data[id];
  16527. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16528. spriteManager.render();
  16529. }
  16530. }
  16531. this._scene._spritesDuration.endMonitoring(false);
  16532. };
  16533. return RenderingGroup;
  16534. }());
  16535. BABYLON.RenderingGroup = RenderingGroup;
  16536. })(BABYLON || (BABYLON = {}));
  16537. //# sourceMappingURL=babylon.renderingGroup.js.map
  16538. var BABYLON;
  16539. (function (BABYLON) {
  16540. var ClickInfo = (function () {
  16541. function ClickInfo() {
  16542. this._singleClick = false;
  16543. this._doubleClick = false;
  16544. this._hasSwiped = false;
  16545. this._ignore = false;
  16546. }
  16547. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  16548. get: function () {
  16549. return this._singleClick;
  16550. },
  16551. set: function (b) {
  16552. this._singleClick = b;
  16553. },
  16554. enumerable: true,
  16555. configurable: true
  16556. });
  16557. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  16558. get: function () {
  16559. return this._doubleClick;
  16560. },
  16561. set: function (b) {
  16562. this._doubleClick = b;
  16563. },
  16564. enumerable: true,
  16565. configurable: true
  16566. });
  16567. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  16568. get: function () {
  16569. return this._hasSwiped;
  16570. },
  16571. set: function (b) {
  16572. this._hasSwiped = b;
  16573. },
  16574. enumerable: true,
  16575. configurable: true
  16576. });
  16577. Object.defineProperty(ClickInfo.prototype, "ignore", {
  16578. get: function () {
  16579. return this._ignore;
  16580. },
  16581. set: function (b) {
  16582. this._ignore = b;
  16583. },
  16584. enumerable: true,
  16585. configurable: true
  16586. });
  16587. return ClickInfo;
  16588. }());
  16589. /**
  16590. * This class is used by the onRenderingGroupObservable
  16591. */
  16592. var RenderingGroupInfo = (function () {
  16593. function RenderingGroupInfo() {
  16594. }
  16595. /**
  16596. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16597. * This stage will be fired no matter what
  16598. */
  16599. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16600. /**
  16601. * Called before opaque object are rendered.
  16602. * This stage will be fired only if there's 3D Opaque content to render
  16603. */
  16604. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16605. /**
  16606. * Called after the opaque objects are rendered and before the transparent ones
  16607. * This stage will be fired only if there's 3D transparent content to render
  16608. */
  16609. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16610. /**
  16611. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16612. * This stage will be fired no matter what
  16613. */
  16614. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16615. return RenderingGroupInfo;
  16616. }());
  16617. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16618. /**
  16619. * Represents a scene to be rendered by the engine.
  16620. * @see http://doc.babylonjs.com/page.php?p=21911
  16621. */
  16622. var Scene = (function () {
  16623. /**
  16624. * @constructor
  16625. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16626. */
  16627. function Scene(engine) {
  16628. // Members
  16629. this.autoClear = true;
  16630. this.autoClearDepthAndStencil = true;
  16631. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  16632. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16633. this.forceWireframe = false;
  16634. this._forcePointsCloud = false;
  16635. this.forceShowBoundingBoxes = false;
  16636. this.animationsEnabled = true;
  16637. this.constantlyUpdateMeshUnderPointer = false;
  16638. this.hoverCursor = "pointer";
  16639. this.defaultCursor = "";
  16640. // Metadata
  16641. this.metadata = null;
  16642. /**
  16643. * An event triggered when the scene is disposed.
  16644. * @type {BABYLON.Observable}
  16645. */
  16646. this.onDisposeObservable = new BABYLON.Observable();
  16647. /**
  16648. * An event triggered before rendering the scene
  16649. * @type {BABYLON.Observable}
  16650. */
  16651. this.onBeforeRenderObservable = new BABYLON.Observable();
  16652. /**
  16653. * An event triggered after rendering the scene
  16654. * @type {BABYLON.Observable}
  16655. */
  16656. this.onAfterRenderObservable = new BABYLON.Observable();
  16657. /**
  16658. * An event triggered when the scene is ready
  16659. * @type {BABYLON.Observable}
  16660. */
  16661. this.onReadyObservable = new BABYLON.Observable();
  16662. /**
  16663. * An event triggered before rendering a camera
  16664. * @type {BABYLON.Observable}
  16665. */
  16666. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16667. /**
  16668. * An event triggered after rendering a camera
  16669. * @type {BABYLON.Observable}
  16670. */
  16671. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16672. /**
  16673. * An event triggered when a camera is created
  16674. * @type {BABYLON.Observable}
  16675. */
  16676. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16677. /**
  16678. * An event triggered when a camera is removed
  16679. * @type {BABYLON.Observable}
  16680. */
  16681. this.onCameraRemovedObservable = new BABYLON.Observable();
  16682. /**
  16683. * An event triggered when a light is created
  16684. * @type {BABYLON.Observable}
  16685. */
  16686. this.onNewLightAddedObservable = new BABYLON.Observable();
  16687. /**
  16688. * An event triggered when a light is removed
  16689. * @type {BABYLON.Observable}
  16690. */
  16691. this.onLightRemovedObservable = new BABYLON.Observable();
  16692. /**
  16693. * An event triggered when a geometry is created
  16694. * @type {BABYLON.Observable}
  16695. */
  16696. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16697. /**
  16698. * An event triggered when a geometry is removed
  16699. * @type {BABYLON.Observable}
  16700. */
  16701. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16702. /**
  16703. * An event triggered when a mesh is created
  16704. * @type {BABYLON.Observable}
  16705. */
  16706. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16707. /**
  16708. * An event triggered when a mesh is removed
  16709. * @type {BABYLON.Observable}
  16710. */
  16711. this.onMeshRemovedObservable = new BABYLON.Observable();
  16712. /**
  16713. * An event triggered before calculating deterministic simulation step
  16714. * @type {BABYLON.Observable}
  16715. */
  16716. this.onBeforeStepObservable = new BABYLON.Observable();
  16717. /**
  16718. * An event triggered after calculating deterministic simulation step
  16719. * @type {BABYLON.Observable}
  16720. */
  16721. this.onAfterStepObservable = new BABYLON.Observable();
  16722. /**
  16723. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16724. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16725. * 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)
  16726. */
  16727. this.onRenderingGroupObservable = new BABYLON.Observable();
  16728. // Animations
  16729. this.animations = [];
  16730. /**
  16731. * 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).
  16732. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  16733. */
  16734. this.onPrePointerObservable = new BABYLON.Observable();
  16735. /**
  16736. * Observable event triggered each time an input event is received from the rendering canvas
  16737. */
  16738. this.onPointerObservable = new BABYLON.Observable();
  16739. this._meshPickProceed = false;
  16740. this._previousHasSwiped = false;
  16741. this._currentPickResult = null;
  16742. this._previousPickResult = null;
  16743. this._totalPointersPressed = 0;
  16744. this._doubleClickOccured = false;
  16745. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  16746. this.cameraToUseForPointers = null;
  16747. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16748. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  16749. this._startingPointerTime = 0;
  16750. this._previousStartingPointerTime = 0;
  16751. // Deterministic lockstep
  16752. this._timeAccumulator = 0;
  16753. this._currentStepId = 0;
  16754. this._currentInternalStep = 0;
  16755. // Keyboard
  16756. /**
  16757. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  16758. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  16759. */
  16760. this.onPreKeyboardObservable = new BABYLON.Observable();
  16761. /**
  16762. * Observable event triggered each time an keyboard event is received from the hosting window
  16763. */
  16764. this.onKeyboardObservable = new BABYLON.Observable();
  16765. // Coordinate system
  16766. /**
  16767. * use right-handed coordinate system on this scene.
  16768. * @type {boolean}
  16769. */
  16770. this._useRightHandedSystem = false;
  16771. // Fog
  16772. this._fogEnabled = true;
  16773. this._fogMode = Scene.FOGMODE_NONE;
  16774. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16775. this.fogDensity = 0.1;
  16776. this.fogStart = 0;
  16777. this.fogEnd = 1000.0;
  16778. // Lights
  16779. /**
  16780. * is shadow enabled on this scene.
  16781. * @type {boolean}
  16782. */
  16783. this._shadowsEnabled = true;
  16784. /**
  16785. * is light enabled on this scene.
  16786. * @type {boolean}
  16787. */
  16788. this._lightsEnabled = true;
  16789. /**
  16790. * All of the lights added to this scene.
  16791. * @see BABYLON.Light
  16792. * @type {BABYLON.Light[]}
  16793. */
  16794. this.lights = new Array();
  16795. // Cameras
  16796. /** All of the cameras added to this scene. */
  16797. this.cameras = new Array();
  16798. /** All of the active cameras added to this scene. */
  16799. this.activeCameras = new Array();
  16800. // Meshes
  16801. /**
  16802. * All of the (abstract) meshes added to this scene.
  16803. * @see BABYLON.AbstractMesh
  16804. * @type {BABYLON.AbstractMesh[]}
  16805. */
  16806. this.meshes = new Array();
  16807. // Geometries
  16808. this._geometries = new Array();
  16809. this.materials = new Array();
  16810. this.multiMaterials = new Array();
  16811. // Textures
  16812. this._texturesEnabled = true;
  16813. this.textures = new Array();
  16814. // Particles
  16815. this.particlesEnabled = true;
  16816. this.particleSystems = new Array();
  16817. // Sprites
  16818. this.spritesEnabled = true;
  16819. this.spriteManagers = new Array();
  16820. // Layers
  16821. this.layers = new Array();
  16822. this.highlightLayers = new Array();
  16823. // Skeletons
  16824. this._skeletonsEnabled = true;
  16825. this.skeletons = new Array();
  16826. // Morph targets
  16827. this.morphTargetManagers = new Array();
  16828. // Lens flares
  16829. this.lensFlaresEnabled = true;
  16830. this.lensFlareSystems = new Array();
  16831. // Collisions
  16832. this.collisionsEnabled = true;
  16833. /** Defines the gravity applied to this scene */
  16834. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16835. // Postprocesses
  16836. this.postProcesses = new Array();
  16837. this.postProcessesEnabled = true;
  16838. // Customs render targets
  16839. this.renderTargetsEnabled = true;
  16840. this.dumpNextRenderTargets = false;
  16841. this.customRenderTargets = new Array();
  16842. // Imported meshes
  16843. this.importedMeshesFiles = new Array();
  16844. // Probes
  16845. this.probesEnabled = true;
  16846. this.reflectionProbes = new Array();
  16847. this._actionManagers = new Array();
  16848. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16849. // Procedural textures
  16850. this.proceduralTexturesEnabled = true;
  16851. this._proceduralTextures = new Array();
  16852. this.soundTracks = new Array();
  16853. this._audioEnabled = true;
  16854. this._headphone = false;
  16855. // Performance counters
  16856. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16857. this._totalLightsCounter = new BABYLON.PerfCounter();
  16858. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16859. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16860. this._totalVertices = new BABYLON.PerfCounter();
  16861. this._activeIndices = new BABYLON.PerfCounter();
  16862. this._activeParticles = new BABYLON.PerfCounter();
  16863. this._interFrameDuration = new BABYLON.PerfCounter();
  16864. this._lastFrameDuration = new BABYLON.PerfCounter();
  16865. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16866. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16867. this._particlesDuration = new BABYLON.PerfCounter();
  16868. this._renderDuration = new BABYLON.PerfCounter();
  16869. this._spritesDuration = new BABYLON.PerfCounter();
  16870. this._activeBones = new BABYLON.PerfCounter();
  16871. this._animationTime = 0;
  16872. this.animationTimeScale = 1;
  16873. this._renderId = 0;
  16874. this._executeWhenReadyTimeoutId = -1;
  16875. this._intermediateRendering = false;
  16876. this._viewUpdateFlag = -1;
  16877. this._projectionUpdateFlag = -1;
  16878. this._alternateViewUpdateFlag = -1;
  16879. this._alternateProjectionUpdateFlag = -1;
  16880. this._toBeDisposed = new BABYLON.SmartArray(256);
  16881. this._pendingData = new Array();
  16882. this._activeMeshes = new BABYLON.SmartArray(256);
  16883. this._processedMaterials = new BABYLON.SmartArray(256);
  16884. this._renderTargets = new BABYLON.SmartArray(256);
  16885. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16886. this._activeSkeletons = new BABYLON.SmartArray(32);
  16887. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16888. this._activeAnimatables = new Array();
  16889. this._transformMatrix = BABYLON.Matrix.Zero();
  16890. this._useAlternateCameraConfiguration = false;
  16891. this._alternateRendering = false;
  16892. this.requireLightSorting = false;
  16893. this._activeMeshesFrozen = false;
  16894. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  16895. this._engine.scenes.push(this);
  16896. this._uid = null;
  16897. this._renderingManager = new BABYLON.RenderingManager(this);
  16898. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16899. if (BABYLON.OutlineRenderer) {
  16900. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16901. }
  16902. if (BABYLON.Tools.IsWindowObjectExist()) {
  16903. this.attachControl();
  16904. }
  16905. //simplification queue
  16906. if (BABYLON.SimplificationQueue) {
  16907. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16908. }
  16909. //collision coordinator initialization. For now legacy per default.
  16910. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16911. // Uniform Buffer
  16912. this._createUbo();
  16913. // Default Image processing definition.
  16914. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  16915. }
  16916. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16917. /** The fog is deactivated */
  16918. get: function () {
  16919. return Scene._FOGMODE_NONE;
  16920. },
  16921. enumerable: true,
  16922. configurable: true
  16923. });
  16924. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16925. /** The fog density is following an exponential function */
  16926. get: function () {
  16927. return Scene._FOGMODE_EXP;
  16928. },
  16929. enumerable: true,
  16930. configurable: true
  16931. });
  16932. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16933. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  16934. get: function () {
  16935. return Scene._FOGMODE_EXP2;
  16936. },
  16937. enumerable: true,
  16938. configurable: true
  16939. });
  16940. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16941. /** The fog density is following a linear function. */
  16942. get: function () {
  16943. return Scene._FOGMODE_LINEAR;
  16944. },
  16945. enumerable: true,
  16946. configurable: true
  16947. });
  16948. Object.defineProperty(Scene.prototype, "environmentTexture", {
  16949. /**
  16950. * Texture used in all pbr material as the reflection texture.
  16951. * As in the majority of the scene they are the same (exception for multi room and so on),
  16952. * this is easier to reference from here than from all the materials.
  16953. */
  16954. get: function () {
  16955. return this._environmentTexture;
  16956. },
  16957. /**
  16958. * Texture used in all pbr material as the reflection texture.
  16959. * As in the majority of the scene they are the same (exception for multi room and so on),
  16960. * this is easier to set here than in all the materials.
  16961. */
  16962. set: function (value) {
  16963. this._environmentTexture = value;
  16964. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16965. },
  16966. enumerable: true,
  16967. configurable: true
  16968. });
  16969. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  16970. /**
  16971. * Default image processing configuration used either in the rendering
  16972. * Forward main pass or through the imageProcessingPostProcess if present.
  16973. * As in the majority of the scene they are the same (exception for multi camera),
  16974. * this is easier to reference from here than from all the materials and post process.
  16975. *
  16976. * No setter as we it is a shared configuration, you can set the values instead.
  16977. */
  16978. get: function () {
  16979. return this._imageProcessingConfiguration;
  16980. },
  16981. enumerable: true,
  16982. configurable: true
  16983. });
  16984. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  16985. get: function () {
  16986. return this._forcePointsCloud;
  16987. },
  16988. set: function (value) {
  16989. if (this._forcePointsCloud === value) {
  16990. return;
  16991. }
  16992. this._forcePointsCloud = value;
  16993. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16994. },
  16995. enumerable: true,
  16996. configurable: true
  16997. });
  16998. Object.defineProperty(Scene.prototype, "onDispose", {
  16999. /** A function to be executed when this scene is disposed. */
  17000. set: function (callback) {
  17001. if (this._onDisposeObserver) {
  17002. this.onDisposeObservable.remove(this._onDisposeObserver);
  17003. }
  17004. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17005. },
  17006. enumerable: true,
  17007. configurable: true
  17008. });
  17009. Object.defineProperty(Scene.prototype, "beforeRender", {
  17010. /** A function to be executed before rendering this scene */
  17011. set: function (callback) {
  17012. if (this._onBeforeRenderObserver) {
  17013. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  17014. }
  17015. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  17016. },
  17017. enumerable: true,
  17018. configurable: true
  17019. });
  17020. Object.defineProperty(Scene.prototype, "afterRender", {
  17021. /** A function to be executed after rendering this scene */
  17022. set: function (callback) {
  17023. if (this._onAfterRenderObserver) {
  17024. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  17025. }
  17026. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  17027. },
  17028. enumerable: true,
  17029. configurable: true
  17030. });
  17031. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  17032. set: function (callback) {
  17033. if (this._onBeforeCameraRenderObserver) {
  17034. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  17035. }
  17036. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  17037. },
  17038. enumerable: true,
  17039. configurable: true
  17040. });
  17041. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  17042. set: function (callback) {
  17043. if (this._onAfterCameraRenderObserver) {
  17044. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  17045. }
  17046. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  17047. },
  17048. enumerable: true,
  17049. configurable: true
  17050. });
  17051. Object.defineProperty(Scene.prototype, "gamepadManager", {
  17052. get: function () {
  17053. if (!this._gamepadManager) {
  17054. this._gamepadManager = new BABYLON.GamepadManager();
  17055. }
  17056. return this._gamepadManager;
  17057. },
  17058. enumerable: true,
  17059. configurable: true
  17060. });
  17061. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  17062. get: function () {
  17063. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  17064. },
  17065. enumerable: true,
  17066. configurable: true
  17067. });
  17068. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  17069. get: function () {
  17070. return this._useRightHandedSystem;
  17071. },
  17072. set: function (value) {
  17073. if (this._useRightHandedSystem === value) {
  17074. return;
  17075. }
  17076. this._useRightHandedSystem = value;
  17077. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17078. },
  17079. enumerable: true,
  17080. configurable: true
  17081. });
  17082. Scene.prototype.setStepId = function (newStepId) {
  17083. this._currentStepId = newStepId;
  17084. };
  17085. ;
  17086. Scene.prototype.getStepId = function () {
  17087. return this._currentStepId;
  17088. };
  17089. ;
  17090. Scene.prototype.getInternalStep = function () {
  17091. return this._currentInternalStep;
  17092. };
  17093. ;
  17094. Object.defineProperty(Scene.prototype, "fogEnabled", {
  17095. get: function () {
  17096. return this._fogEnabled;
  17097. },
  17098. /**
  17099. * is fog enabled on this scene.
  17100. */
  17101. set: function (value) {
  17102. if (this._fogEnabled === value) {
  17103. return;
  17104. }
  17105. this._fogEnabled = value;
  17106. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17107. },
  17108. enumerable: true,
  17109. configurable: true
  17110. });
  17111. Object.defineProperty(Scene.prototype, "fogMode", {
  17112. get: function () {
  17113. return this._fogMode;
  17114. },
  17115. set: function (value) {
  17116. if (this._fogMode === value) {
  17117. return;
  17118. }
  17119. this._fogMode = value;
  17120. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17121. },
  17122. enumerable: true,
  17123. configurable: true
  17124. });
  17125. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  17126. get: function () {
  17127. return this._shadowsEnabled;
  17128. },
  17129. set: function (value) {
  17130. if (this._shadowsEnabled === value) {
  17131. return;
  17132. }
  17133. this._shadowsEnabled = value;
  17134. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17135. },
  17136. enumerable: true,
  17137. configurable: true
  17138. });
  17139. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  17140. get: function () {
  17141. return this._lightsEnabled;
  17142. },
  17143. set: function (value) {
  17144. if (this._lightsEnabled === value) {
  17145. return;
  17146. }
  17147. this._lightsEnabled = value;
  17148. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17149. },
  17150. enumerable: true,
  17151. configurable: true
  17152. });
  17153. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  17154. /** The default material used on meshes when no material is affected */
  17155. get: function () {
  17156. if (!this._defaultMaterial) {
  17157. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  17158. }
  17159. return this._defaultMaterial;
  17160. },
  17161. /** The default material used on meshes when no material is affected */
  17162. set: function (value) {
  17163. this._defaultMaterial = value;
  17164. },
  17165. enumerable: true,
  17166. configurable: true
  17167. });
  17168. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  17169. get: function () {
  17170. return this._texturesEnabled;
  17171. },
  17172. set: function (value) {
  17173. if (this._texturesEnabled === value) {
  17174. return;
  17175. }
  17176. this._texturesEnabled = value;
  17177. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17178. },
  17179. enumerable: true,
  17180. configurable: true
  17181. });
  17182. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  17183. get: function () {
  17184. return this._skeletonsEnabled;
  17185. },
  17186. set: function (value) {
  17187. if (this._skeletonsEnabled === value) {
  17188. return;
  17189. }
  17190. this._skeletonsEnabled = value;
  17191. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  17192. },
  17193. enumerable: true,
  17194. configurable: true
  17195. });
  17196. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  17197. get: function () {
  17198. if (!this._postProcessRenderPipelineManager) {
  17199. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  17200. }
  17201. return this._postProcessRenderPipelineManager;
  17202. },
  17203. enumerable: true,
  17204. configurable: true
  17205. });
  17206. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  17207. get: function () {
  17208. if (!this._mainSoundTrack) {
  17209. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  17210. }
  17211. return this._mainSoundTrack;
  17212. },
  17213. enumerable: true,
  17214. configurable: true
  17215. });
  17216. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  17217. get: function () {
  17218. return this._alternateRendering;
  17219. },
  17220. enumerable: true,
  17221. configurable: true
  17222. });
  17223. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  17224. get: function () {
  17225. return this._frustumPlanes;
  17226. },
  17227. enumerable: true,
  17228. configurable: true
  17229. });
  17230. Object.defineProperty(Scene.prototype, "debugLayer", {
  17231. // Properties
  17232. get: function () {
  17233. if (!this._debugLayer) {
  17234. this._debugLayer = new BABYLON.DebugLayer(this);
  17235. }
  17236. return this._debugLayer;
  17237. },
  17238. enumerable: true,
  17239. configurable: true
  17240. });
  17241. Object.defineProperty(Scene.prototype, "workerCollisions", {
  17242. get: function () {
  17243. return this._workerCollisions;
  17244. },
  17245. set: function (enabled) {
  17246. if (!BABYLON.CollisionCoordinatorLegacy) {
  17247. return;
  17248. }
  17249. enabled = (enabled && !!Worker);
  17250. this._workerCollisions = enabled;
  17251. if (this.collisionCoordinator) {
  17252. this.collisionCoordinator.destroy();
  17253. }
  17254. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  17255. this.collisionCoordinator.init(this);
  17256. },
  17257. enumerable: true,
  17258. configurable: true
  17259. });
  17260. Object.defineProperty(Scene.prototype, "selectionOctree", {
  17261. get: function () {
  17262. return this._selectionOctree;
  17263. },
  17264. enumerable: true,
  17265. configurable: true
  17266. });
  17267. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  17268. /**
  17269. * The mesh that is currently under the pointer.
  17270. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  17271. */
  17272. get: function () {
  17273. return this._pointerOverMesh;
  17274. },
  17275. enumerable: true,
  17276. configurable: true
  17277. });
  17278. Object.defineProperty(Scene.prototype, "pointerX", {
  17279. /**
  17280. * Current on-screen X position of the pointer
  17281. * @return {number} X position of the pointer
  17282. */
  17283. get: function () {
  17284. return this._pointerX;
  17285. },
  17286. enumerable: true,
  17287. configurable: true
  17288. });
  17289. Object.defineProperty(Scene.prototype, "pointerY", {
  17290. /**
  17291. * Current on-screen Y position of the pointer
  17292. * @return {number} Y position of the pointer
  17293. */
  17294. get: function () {
  17295. return this._pointerY;
  17296. },
  17297. enumerable: true,
  17298. configurable: true
  17299. });
  17300. Scene.prototype.getCachedMaterial = function () {
  17301. return this._cachedMaterial;
  17302. };
  17303. Scene.prototype.getCachedEffect = function () {
  17304. return this._cachedEffect;
  17305. };
  17306. Scene.prototype.getCachedVisibility = function () {
  17307. return this._cachedVisibility;
  17308. };
  17309. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  17310. if (visibility === void 0) { visibility = 1; }
  17311. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  17312. };
  17313. Scene.prototype.getBoundingBoxRenderer = function () {
  17314. if (!this._boundingBoxRenderer) {
  17315. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  17316. }
  17317. return this._boundingBoxRenderer;
  17318. };
  17319. Scene.prototype.getOutlineRenderer = function () {
  17320. return this._outlineRenderer;
  17321. };
  17322. Scene.prototype.getEngine = function () {
  17323. return this._engine;
  17324. };
  17325. Scene.prototype.getTotalVertices = function () {
  17326. return this._totalVertices.current;
  17327. };
  17328. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17329. get: function () {
  17330. return this._totalVertices;
  17331. },
  17332. enumerable: true,
  17333. configurable: true
  17334. });
  17335. Scene.prototype.getActiveIndices = function () {
  17336. return this._activeIndices.current;
  17337. };
  17338. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17339. get: function () {
  17340. return this._activeIndices;
  17341. },
  17342. enumerable: true,
  17343. configurable: true
  17344. });
  17345. Scene.prototype.getActiveParticles = function () {
  17346. return this._activeParticles.current;
  17347. };
  17348. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17349. get: function () {
  17350. return this._activeParticles;
  17351. },
  17352. enumerable: true,
  17353. configurable: true
  17354. });
  17355. Scene.prototype.getActiveBones = function () {
  17356. return this._activeBones.current;
  17357. };
  17358. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17359. get: function () {
  17360. return this._activeBones;
  17361. },
  17362. enumerable: true,
  17363. configurable: true
  17364. });
  17365. // Stats
  17366. Scene.prototype.getInterFramePerfCounter = function () {
  17367. return this._interFrameDuration.current;
  17368. };
  17369. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  17370. get: function () {
  17371. return this._interFrameDuration;
  17372. },
  17373. enumerable: true,
  17374. configurable: true
  17375. });
  17376. Scene.prototype.getLastFrameDuration = function () {
  17377. return this._lastFrameDuration.current;
  17378. };
  17379. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  17380. get: function () {
  17381. return this._lastFrameDuration;
  17382. },
  17383. enumerable: true,
  17384. configurable: true
  17385. });
  17386. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  17387. return this._evaluateActiveMeshesDuration.current;
  17388. };
  17389. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  17390. get: function () {
  17391. return this._evaluateActiveMeshesDuration;
  17392. },
  17393. enumerable: true,
  17394. configurable: true
  17395. });
  17396. Scene.prototype.getActiveMeshes = function () {
  17397. return this._activeMeshes;
  17398. };
  17399. Scene.prototype.getRenderTargetsDuration = function () {
  17400. return this._renderTargetsDuration.current;
  17401. };
  17402. Scene.prototype.getRenderDuration = function () {
  17403. return this._renderDuration.current;
  17404. };
  17405. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  17406. get: function () {
  17407. return this._renderDuration;
  17408. },
  17409. enumerable: true,
  17410. configurable: true
  17411. });
  17412. Scene.prototype.getParticlesDuration = function () {
  17413. return this._particlesDuration.current;
  17414. };
  17415. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17416. get: function () {
  17417. return this._particlesDuration;
  17418. },
  17419. enumerable: true,
  17420. configurable: true
  17421. });
  17422. Scene.prototype.getSpritesDuration = function () {
  17423. return this._spritesDuration.current;
  17424. };
  17425. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17426. get: function () {
  17427. return this._spritesDuration;
  17428. },
  17429. enumerable: true,
  17430. configurable: true
  17431. });
  17432. Scene.prototype.getAnimationRatio = function () {
  17433. return this._animationRatio;
  17434. };
  17435. Scene.prototype.getRenderId = function () {
  17436. return this._renderId;
  17437. };
  17438. Scene.prototype.incrementRenderId = function () {
  17439. this._renderId++;
  17440. };
  17441. Scene.prototype._updatePointerPosition = function (evt) {
  17442. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17443. this._pointerX = evt.clientX - canvasRect.left;
  17444. this._pointerY = evt.clientY - canvasRect.top;
  17445. this._unTranslatedPointerX = this._pointerX;
  17446. this._unTranslatedPointerY = this._pointerY;
  17447. };
  17448. Scene.prototype._createUbo = function () {
  17449. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  17450. this._sceneUbo.addUniform("viewProjection", 16);
  17451. this._sceneUbo.addUniform("view", 16);
  17452. };
  17453. Scene.prototype._createAlternateUbo = function () {
  17454. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  17455. this._alternateSceneUbo.addUniform("viewProjection", 16);
  17456. this._alternateSceneUbo.addUniform("view", 16);
  17457. };
  17458. // Pointers handling
  17459. /**
  17460. * Use this method to simulate a pointer move on a mesh
  17461. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17462. */
  17463. Scene.prototype.simulatePointerMove = function (pickResult) {
  17464. var evt = new PointerEvent("pointermove");
  17465. return this._processPointerMove(pickResult, evt);
  17466. };
  17467. Scene.prototype._processPointerMove = function (pickResult, evt) {
  17468. var canvas = this._engine.getRenderingCanvas();
  17469. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17470. this.setPointerOverSprite(null);
  17471. this.setPointerOverMesh(pickResult.pickedMesh);
  17472. if (this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17473. if (this._pointerOverMesh.actionManager.hoverCursor) {
  17474. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  17475. }
  17476. else {
  17477. canvas.style.cursor = this.hoverCursor;
  17478. }
  17479. }
  17480. else {
  17481. canvas.style.cursor = this.defaultCursor;
  17482. }
  17483. }
  17484. else {
  17485. this.setPointerOverMesh(null);
  17486. // Sprites
  17487. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers);
  17488. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17489. this.setPointerOverSprite(pickResult.pickedSprite);
  17490. if (this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  17491. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  17492. }
  17493. else {
  17494. canvas.style.cursor = this.hoverCursor;
  17495. }
  17496. }
  17497. else {
  17498. this.setPointerOverSprite(null);
  17499. // Restore pointer
  17500. canvas.style.cursor = this.defaultCursor;
  17501. }
  17502. }
  17503. if (this.onPointerMove) {
  17504. this.onPointerMove(evt, pickResult);
  17505. }
  17506. if (this.onPointerObservable.hasObservers()) {
  17507. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17508. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17509. this.onPointerObservable.notifyObservers(pi, type);
  17510. }
  17511. return this;
  17512. };
  17513. /**
  17514. * Use this method to simulate a pointer down on a mesh
  17515. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17516. */
  17517. Scene.prototype.simulatePointerDown = function (pickResult) {
  17518. var evt = new PointerEvent("pointerdown");
  17519. return this._processPointerDown(pickResult, evt);
  17520. };
  17521. Scene.prototype._processPointerDown = function (pickResult, evt) {
  17522. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17523. this._pickedDownMesh = pickResult.pickedMesh;
  17524. var actionManager = pickResult.pickedMesh.actionManager;
  17525. if (actionManager) {
  17526. if (actionManager.hasPickTriggers) {
  17527. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17528. switch (evt.button) {
  17529. case 0:
  17530. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17531. break;
  17532. case 1:
  17533. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17534. break;
  17535. case 2:
  17536. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17537. break;
  17538. }
  17539. }
  17540. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17541. window.setTimeout((function () {
  17542. var _this = this;
  17543. 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);
  17544. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17545. if (this._totalPointersPressed !== 0 &&
  17546. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  17547. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  17548. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  17549. this._startingPointerTime = 0;
  17550. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17551. }
  17552. }
  17553. }).bind(this), Scene.LongPressDelay);
  17554. }
  17555. }
  17556. }
  17557. if (this.onPointerDown) {
  17558. this.onPointerDown(evt, pickResult);
  17559. }
  17560. if (this.onPointerObservable.hasObservers()) {
  17561. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  17562. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17563. this.onPointerObservable.notifyObservers(pi, type);
  17564. }
  17565. return this;
  17566. };
  17567. /**
  17568. * Use this method to simulate a pointer up on a mesh
  17569. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  17570. */
  17571. Scene.prototype.simulatePointerUp = function (pickResult) {
  17572. var evt = new PointerEvent("pointerup");
  17573. var clickInfo = new ClickInfo();
  17574. clickInfo.singleClick = true;
  17575. return this._processPointerUp(pickResult, evt, clickInfo);
  17576. };
  17577. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  17578. if (pickResult && pickResult && pickResult.pickedMesh) {
  17579. this._pickedUpMesh = pickResult.pickedMesh;
  17580. if (this._pickedDownMesh === this._pickedUpMesh) {
  17581. if (this.onPointerPick) {
  17582. this.onPointerPick(evt, pickResult);
  17583. }
  17584. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  17585. var type = BABYLON.PointerEventTypes.POINTERPICK;
  17586. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17587. this.onPointerObservable.notifyObservers(pi, type);
  17588. }
  17589. }
  17590. if (pickResult.pickedMesh.actionManager) {
  17591. if (clickInfo.ignore) {
  17592. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17593. }
  17594. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  17595. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17596. }
  17597. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17598. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17599. }
  17600. }
  17601. }
  17602. if (this._pickedDownMesh &&
  17603. this._pickedDownMesh.actionManager &&
  17604. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  17605. this._pickedDownMesh !== this._pickedUpMesh) {
  17606. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  17607. }
  17608. if (this.onPointerUp) {
  17609. this.onPointerUp(evt, pickResult);
  17610. }
  17611. if (this.onPointerObservable.hasObservers()) {
  17612. if (!clickInfo.ignore) {
  17613. if (!clickInfo.hasSwiped) {
  17614. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  17615. var type = BABYLON.PointerEventTypes.POINTERTAP;
  17616. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17617. this.onPointerObservable.notifyObservers(pi, type);
  17618. }
  17619. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  17620. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  17621. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17622. this.onPointerObservable.notifyObservers(pi, type);
  17623. }
  17624. }
  17625. }
  17626. else {
  17627. var type = BABYLON.PointerEventTypes.POINTERUP;
  17628. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  17629. this.onPointerObservable.notifyObservers(pi, type);
  17630. }
  17631. }
  17632. return this;
  17633. };
  17634. /**
  17635. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17636. * @param attachUp defines if you want to attach events to pointerup
  17637. * @param attachDown defines if you want to attach events to pointerdown
  17638. * @param attachMove defines if you want to attach events to pointermove
  17639. */
  17640. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17641. var _this = this;
  17642. if (attachUp === void 0) { attachUp = true; }
  17643. if (attachDown === void 0) { attachDown = true; }
  17644. if (attachMove === void 0) { attachMove = true; }
  17645. this._initActionManager = function (act, clickInfo) {
  17646. if (!_this._meshPickProceed) {
  17647. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17648. _this._currentPickResult = pickResult;
  17649. if (pickResult) {
  17650. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  17651. }
  17652. _this._meshPickProceed = true;
  17653. }
  17654. return act;
  17655. };
  17656. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  17657. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  17658. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  17659. btn !== _this._previousButtonPressed) {
  17660. _this._doubleClickOccured = false;
  17661. clickInfo.singleClick = true;
  17662. clickInfo.ignore = false;
  17663. cb(clickInfo, _this._currentPickResult);
  17664. }
  17665. };
  17666. this._initClickEvent = function (obs1, obs2, evt, cb) {
  17667. var clickInfo = new ClickInfo();
  17668. _this._currentPickResult = null;
  17669. var act;
  17670. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  17671. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  17672. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17673. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  17674. act = _this._initActionManager(act, clickInfo);
  17675. if (act)
  17676. checkPicking = act.hasPickTriggers;
  17677. }
  17678. if (checkPicking) {
  17679. var btn = evt.button;
  17680. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  17681. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  17682. if (!clickInfo.hasSwiped) {
  17683. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  17684. if (!checkSingleClickImmediately) {
  17685. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  17686. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17687. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17688. act = _this._initActionManager(act, clickInfo);
  17689. if (act)
  17690. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17691. }
  17692. }
  17693. if (checkSingleClickImmediately) {
  17694. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  17695. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  17696. btn !== _this._previousButtonPressed) {
  17697. clickInfo.singleClick = true;
  17698. cb(clickInfo, _this._currentPickResult);
  17699. }
  17700. }
  17701. else {
  17702. // wait that no double click has been raised during the double click delay
  17703. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17704. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  17705. }
  17706. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  17707. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  17708. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17709. act = _this._initActionManager(act, clickInfo);
  17710. if (act)
  17711. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17712. }
  17713. if (checkDoubleClick) {
  17714. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  17715. if (btn === _this._previousButtonPressed &&
  17716. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  17717. !_this._doubleClickOccured) {
  17718. // pointer has not moved for 2 clicks, it's a double click
  17719. if (!clickInfo.hasSwiped &&
  17720. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  17721. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  17722. _this._previousStartingPointerTime = 0;
  17723. _this._doubleClickOccured = true;
  17724. clickInfo.doubleClick = true;
  17725. clickInfo.ignore = false;
  17726. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  17727. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  17728. }
  17729. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17730. cb(clickInfo, _this._currentPickResult);
  17731. }
  17732. else {
  17733. _this._doubleClickOccured = false;
  17734. _this._previousStartingPointerTime = _this._startingPointerTime;
  17735. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17736. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17737. _this._previousButtonPressed = btn;
  17738. _this._previousHasSwiped = clickInfo.hasSwiped;
  17739. if (Scene.ExclusiveDoubleClickMode) {
  17740. if (_this._previousDelayedSimpleClickTimeout) {
  17741. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  17742. }
  17743. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17744. cb(clickInfo, _this._previousPickResult);
  17745. }
  17746. else {
  17747. cb(clickInfo, _this._currentPickResult);
  17748. }
  17749. }
  17750. }
  17751. else {
  17752. _this._doubleClickOccured = false;
  17753. _this._previousStartingPointerTime = _this._startingPointerTime;
  17754. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17755. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17756. _this._previousButtonPressed = btn;
  17757. _this._previousHasSwiped = clickInfo.hasSwiped;
  17758. }
  17759. }
  17760. }
  17761. }
  17762. clickInfo.ignore = true;
  17763. cb(clickInfo, _this._currentPickResult);
  17764. };
  17765. this._spritePredicate = function (sprite) {
  17766. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17767. };
  17768. this._onPointerMove = function (evt) {
  17769. _this._updatePointerPosition(evt);
  17770. // PreObservable support
  17771. if (_this.onPrePointerObservable.hasObservers()) {
  17772. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  17773. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17774. _this.onPrePointerObservable.notifyObservers(pi, type);
  17775. if (pi.skipOnPointerObservable) {
  17776. return;
  17777. }
  17778. }
  17779. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17780. return;
  17781. }
  17782. if (!_this.pointerMovePredicate) {
  17783. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  17784. }
  17785. // Meshes
  17786. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17787. _this._processPointerMove(pickResult, evt);
  17788. };
  17789. this._onPointerDown = function (evt) {
  17790. _this._totalPointersPressed++;
  17791. _this._pickedDownMesh = null;
  17792. _this._meshPickProceed = false;
  17793. _this._updatePointerPosition(evt);
  17794. // PreObservable support
  17795. if (_this.onPrePointerObservable.hasObservers()) {
  17796. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  17797. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17798. _this.onPrePointerObservable.notifyObservers(pi, type);
  17799. if (pi.skipOnPointerObservable) {
  17800. return;
  17801. }
  17802. }
  17803. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17804. return;
  17805. }
  17806. _this._startingPointerPosition.x = _this._pointerX;
  17807. _this._startingPointerPosition.y = _this._pointerY;
  17808. _this._startingPointerTime = new Date().getTime();
  17809. if (!_this.pointerDownPredicate) {
  17810. _this.pointerDownPredicate = function (mesh) {
  17811. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17812. };
  17813. }
  17814. // Meshes
  17815. _this._pickedDownMesh = null;
  17816. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17817. _this._processPointerDown(pickResult, evt);
  17818. // Sprites
  17819. _this._pickedDownSprite = null;
  17820. if (_this.spriteManagers.length > 0) {
  17821. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers);
  17822. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17823. if (pickResult.pickedSprite.actionManager) {
  17824. _this._pickedDownSprite = pickResult.pickedSprite;
  17825. switch (evt.button) {
  17826. case 0:
  17827. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17828. break;
  17829. case 1:
  17830. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17831. break;
  17832. case 2:
  17833. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17834. break;
  17835. }
  17836. if (pickResult.pickedSprite.actionManager) {
  17837. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17838. }
  17839. }
  17840. }
  17841. }
  17842. };
  17843. this._onPointerUp = function (evt) {
  17844. if (_this._totalPointersPressed === 0) {
  17845. return; // So we need to test it the pointer down was pressed before.
  17846. }
  17847. _this._totalPointersPressed--;
  17848. _this._pickedUpMesh = null;
  17849. _this._meshPickProceed = false;
  17850. _this._updatePointerPosition(evt);
  17851. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  17852. // PreObservable support
  17853. if (this.onPrePointerObservable.hasObservers()) {
  17854. if (!clickInfo.ignore) {
  17855. if (!clickInfo.hasSwiped) {
  17856. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  17857. var type = BABYLON.PointerEventTypes.POINTERTAP;
  17858. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17859. this.onPrePointerObservable.notifyObservers(pi, type);
  17860. if (pi.skipOnPointerObservable) {
  17861. return;
  17862. }
  17863. }
  17864. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  17865. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  17866. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17867. this.onPrePointerObservable.notifyObservers(pi, type);
  17868. if (pi.skipOnPointerObservable) {
  17869. return;
  17870. }
  17871. }
  17872. }
  17873. }
  17874. else {
  17875. var type = BABYLON.PointerEventTypes.POINTERUP;
  17876. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17877. this.onPrePointerObservable.notifyObservers(pi, type);
  17878. if (pi.skipOnPointerObservable) {
  17879. return;
  17880. }
  17881. }
  17882. }
  17883. if (!this.cameraToUseForPointers && !this.activeCamera) {
  17884. return;
  17885. }
  17886. if (!this.pointerUpPredicate) {
  17887. this.pointerUpPredicate = function (mesh) {
  17888. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17889. };
  17890. }
  17891. // Meshes
  17892. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  17893. this._initActionManager(null, clickInfo);
  17894. }
  17895. if (!pickResult) {
  17896. pickResult = this._currentPickResult;
  17897. }
  17898. this._processPointerUp(pickResult, evt, clickInfo);
  17899. // Sprites
  17900. if (this.spriteManagers.length > 0) {
  17901. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers);
  17902. if (pickResult.hit && pickResult.pickedSprite) {
  17903. if (pickResult.pickedSprite.actionManager) {
  17904. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17905. if (pickResult.pickedSprite.actionManager) {
  17906. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  17907. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17908. }
  17909. }
  17910. }
  17911. }
  17912. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  17913. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  17914. }
  17915. }
  17916. this._previousPickResult = this._currentPickResult;
  17917. }).bind(_this));
  17918. };
  17919. this._onKeyDown = function (evt) {
  17920. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  17921. if (_this.onPreKeyboardObservable.hasObservers()) {
  17922. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  17923. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  17924. if (pi.skipOnPointerObservable) {
  17925. return;
  17926. }
  17927. }
  17928. if (_this.onKeyboardObservable.hasObservers()) {
  17929. var pi = new BABYLON.KeyboardInfo(type, evt);
  17930. _this.onKeyboardObservable.notifyObservers(pi, type);
  17931. }
  17932. if (_this.actionManager) {
  17933. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17934. }
  17935. };
  17936. this._onKeyUp = function (evt) {
  17937. var type = BABYLON.KeyboardEventTypes.KEYUP;
  17938. if (_this.onPreKeyboardObservable.hasObservers()) {
  17939. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  17940. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  17941. if (pi.skipOnPointerObservable) {
  17942. return;
  17943. }
  17944. }
  17945. if (_this.onKeyboardObservable.hasObservers()) {
  17946. var pi = new BABYLON.KeyboardInfo(type, evt);
  17947. _this.onKeyboardObservable.notifyObservers(pi, type);
  17948. }
  17949. if (_this.actionManager) {
  17950. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17951. }
  17952. };
  17953. var engine = this.getEngine();
  17954. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  17955. canvas.addEventListener("keydown", _this._onKeyDown, false);
  17956. canvas.addEventListener("keyup", _this._onKeyUp, false);
  17957. });
  17958. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  17959. canvas.removeEventListener("keydown", _this._onKeyDown);
  17960. canvas.removeEventListener("keyup", _this._onKeyUp);
  17961. });
  17962. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17963. var canvas = this._engine.getRenderingCanvas();
  17964. if (attachMove) {
  17965. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17966. // Wheel
  17967. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17968. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17969. }
  17970. if (attachDown) {
  17971. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17972. }
  17973. if (attachUp) {
  17974. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17975. }
  17976. canvas.tabIndex = 1;
  17977. };
  17978. Scene.prototype.detachControl = function () {
  17979. var engine = this.getEngine();
  17980. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17981. var canvas = engine.getRenderingCanvas();
  17982. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17983. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17984. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17985. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  17986. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  17987. // Wheel
  17988. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17989. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17990. // Keyboard
  17991. canvas.removeEventListener("keydown", this._onKeyDown);
  17992. canvas.removeEventListener("keyup", this._onKeyUp);
  17993. // Observables
  17994. this.onKeyboardObservable.clear();
  17995. this.onPreKeyboardObservable.clear();
  17996. this.onPointerObservable.clear();
  17997. this.onPrePointerObservable.clear();
  17998. };
  17999. // Ready
  18000. Scene.prototype.isReady = function () {
  18001. if (this._pendingData.length > 0) {
  18002. return false;
  18003. }
  18004. var index;
  18005. // Geometries
  18006. for (index = 0; index < this._geometries.length; index++) {
  18007. var geometry = this._geometries[index];
  18008. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18009. return false;
  18010. }
  18011. }
  18012. // Meshes
  18013. for (index = 0; index < this.meshes.length; index++) {
  18014. var mesh = this.meshes[index];
  18015. if (!mesh.isEnabled()) {
  18016. continue;
  18017. }
  18018. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  18019. continue;
  18020. }
  18021. if (!mesh.isReady()) {
  18022. return false;
  18023. }
  18024. var mat = mesh.material;
  18025. if (mat) {
  18026. if (!mat.isReady(mesh)) {
  18027. return false;
  18028. }
  18029. }
  18030. }
  18031. return true;
  18032. };
  18033. Scene.prototype.resetCachedMaterial = function () {
  18034. this._cachedMaterial = null;
  18035. this._cachedEffect = null;
  18036. this._cachedVisibility = null;
  18037. };
  18038. Scene.prototype.registerBeforeRender = function (func) {
  18039. this.onBeforeRenderObservable.add(func);
  18040. };
  18041. Scene.prototype.unregisterBeforeRender = function (func) {
  18042. this.onBeforeRenderObservable.removeCallback(func);
  18043. };
  18044. Scene.prototype.registerAfterRender = function (func) {
  18045. this.onAfterRenderObservable.add(func);
  18046. };
  18047. Scene.prototype.unregisterAfterRender = function (func) {
  18048. this.onAfterRenderObservable.removeCallback(func);
  18049. };
  18050. Scene.prototype._addPendingData = function (data) {
  18051. this._pendingData.push(data);
  18052. };
  18053. Scene.prototype._removePendingData = function (data) {
  18054. var index = this._pendingData.indexOf(data);
  18055. if (index !== -1) {
  18056. this._pendingData.splice(index, 1);
  18057. }
  18058. };
  18059. Scene.prototype.getWaitingItemsCount = function () {
  18060. return this._pendingData.length;
  18061. };
  18062. /**
  18063. * Registers a function to be executed when the scene is ready.
  18064. * @param {Function} func - the function to be executed.
  18065. */
  18066. Scene.prototype.executeWhenReady = function (func) {
  18067. var _this = this;
  18068. this.onReadyObservable.add(func);
  18069. if (this._executeWhenReadyTimeoutId !== -1) {
  18070. return;
  18071. }
  18072. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18073. _this._checkIsReady();
  18074. }, 150);
  18075. };
  18076. Scene.prototype._checkIsReady = function () {
  18077. var _this = this;
  18078. if (this.isReady()) {
  18079. this.onReadyObservable.notifyObservers(this);
  18080. this.onReadyObservable.clear();
  18081. this._executeWhenReadyTimeoutId = -1;
  18082. return;
  18083. }
  18084. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18085. _this._checkIsReady();
  18086. }, 150);
  18087. };
  18088. // Animations
  18089. /**
  18090. * Will start the animation sequence of a given target
  18091. * @param target - the target
  18092. * @param {number} from - from which frame should animation start
  18093. * @param {number} to - till which frame should animation run.
  18094. * @param {boolean} [loop] - should the animation loop
  18095. * @param {number} [speedRatio] - the speed in which to run the animation
  18096. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  18097. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  18098. * Returns {BABYLON.Animatable} the animatable object created for this animation
  18099. * See BABYLON.Animatable
  18100. */
  18101. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  18102. if (speedRatio === void 0) { speedRatio = 1.0; }
  18103. if (from > to && speedRatio > 0) {
  18104. speedRatio *= -1;
  18105. }
  18106. this.stopAnimation(target);
  18107. if (!animatable) {
  18108. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  18109. }
  18110. // Local animations
  18111. if (target.animations) {
  18112. animatable.appendAnimations(target, target.animations);
  18113. }
  18114. // Children animations
  18115. if (target.getAnimatables) {
  18116. var animatables = target.getAnimatables();
  18117. for (var index = 0; index < animatables.length; index++) {
  18118. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  18119. }
  18120. }
  18121. animatable.reset();
  18122. return animatable;
  18123. };
  18124. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  18125. if (speedRatio === undefined) {
  18126. speedRatio = 1.0;
  18127. }
  18128. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  18129. return animatable;
  18130. };
  18131. Scene.prototype.getAnimatableByTarget = function (target) {
  18132. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18133. if (this._activeAnimatables[index].target === target) {
  18134. return this._activeAnimatables[index];
  18135. }
  18136. }
  18137. return null;
  18138. };
  18139. Object.defineProperty(Scene.prototype, "Animatables", {
  18140. get: function () {
  18141. return this._activeAnimatables;
  18142. },
  18143. enumerable: true,
  18144. configurable: true
  18145. });
  18146. /**
  18147. * Will stop the animation of the given target
  18148. * @param target - the target
  18149. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  18150. * @see beginAnimation
  18151. */
  18152. Scene.prototype.stopAnimation = function (target, animationName) {
  18153. var animatable = this.getAnimatableByTarget(target);
  18154. if (animatable) {
  18155. animatable.stop(animationName);
  18156. }
  18157. };
  18158. Scene.prototype._animate = function () {
  18159. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  18160. return;
  18161. }
  18162. // Getting time
  18163. var now = BABYLON.Tools.Now;
  18164. if (!this._animationTimeLast) {
  18165. if (this._pendingData.length > 0) {
  18166. return;
  18167. }
  18168. this._animationTimeLast = now;
  18169. }
  18170. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  18171. this._animationTime += deltaTime;
  18172. this._animationTimeLast = now;
  18173. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18174. this._activeAnimatables[index]._animate(this._animationTime);
  18175. }
  18176. };
  18177. // Matrix
  18178. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  18179. this._useAlternateCameraConfiguration = active;
  18180. };
  18181. Scene.prototype.getViewMatrix = function () {
  18182. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  18183. };
  18184. Scene.prototype.getProjectionMatrix = function () {
  18185. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  18186. };
  18187. Scene.prototype.getTransformMatrix = function () {
  18188. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  18189. };
  18190. Scene.prototype.setTransformMatrix = function (view, projection) {
  18191. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  18192. return;
  18193. }
  18194. this._viewUpdateFlag = view.updateFlag;
  18195. this._projectionUpdateFlag = projection.updateFlag;
  18196. this._viewMatrix = view;
  18197. this._projectionMatrix = projection;
  18198. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18199. // Update frustum
  18200. if (!this._frustumPlanes) {
  18201. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18202. }
  18203. else {
  18204. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18205. }
  18206. if (this.activeCamera._alternateCamera) {
  18207. var otherCamera = this.activeCamera._alternateCamera;
  18208. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  18209. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  18210. }
  18211. if (this._sceneUbo.useUbo) {
  18212. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  18213. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  18214. this._sceneUbo.update();
  18215. }
  18216. };
  18217. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  18218. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  18219. return;
  18220. }
  18221. this._alternateViewUpdateFlag = view.updateFlag;
  18222. this._alternateProjectionUpdateFlag = projection.updateFlag;
  18223. this._alternateViewMatrix = view;
  18224. this._alternateProjectionMatrix = projection;
  18225. if (!this._alternateTransformMatrix) {
  18226. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  18227. }
  18228. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  18229. if (!this._alternateSceneUbo) {
  18230. this._createAlternateUbo();
  18231. }
  18232. if (this._alternateSceneUbo.useUbo) {
  18233. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  18234. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  18235. this._alternateSceneUbo.update();
  18236. }
  18237. };
  18238. Scene.prototype.getSceneUniformBuffer = function () {
  18239. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  18240. };
  18241. // Methods
  18242. Scene.prototype.getUniqueId = function () {
  18243. var result = Scene._uniqueIdCounter;
  18244. Scene._uniqueIdCounter++;
  18245. return result;
  18246. };
  18247. Scene.prototype.addMesh = function (newMesh) {
  18248. var position = this.meshes.push(newMesh);
  18249. //notify the collision coordinator
  18250. if (this.collisionCoordinator) {
  18251. this.collisionCoordinator.onMeshAdded(newMesh);
  18252. }
  18253. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  18254. };
  18255. Scene.prototype.removeMesh = function (toRemove) {
  18256. var index = this.meshes.indexOf(toRemove);
  18257. if (index !== -1) {
  18258. // Remove from the scene if mesh found
  18259. this.meshes.splice(index, 1);
  18260. }
  18261. //notify the collision coordinator
  18262. if (this.collisionCoordinator) {
  18263. this.collisionCoordinator.onMeshRemoved(toRemove);
  18264. }
  18265. this.onMeshRemovedObservable.notifyObservers(toRemove);
  18266. return index;
  18267. };
  18268. Scene.prototype.removeSkeleton = function (toRemove) {
  18269. var index = this.skeletons.indexOf(toRemove);
  18270. if (index !== -1) {
  18271. // Remove from the scene if found
  18272. this.skeletons.splice(index, 1);
  18273. }
  18274. return index;
  18275. };
  18276. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  18277. var index = this.morphTargetManagers.indexOf(toRemove);
  18278. if (index !== -1) {
  18279. // Remove from the scene if found
  18280. this.morphTargetManagers.splice(index, 1);
  18281. }
  18282. return index;
  18283. };
  18284. Scene.prototype.removeLight = function (toRemove) {
  18285. var index = this.lights.indexOf(toRemove);
  18286. if (index !== -1) {
  18287. // Remove from the scene if mesh found
  18288. this.lights.splice(index, 1);
  18289. this.sortLightsByPriority();
  18290. }
  18291. this.onLightRemovedObservable.notifyObservers(toRemove);
  18292. return index;
  18293. };
  18294. Scene.prototype.removeCamera = function (toRemove) {
  18295. var index = this.cameras.indexOf(toRemove);
  18296. if (index !== -1) {
  18297. // Remove from the scene if mesh found
  18298. this.cameras.splice(index, 1);
  18299. }
  18300. // Remove from activeCameras
  18301. var index2 = this.activeCameras.indexOf(toRemove);
  18302. if (index2 !== -1) {
  18303. // Remove from the scene if mesh found
  18304. this.activeCameras.splice(index2, 1);
  18305. }
  18306. // Reset the activeCamera
  18307. if (this.activeCamera === toRemove) {
  18308. if (this.cameras.length > 0) {
  18309. this.activeCamera = this.cameras[0];
  18310. }
  18311. else {
  18312. this.activeCamera = null;
  18313. }
  18314. }
  18315. this.onCameraRemovedObservable.notifyObservers(toRemove);
  18316. return index;
  18317. };
  18318. Scene.prototype.addLight = function (newLight) {
  18319. this.lights.push(newLight);
  18320. this.sortLightsByPriority();
  18321. this.onNewLightAddedObservable.notifyObservers(newLight);
  18322. };
  18323. Scene.prototype.sortLightsByPriority = function () {
  18324. if (this.requireLightSorting) {
  18325. this.lights.sort(BABYLON.Light.compareLightsPriority);
  18326. }
  18327. };
  18328. Scene.prototype.addCamera = function (newCamera) {
  18329. var position = this.cameras.push(newCamera);
  18330. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  18331. };
  18332. /**
  18333. * Switch active camera
  18334. * @param {Camera} newCamera - new active camera
  18335. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  18336. */
  18337. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  18338. if (attachControl === void 0) { attachControl = true; }
  18339. var canvas = this._engine.getRenderingCanvas();
  18340. this.activeCamera.detachControl(canvas);
  18341. this.activeCamera = newCamera;
  18342. if (attachControl) {
  18343. newCamera.attachControl(canvas);
  18344. }
  18345. };
  18346. /**
  18347. * sets the active camera of the scene using its ID
  18348. * @param {string} id - the camera's ID
  18349. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18350. * @see activeCamera
  18351. */
  18352. Scene.prototype.setActiveCameraByID = function (id) {
  18353. var camera = this.getCameraByID(id);
  18354. if (camera) {
  18355. this.activeCamera = camera;
  18356. return camera;
  18357. }
  18358. return null;
  18359. };
  18360. /**
  18361. * sets the active camera of the scene using its name
  18362. * @param {string} name - the camera's name
  18363. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18364. * @see activeCamera
  18365. */
  18366. Scene.prototype.setActiveCameraByName = function (name) {
  18367. var camera = this.getCameraByName(name);
  18368. if (camera) {
  18369. this.activeCamera = camera;
  18370. return camera;
  18371. }
  18372. return null;
  18373. };
  18374. /**
  18375. * get a material using its id
  18376. * @param {string} the material's ID
  18377. * @return {BABYLON.Material|null} the material or null if none found.
  18378. */
  18379. Scene.prototype.getMaterialByID = function (id) {
  18380. for (var index = 0; index < this.materials.length; index++) {
  18381. if (this.materials[index].id === id) {
  18382. return this.materials[index];
  18383. }
  18384. }
  18385. return null;
  18386. };
  18387. /**
  18388. * get a material using its name
  18389. * @param {string} the material's name
  18390. * @return {BABYLON.Material|null} the material or null if none found.
  18391. */
  18392. Scene.prototype.getMaterialByName = function (name) {
  18393. for (var index = 0; index < this.materials.length; index++) {
  18394. if (this.materials[index].name === name) {
  18395. return this.materials[index];
  18396. }
  18397. }
  18398. return null;
  18399. };
  18400. Scene.prototype.getLensFlareSystemByName = function (name) {
  18401. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18402. if (this.lensFlareSystems[index].name === name) {
  18403. return this.lensFlareSystems[index];
  18404. }
  18405. }
  18406. return null;
  18407. };
  18408. Scene.prototype.getLensFlareSystemByID = function (id) {
  18409. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18410. if (this.lensFlareSystems[index].id === id) {
  18411. return this.lensFlareSystems[index];
  18412. }
  18413. }
  18414. return null;
  18415. };
  18416. Scene.prototype.getCameraByID = function (id) {
  18417. for (var index = 0; index < this.cameras.length; index++) {
  18418. if (this.cameras[index].id === id) {
  18419. return this.cameras[index];
  18420. }
  18421. }
  18422. return null;
  18423. };
  18424. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  18425. for (var index = 0; index < this.cameras.length; index++) {
  18426. if (this.cameras[index].uniqueId === uniqueId) {
  18427. return this.cameras[index];
  18428. }
  18429. }
  18430. return null;
  18431. };
  18432. /**
  18433. * get a camera using its name
  18434. * @param {string} the camera's name
  18435. * @return {BABYLON.Camera|null} the camera or null if none found.
  18436. */
  18437. Scene.prototype.getCameraByName = function (name) {
  18438. for (var index = 0; index < this.cameras.length; index++) {
  18439. if (this.cameras[index].name === name) {
  18440. return this.cameras[index];
  18441. }
  18442. }
  18443. return null;
  18444. };
  18445. /**
  18446. * get a bone using its id
  18447. * @param {string} the bone's id
  18448. * @return {BABYLON.Bone|null} the bone or null if not found
  18449. */
  18450. Scene.prototype.getBoneByID = function (id) {
  18451. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18452. var skeleton = this.skeletons[skeletonIndex];
  18453. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18454. if (skeleton.bones[boneIndex].id === id) {
  18455. return skeleton.bones[boneIndex];
  18456. }
  18457. }
  18458. }
  18459. return null;
  18460. };
  18461. /**
  18462. * get a bone using its id
  18463. * @param {string} the bone's name
  18464. * @return {BABYLON.Bone|null} the bone or null if not found
  18465. */
  18466. Scene.prototype.getBoneByName = function (name) {
  18467. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18468. var skeleton = this.skeletons[skeletonIndex];
  18469. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18470. if (skeleton.bones[boneIndex].name === name) {
  18471. return skeleton.bones[boneIndex];
  18472. }
  18473. }
  18474. }
  18475. return null;
  18476. };
  18477. /**
  18478. * get a light node using its name
  18479. * @param {string} the light's name
  18480. * @return {BABYLON.Light|null} the light or null if none found.
  18481. */
  18482. Scene.prototype.getLightByName = function (name) {
  18483. for (var index = 0; index < this.lights.length; index++) {
  18484. if (this.lights[index].name === name) {
  18485. return this.lights[index];
  18486. }
  18487. }
  18488. return null;
  18489. };
  18490. /**
  18491. * get a light node using its ID
  18492. * @param {string} the light's id
  18493. * @return {BABYLON.Light|null} the light or null if none found.
  18494. */
  18495. Scene.prototype.getLightByID = function (id) {
  18496. for (var index = 0; index < this.lights.length; index++) {
  18497. if (this.lights[index].id === id) {
  18498. return this.lights[index];
  18499. }
  18500. }
  18501. return null;
  18502. };
  18503. /**
  18504. * get a light node using its scene-generated unique ID
  18505. * @param {number} the light's unique id
  18506. * @return {BABYLON.Light|null} the light or null if none found.
  18507. */
  18508. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  18509. for (var index = 0; index < this.lights.length; index++) {
  18510. if (this.lights[index].uniqueId === uniqueId) {
  18511. return this.lights[index];
  18512. }
  18513. }
  18514. return null;
  18515. };
  18516. /**
  18517. * get a particle system by id
  18518. * @param id {number} the particle system id
  18519. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  18520. */
  18521. Scene.prototype.getParticleSystemByID = function (id) {
  18522. for (var index = 0; index < this.particleSystems.length; index++) {
  18523. if (this.particleSystems[index].id === id) {
  18524. return this.particleSystems[index];
  18525. }
  18526. }
  18527. return null;
  18528. };
  18529. /**
  18530. * get a geometry using its ID
  18531. * @param {string} the geometry's id
  18532. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  18533. */
  18534. Scene.prototype.getGeometryByID = function (id) {
  18535. for (var index = 0; index < this._geometries.length; index++) {
  18536. if (this._geometries[index].id === id) {
  18537. return this._geometries[index];
  18538. }
  18539. }
  18540. return null;
  18541. };
  18542. /**
  18543. * add a new geometry to this scene.
  18544. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  18545. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  18546. * @return {boolean} was the geometry added or not
  18547. */
  18548. Scene.prototype.pushGeometry = function (geometry, force) {
  18549. if (!force && this.getGeometryByID(geometry.id)) {
  18550. return false;
  18551. }
  18552. this._geometries.push(geometry);
  18553. //notify the collision coordinator
  18554. if (this.collisionCoordinator) {
  18555. this.collisionCoordinator.onGeometryAdded(geometry);
  18556. }
  18557. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  18558. return true;
  18559. };
  18560. /**
  18561. * Removes an existing geometry
  18562. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  18563. * @return {boolean} was the geometry removed or not
  18564. */
  18565. Scene.prototype.removeGeometry = function (geometry) {
  18566. var index = this._geometries.indexOf(geometry);
  18567. if (index > -1) {
  18568. this._geometries.splice(index, 1);
  18569. //notify the collision coordinator
  18570. if (this.collisionCoordinator) {
  18571. this.collisionCoordinator.onGeometryDeleted(geometry);
  18572. }
  18573. this.onGeometryRemovedObservable.notifyObservers(geometry);
  18574. return true;
  18575. }
  18576. return false;
  18577. };
  18578. Scene.prototype.getGeometries = function () {
  18579. return this._geometries;
  18580. };
  18581. /**
  18582. * Get the first added mesh found of a given ID
  18583. * @param {string} id - the id to search for
  18584. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18585. */
  18586. Scene.prototype.getMeshByID = function (id) {
  18587. for (var index = 0; index < this.meshes.length; index++) {
  18588. if (this.meshes[index].id === id) {
  18589. return this.meshes[index];
  18590. }
  18591. }
  18592. return null;
  18593. };
  18594. Scene.prototype.getMeshesByID = function (id) {
  18595. return this.meshes.filter(function (m) {
  18596. return m.id === id;
  18597. });
  18598. };
  18599. /**
  18600. * Get a mesh with its auto-generated unique id
  18601. * @param {number} uniqueId - the unique id to search for
  18602. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18603. */
  18604. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  18605. for (var index = 0; index < this.meshes.length; index++) {
  18606. if (this.meshes[index].uniqueId === uniqueId) {
  18607. return this.meshes[index];
  18608. }
  18609. }
  18610. return null;
  18611. };
  18612. /**
  18613. * Get a the last added mesh found of a given ID
  18614. * @param {string} id - the id to search for
  18615. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18616. */
  18617. Scene.prototype.getLastMeshByID = function (id) {
  18618. for (var index = this.meshes.length - 1; index >= 0; index--) {
  18619. if (this.meshes[index].id === id) {
  18620. return this.meshes[index];
  18621. }
  18622. }
  18623. return null;
  18624. };
  18625. /**
  18626. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  18627. * @param {string} id - the id to search for
  18628. * @return {BABYLON.Node|null} the node found or null if not found at all.
  18629. */
  18630. Scene.prototype.getLastEntryByID = function (id) {
  18631. var index;
  18632. for (index = this.meshes.length - 1; index >= 0; index--) {
  18633. if (this.meshes[index].id === id) {
  18634. return this.meshes[index];
  18635. }
  18636. }
  18637. for (index = this.cameras.length - 1; index >= 0; index--) {
  18638. if (this.cameras[index].id === id) {
  18639. return this.cameras[index];
  18640. }
  18641. }
  18642. for (index = this.lights.length - 1; index >= 0; index--) {
  18643. if (this.lights[index].id === id) {
  18644. return this.lights[index];
  18645. }
  18646. }
  18647. return null;
  18648. };
  18649. Scene.prototype.getNodeByID = function (id) {
  18650. var mesh = this.getMeshByID(id);
  18651. if (mesh) {
  18652. return mesh;
  18653. }
  18654. var light = this.getLightByID(id);
  18655. if (light) {
  18656. return light;
  18657. }
  18658. var camera = this.getCameraByID(id);
  18659. if (camera) {
  18660. return camera;
  18661. }
  18662. var bone = this.getBoneByID(id);
  18663. return bone;
  18664. };
  18665. Scene.prototype.getNodeByName = function (name) {
  18666. var mesh = this.getMeshByName(name);
  18667. if (mesh) {
  18668. return mesh;
  18669. }
  18670. var light = this.getLightByName(name);
  18671. if (light) {
  18672. return light;
  18673. }
  18674. var camera = this.getCameraByName(name);
  18675. if (camera) {
  18676. return camera;
  18677. }
  18678. var bone = this.getBoneByName(name);
  18679. return bone;
  18680. };
  18681. Scene.prototype.getMeshByName = function (name) {
  18682. for (var index = 0; index < this.meshes.length; index++) {
  18683. if (this.meshes[index].name === name) {
  18684. return this.meshes[index];
  18685. }
  18686. }
  18687. return null;
  18688. };
  18689. Scene.prototype.getSoundByName = function (name) {
  18690. var index;
  18691. if (BABYLON.AudioEngine) {
  18692. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18693. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18694. return this.mainSoundTrack.soundCollection[index];
  18695. }
  18696. }
  18697. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18698. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18699. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18700. return this.soundTracks[sdIndex].soundCollection[index];
  18701. }
  18702. }
  18703. }
  18704. }
  18705. return null;
  18706. };
  18707. Scene.prototype.getLastSkeletonByID = function (id) {
  18708. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18709. if (this.skeletons[index].id === id) {
  18710. return this.skeletons[index];
  18711. }
  18712. }
  18713. return null;
  18714. };
  18715. Scene.prototype.getSkeletonById = function (id) {
  18716. for (var index = 0; index < this.skeletons.length; index++) {
  18717. if (this.skeletons[index].id === id) {
  18718. return this.skeletons[index];
  18719. }
  18720. }
  18721. return null;
  18722. };
  18723. Scene.prototype.getSkeletonByName = function (name) {
  18724. for (var index = 0; index < this.skeletons.length; index++) {
  18725. if (this.skeletons[index].name === name) {
  18726. return this.skeletons[index];
  18727. }
  18728. }
  18729. return null;
  18730. };
  18731. Scene.prototype.getMorphTargetManagerById = function (id) {
  18732. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  18733. if (this.morphTargetManagers[index].uniqueId === id) {
  18734. return this.morphTargetManagers[index];
  18735. }
  18736. }
  18737. return null;
  18738. };
  18739. Scene.prototype.isActiveMesh = function (mesh) {
  18740. return (this._activeMeshes.indexOf(mesh) !== -1);
  18741. };
  18742. /**
  18743. * Return a the first highlight layer of the scene with a given name.
  18744. * @param name The name of the highlight layer to look for.
  18745. * @return The highlight layer if found otherwise null.
  18746. */
  18747. Scene.prototype.getHighlightLayerByName = function (name) {
  18748. for (var index = 0; index < this.highlightLayers.length; index++) {
  18749. if (this.highlightLayers[index].name === name) {
  18750. return this.highlightLayers[index];
  18751. }
  18752. }
  18753. return null;
  18754. };
  18755. Object.defineProperty(Scene.prototype, "uid", {
  18756. /**
  18757. * Return a unique id as a string which can serve as an identifier for the scene
  18758. */
  18759. get: function () {
  18760. if (!this._uid) {
  18761. this._uid = BABYLON.Tools.RandomId();
  18762. }
  18763. return this._uid;
  18764. },
  18765. enumerable: true,
  18766. configurable: true
  18767. });
  18768. /**
  18769. * Add an externaly attached data from its key.
  18770. * This method call will fail and return false, if such key already exists.
  18771. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18772. * @param key the unique key that identifies the data
  18773. * @param data the data object to associate to the key for this Engine instance
  18774. * @return true if no such key were already present and the data was added successfully, false otherwise
  18775. */
  18776. Scene.prototype.addExternalData = function (key, data) {
  18777. if (!this._externalData) {
  18778. this._externalData = new BABYLON.StringDictionary();
  18779. }
  18780. return this._externalData.add(key, data);
  18781. };
  18782. /**
  18783. * Get an externaly attached data from its key
  18784. * @param key the unique key that identifies the data
  18785. * @return the associated data, if present (can be null), or undefined if not present
  18786. */
  18787. Scene.prototype.getExternalData = function (key) {
  18788. if (!this._externalData) {
  18789. return null;
  18790. }
  18791. return this._externalData.get(key);
  18792. };
  18793. /**
  18794. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18795. * @param key the unique key that identifies the data
  18796. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18797. * @return the associated data, can be null if the factory returned null.
  18798. */
  18799. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18800. if (!this._externalData) {
  18801. this._externalData = new BABYLON.StringDictionary();
  18802. }
  18803. return this._externalData.getOrAddWithFactory(key, factory);
  18804. };
  18805. /**
  18806. * Remove an externaly attached data from the Engine instance
  18807. * @param key the unique key that identifies the data
  18808. * @return true if the data was successfully removed, false if it doesn't exist
  18809. */
  18810. Scene.prototype.removeExternalData = function (key) {
  18811. return this._externalData.remove(key);
  18812. };
  18813. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18814. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18815. var material = subMesh.getMaterial();
  18816. if (mesh.showSubMeshesBoundingBox) {
  18817. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  18818. }
  18819. if (material) {
  18820. // Render targets
  18821. if (material.getRenderTargetTextures) {
  18822. if (this._processedMaterials.indexOf(material) === -1) {
  18823. this._processedMaterials.push(material);
  18824. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18825. }
  18826. }
  18827. // Dispatch
  18828. this._activeIndices.addCount(subMesh.indexCount, false);
  18829. this._renderingManager.dispatch(subMesh);
  18830. }
  18831. }
  18832. };
  18833. Scene.prototype._isInIntermediateRendering = function () {
  18834. return this._intermediateRendering;
  18835. };
  18836. /**
  18837. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  18838. */
  18839. Scene.prototype.freezeActiveMeshes = function () {
  18840. this._evaluateActiveMeshes();
  18841. this._activeMeshesFrozen = true;
  18842. return this;
  18843. };
  18844. /**
  18845. * Use this function to restart evaluating active meshes on every frame
  18846. */
  18847. Scene.prototype.unfreezeActiveMeshes = function () {
  18848. this._activeMeshesFrozen = false;
  18849. return this;
  18850. };
  18851. Scene.prototype._evaluateActiveMeshes = function () {
  18852. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  18853. return;
  18854. }
  18855. this.activeCamera._activeMeshes.reset();
  18856. this._activeMeshes.reset();
  18857. this._renderingManager.reset();
  18858. this._processedMaterials.reset();
  18859. this._activeParticleSystems.reset();
  18860. this._activeSkeletons.reset();
  18861. this._softwareSkinnedMeshes.reset();
  18862. if (this._boundingBoxRenderer) {
  18863. this._boundingBoxRenderer.reset();
  18864. }
  18865. // Meshes
  18866. var meshes;
  18867. var len;
  18868. if (this._selectionOctree) {
  18869. var selection = this._selectionOctree.select(this._frustumPlanes);
  18870. meshes = selection.data;
  18871. len = selection.length;
  18872. }
  18873. else {
  18874. len = this.meshes.length;
  18875. meshes = this.meshes;
  18876. }
  18877. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18878. var mesh = meshes[meshIndex];
  18879. if (mesh.isBlocked) {
  18880. continue;
  18881. }
  18882. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18883. if (!mesh.isReady() || !mesh.isEnabled()) {
  18884. continue;
  18885. }
  18886. mesh.computeWorldMatrix();
  18887. // Intersections
  18888. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18889. this._meshesForIntersections.pushNoDuplicate(mesh);
  18890. }
  18891. // Switch to current LOD
  18892. var meshLOD = mesh.getLOD(this.activeCamera);
  18893. if (!meshLOD) {
  18894. continue;
  18895. }
  18896. mesh._preActivate();
  18897. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18898. this._activeMeshes.push(mesh);
  18899. this.activeCamera._activeMeshes.push(mesh);
  18900. mesh._activate(this._renderId);
  18901. if (meshLOD !== mesh) {
  18902. meshLOD._activate(this._renderId);
  18903. }
  18904. this._activeMesh(mesh, meshLOD);
  18905. }
  18906. }
  18907. // Particle systems
  18908. this._particlesDuration.beginMonitoring();
  18909. var beforeParticlesDate = BABYLON.Tools.Now;
  18910. if (this.particlesEnabled) {
  18911. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18912. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18913. var particleSystem = this.particleSystems[particleIndex];
  18914. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  18915. continue;
  18916. }
  18917. var emitter = particleSystem.emitter;
  18918. if (!emitter.position || emitter.isEnabled()) {
  18919. this._activeParticleSystems.push(particleSystem);
  18920. particleSystem.animate();
  18921. this._renderingManager.dispatchParticles(particleSystem);
  18922. }
  18923. }
  18924. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18925. }
  18926. this._particlesDuration.endMonitoring(false);
  18927. };
  18928. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18929. if (mesh.skeleton && this.skeletonsEnabled) {
  18930. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18931. mesh.skeleton.prepare();
  18932. }
  18933. if (!mesh.computeBonesUsingShaders) {
  18934. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18935. }
  18936. }
  18937. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18938. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18939. }
  18940. if (mesh && mesh.subMeshes) {
  18941. // Submeshes Octrees
  18942. var len;
  18943. var subMeshes;
  18944. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18945. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18946. len = intersections.length;
  18947. subMeshes = intersections.data;
  18948. }
  18949. else {
  18950. subMeshes = mesh.subMeshes;
  18951. len = subMeshes.length;
  18952. }
  18953. for (var subIndex = 0; subIndex < len; subIndex++) {
  18954. var subMesh = subMeshes[subIndex];
  18955. this._evaluateSubMesh(subMesh, mesh);
  18956. }
  18957. }
  18958. };
  18959. Scene.prototype.updateTransformMatrix = function (force) {
  18960. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18961. };
  18962. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  18963. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  18964. };
  18965. Scene.prototype._renderForCamera = function (camera) {
  18966. if (camera && camera._skipRendering) {
  18967. return;
  18968. }
  18969. var engine = this._engine;
  18970. var startTime = BABYLON.Tools.Now;
  18971. this.activeCamera = camera;
  18972. if (!this.activeCamera)
  18973. throw new Error("Active camera not set");
  18974. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18975. // Viewport
  18976. engine.setViewport(this.activeCamera.viewport);
  18977. // Camera
  18978. this.resetCachedMaterial();
  18979. this._renderId++;
  18980. this.activeCamera.update();
  18981. this.updateTransformMatrix();
  18982. if (camera._alternateCamera) {
  18983. this.updateAlternateTransformMatrix(camera._alternateCamera);
  18984. this._alternateRendering = true;
  18985. }
  18986. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18987. // Meshes
  18988. this._evaluateActiveMeshesDuration.beginMonitoring();
  18989. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18990. this._evaluateActiveMeshes();
  18991. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18992. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18993. // Software skinning
  18994. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18995. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18996. mesh.applySkeleton(mesh.skeleton);
  18997. }
  18998. // Render targets
  18999. this._renderTargetsDuration.beginMonitoring();
  19000. var needsRestoreFrameBuffer = false;
  19001. var beforeRenderTargetDate = BABYLON.Tools.Now;
  19002. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  19003. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  19004. }
  19005. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  19006. this._intermediateRendering = true;
  19007. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19008. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  19009. var renderTarget = this._renderTargets.data[renderIndex];
  19010. if (renderTarget._shouldRender()) {
  19011. this._renderId++;
  19012. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  19013. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  19014. }
  19015. }
  19016. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19017. this._intermediateRendering = false;
  19018. this._renderId++;
  19019. needsRestoreFrameBuffer = true; // Restore back buffer
  19020. }
  19021. // Render HighlightLayer Texture
  19022. var stencilState = this._engine.getStencilBuffer();
  19023. var renderhighlights = false;
  19024. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  19025. this._intermediateRendering = true;
  19026. for (var i = 0; i < this.highlightLayers.length; i++) {
  19027. var highlightLayer = this.highlightLayers[i];
  19028. if (highlightLayer.shouldRender() &&
  19029. (!highlightLayer.camera ||
  19030. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  19031. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  19032. renderhighlights = true;
  19033. var renderTarget = highlightLayer._mainTexture;
  19034. if (renderTarget._shouldRender()) {
  19035. this._renderId++;
  19036. renderTarget.render(false, false);
  19037. needsRestoreFrameBuffer = true;
  19038. }
  19039. }
  19040. }
  19041. this._intermediateRendering = false;
  19042. this._renderId++;
  19043. }
  19044. if (needsRestoreFrameBuffer) {
  19045. engine.restoreDefaultFramebuffer(); // Restore back buffer
  19046. }
  19047. this._renderTargetsDuration.endMonitoring(false);
  19048. // Prepare Frame
  19049. this.postProcessManager._prepareFrame();
  19050. this._renderDuration.beginMonitoring();
  19051. // Backgrounds
  19052. var layerIndex;
  19053. var layer;
  19054. if (this.layers.length) {
  19055. engine.setDepthBuffer(false);
  19056. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19057. layer = this.layers[layerIndex];
  19058. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19059. layer.render();
  19060. }
  19061. }
  19062. engine.setDepthBuffer(true);
  19063. }
  19064. // Render
  19065. BABYLON.Tools.StartPerformanceCounter("Main render");
  19066. // Activate HighlightLayer stencil
  19067. if (renderhighlights) {
  19068. this._engine.setStencilBuffer(true);
  19069. }
  19070. this._renderingManager.render(null, null, true, true);
  19071. // Restore HighlightLayer stencil
  19072. if (renderhighlights) {
  19073. this._engine.setStencilBuffer(stencilState);
  19074. }
  19075. BABYLON.Tools.EndPerformanceCounter("Main render");
  19076. // Bounding boxes
  19077. if (this._boundingBoxRenderer) {
  19078. this._boundingBoxRenderer.render();
  19079. }
  19080. // Lens flares
  19081. if (this.lensFlaresEnabled) {
  19082. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19083. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  19084. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  19085. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  19086. lensFlareSystem.render();
  19087. }
  19088. }
  19089. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19090. }
  19091. // Foregrounds
  19092. if (this.layers.length) {
  19093. engine.setDepthBuffer(false);
  19094. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19095. layer = this.layers[layerIndex];
  19096. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19097. layer.render();
  19098. }
  19099. }
  19100. engine.setDepthBuffer(true);
  19101. }
  19102. // Highlight Layer
  19103. if (renderhighlights) {
  19104. engine.setDepthBuffer(false);
  19105. for (var i = 0; i < this.highlightLayers.length; i++) {
  19106. if (this.highlightLayers[i].shouldRender()) {
  19107. this.highlightLayers[i].render();
  19108. }
  19109. }
  19110. engine.setDepthBuffer(true);
  19111. }
  19112. this._renderDuration.endMonitoring(false);
  19113. // Finalize frame
  19114. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  19115. // Reset some special arrays
  19116. this._renderTargets.reset();
  19117. this._alternateRendering = false;
  19118. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  19119. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19120. };
  19121. Scene.prototype._processSubCameras = function (camera) {
  19122. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  19123. this._renderForCamera(camera);
  19124. return;
  19125. }
  19126. // Update camera
  19127. this.activeCamera.update();
  19128. // rig cameras
  19129. for (var index = 0; index < camera._rigCameras.length; index++) {
  19130. this._renderForCamera(camera._rigCameras[index]);
  19131. }
  19132. this.activeCamera = camera;
  19133. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  19134. };
  19135. Scene.prototype._checkIntersections = function () {
  19136. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  19137. var sourceMesh = this._meshesForIntersections.data[index];
  19138. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  19139. var action = sourceMesh.actionManager.actions[actionIndex];
  19140. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19141. var parameters = action.getTriggerParameter();
  19142. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  19143. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  19144. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  19145. if (areIntersecting && currentIntersectionInProgress === -1) {
  19146. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  19147. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  19148. sourceMesh._intersectionsInProgress.push(otherMesh);
  19149. }
  19150. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19151. sourceMesh._intersectionsInProgress.push(otherMesh);
  19152. }
  19153. }
  19154. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  19155. //They intersected, and now they don't.
  19156. //is this trigger an exit trigger? execute an event.
  19157. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19158. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  19159. }
  19160. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  19161. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19162. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  19163. }
  19164. }
  19165. }
  19166. }
  19167. }
  19168. };
  19169. Scene.prototype.render = function () {
  19170. if (this.isDisposed) {
  19171. return;
  19172. }
  19173. this._interFrameDuration.endMonitoring();
  19174. this._lastFrameDuration.beginMonitoring();
  19175. this._particlesDuration.fetchNewFrame();
  19176. this._spritesDuration.fetchNewFrame();
  19177. this._activeParticles.fetchNewFrame();
  19178. this._renderDuration.fetchNewFrame();
  19179. this._renderTargetsDuration.fetchNewFrame();
  19180. this._evaluateActiveMeshesDuration.fetchNewFrame();
  19181. this._totalVertices.fetchNewFrame();
  19182. this._activeIndices.fetchNewFrame();
  19183. this._activeBones.fetchNewFrame();
  19184. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  19185. this._meshesForIntersections.reset();
  19186. this.resetCachedMaterial();
  19187. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  19188. // Actions
  19189. if (this.actionManager) {
  19190. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  19191. }
  19192. //Simplification Queue
  19193. if (this.simplificationQueue && !this.simplificationQueue.running) {
  19194. this.simplificationQueue.executeNext();
  19195. }
  19196. if (this._engine.isDeterministicLockStep()) {
  19197. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  19198. var defaultTimeStep = (60.0 / 1000.0);
  19199. if (this._physicsEngine) {
  19200. defaultTimeStep = this._physicsEngine.getTimeStep();
  19201. }
  19202. var maxSubSteps = this._engine.getLockstepMaxSteps();
  19203. this._timeAccumulator += deltaTime;
  19204. // compute the amount of fixed steps we should have taken since the last step
  19205. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  19206. internalSteps = Math.min(internalSteps, maxSubSteps);
  19207. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  19208. this.onBeforeStepObservable.notifyObservers(this);
  19209. // Animations
  19210. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  19211. this._animate();
  19212. // Physics
  19213. if (this._physicsEngine) {
  19214. BABYLON.Tools.StartPerformanceCounter("Physics");
  19215. this._physicsEngine._step(defaultTimeStep);
  19216. BABYLON.Tools.EndPerformanceCounter("Physics");
  19217. }
  19218. this._timeAccumulator -= defaultTimeStep;
  19219. this.onAfterStepObservable.notifyObservers(this);
  19220. this._currentStepId++;
  19221. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  19222. this._evaluateActiveMeshes();
  19223. }
  19224. }
  19225. }
  19226. else {
  19227. // Animations
  19228. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  19229. this._animationRatio = deltaTime * (60.0 / 1000.0);
  19230. this._animate();
  19231. // Physics
  19232. if (this._physicsEngine) {
  19233. BABYLON.Tools.StartPerformanceCounter("Physics");
  19234. this._physicsEngine._step(deltaTime / 1000.0);
  19235. BABYLON.Tools.EndPerformanceCounter("Physics");
  19236. }
  19237. }
  19238. // Before render
  19239. this.onBeforeRenderObservable.notifyObservers(this);
  19240. // Customs render targets
  19241. this._renderTargetsDuration.beginMonitoring();
  19242. var beforeRenderTargetDate = BABYLON.Tools.Now;
  19243. var engine = this.getEngine();
  19244. var currentActiveCamera = this.activeCamera;
  19245. if (this.renderTargetsEnabled) {
  19246. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19247. this._intermediateRendering = true;
  19248. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  19249. var renderTarget = this.customRenderTargets[customIndex];
  19250. if (renderTarget._shouldRender()) {
  19251. this._renderId++;
  19252. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  19253. if (!this.activeCamera)
  19254. throw new Error("Active camera not set");
  19255. // Viewport
  19256. engine.setViewport(this.activeCamera.viewport);
  19257. // Camera
  19258. this.updateTransformMatrix();
  19259. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  19260. }
  19261. }
  19262. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19263. this._intermediateRendering = false;
  19264. this._renderId++;
  19265. }
  19266. // Restore back buffer
  19267. if (this.customRenderTargets.length > 0) {
  19268. engine.restoreDefaultFramebuffer();
  19269. }
  19270. this._renderTargetsDuration.endMonitoring();
  19271. this.activeCamera = currentActiveCamera;
  19272. // Procedural textures
  19273. if (this.proceduralTexturesEnabled) {
  19274. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19275. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  19276. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  19277. if (proceduralTexture._shouldRender()) {
  19278. proceduralTexture.render();
  19279. }
  19280. }
  19281. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19282. }
  19283. // Clear
  19284. if (this.autoClearDepthAndStencil || this.autoClear) {
  19285. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  19286. }
  19287. // Shadows
  19288. if (this.shadowsEnabled) {
  19289. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  19290. var light = this.lights[lightIndex];
  19291. var shadowGenerator = light.getShadowGenerator();
  19292. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  19293. var shadowMap = shadowGenerator.getShadowMap();
  19294. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  19295. this._renderTargets.push(shadowMap);
  19296. }
  19297. }
  19298. }
  19299. }
  19300. // Depth renderer
  19301. if (this._depthRenderer) {
  19302. this._renderTargets.push(this._depthRenderer.getDepthMap());
  19303. }
  19304. // Geometry renderer
  19305. if (this._geometryBufferRenderer) {
  19306. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  19307. }
  19308. // RenderPipeline
  19309. if (this._postProcessRenderPipelineManager) {
  19310. this._postProcessRenderPipelineManager.update();
  19311. }
  19312. // Multi-cameras?
  19313. if (this.activeCameras.length > 0) {
  19314. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  19315. if (cameraIndex > 0) {
  19316. this._engine.clear(null, false, true, true);
  19317. }
  19318. this._processSubCameras(this.activeCameras[cameraIndex]);
  19319. }
  19320. }
  19321. else {
  19322. if (!this.activeCamera) {
  19323. throw new Error("No camera defined");
  19324. }
  19325. this._processSubCameras(this.activeCamera);
  19326. }
  19327. // Intersection checks
  19328. this._checkIntersections();
  19329. // Update the audio listener attached to the camera
  19330. if (BABYLON.AudioEngine) {
  19331. this._updateAudioParameters();
  19332. }
  19333. // After render
  19334. if (this.afterRender) {
  19335. this.afterRender();
  19336. }
  19337. this.onAfterRenderObservable.notifyObservers(this);
  19338. // Cleaning
  19339. for (var index = 0; index < this._toBeDisposed.length; index++) {
  19340. this._toBeDisposed.data[index].dispose();
  19341. this._toBeDisposed[index] = null;
  19342. }
  19343. this._toBeDisposed.reset();
  19344. if (this.dumpNextRenderTargets) {
  19345. this.dumpNextRenderTargets = false;
  19346. }
  19347. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  19348. this._interFrameDuration.beginMonitoring();
  19349. this._lastFrameDuration.endMonitoring();
  19350. this._totalMeshesCounter.addCount(this.meshes.length, true);
  19351. this._totalLightsCounter.addCount(this.lights.length, true);
  19352. this._totalMaterialsCounter.addCount(this.materials.length, true);
  19353. this._totalTexturesCounter.addCount(this.textures.length, true);
  19354. this._activeBones.addCount(0, true);
  19355. this._activeIndices.addCount(0, true);
  19356. this._activeParticles.addCount(0, true);
  19357. };
  19358. Scene.prototype._updateAudioParameters = function () {
  19359. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  19360. return;
  19361. }
  19362. var listeningCamera;
  19363. var audioEngine = BABYLON.Engine.audioEngine;
  19364. if (this.activeCameras.length > 0) {
  19365. listeningCamera = this.activeCameras[0];
  19366. }
  19367. else {
  19368. listeningCamera = this.activeCamera;
  19369. }
  19370. if (listeningCamera && audioEngine.canUseWebAudio) {
  19371. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  19372. // for VR cameras
  19373. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  19374. listeningCamera = listeningCamera.rigCameras[0];
  19375. }
  19376. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  19377. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  19378. cameraDirection.normalize();
  19379. // To avoid some errors on GearVR
  19380. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  19381. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  19382. }
  19383. var i;
  19384. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19385. var sound = this.mainSoundTrack.soundCollection[i];
  19386. if (sound.useCustomAttenuation) {
  19387. sound.updateDistanceFromListener();
  19388. }
  19389. }
  19390. for (i = 0; i < this.soundTracks.length; i++) {
  19391. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19392. sound = this.soundTracks[i].soundCollection[j];
  19393. if (sound.useCustomAttenuation) {
  19394. sound.updateDistanceFromListener();
  19395. }
  19396. }
  19397. }
  19398. }
  19399. };
  19400. Object.defineProperty(Scene.prototype, "audioEnabled", {
  19401. // Audio
  19402. get: function () {
  19403. return this._audioEnabled;
  19404. },
  19405. set: function (value) {
  19406. this._audioEnabled = value;
  19407. if (BABYLON.AudioEngine) {
  19408. if (this._audioEnabled) {
  19409. this._enableAudio();
  19410. }
  19411. else {
  19412. this._disableAudio();
  19413. }
  19414. }
  19415. },
  19416. enumerable: true,
  19417. configurable: true
  19418. });
  19419. Scene.prototype._disableAudio = function () {
  19420. var i;
  19421. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19422. this.mainSoundTrack.soundCollection[i].pause();
  19423. }
  19424. for (i = 0; i < this.soundTracks.length; i++) {
  19425. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19426. this.soundTracks[i].soundCollection[j].pause();
  19427. }
  19428. }
  19429. };
  19430. Scene.prototype._enableAudio = function () {
  19431. var i;
  19432. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19433. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  19434. this.mainSoundTrack.soundCollection[i].play();
  19435. }
  19436. }
  19437. for (i = 0; i < this.soundTracks.length; i++) {
  19438. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19439. if (this.soundTracks[i].soundCollection[j].isPaused) {
  19440. this.soundTracks[i].soundCollection[j].play();
  19441. }
  19442. }
  19443. }
  19444. };
  19445. Object.defineProperty(Scene.prototype, "headphone", {
  19446. get: function () {
  19447. return this._headphone;
  19448. },
  19449. set: function (value) {
  19450. this._headphone = value;
  19451. if (BABYLON.AudioEngine) {
  19452. if (this._headphone) {
  19453. this._switchAudioModeForHeadphones();
  19454. }
  19455. else {
  19456. this._switchAudioModeForNormalSpeakers();
  19457. }
  19458. }
  19459. },
  19460. enumerable: true,
  19461. configurable: true
  19462. });
  19463. Scene.prototype._switchAudioModeForHeadphones = function () {
  19464. this.mainSoundTrack.switchPanningModelToHRTF();
  19465. for (var i = 0; i < this.soundTracks.length; i++) {
  19466. this.soundTracks[i].switchPanningModelToHRTF();
  19467. }
  19468. };
  19469. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  19470. this.mainSoundTrack.switchPanningModelToEqualPower();
  19471. for (var i = 0; i < this.soundTracks.length; i++) {
  19472. this.soundTracks[i].switchPanningModelToEqualPower();
  19473. }
  19474. };
  19475. Scene.prototype.enableDepthRenderer = function () {
  19476. if (this._depthRenderer) {
  19477. return this._depthRenderer;
  19478. }
  19479. this._depthRenderer = new BABYLON.DepthRenderer(this);
  19480. return this._depthRenderer;
  19481. };
  19482. Scene.prototype.disableDepthRenderer = function () {
  19483. if (!this._depthRenderer) {
  19484. return;
  19485. }
  19486. this._depthRenderer.dispose();
  19487. this._depthRenderer = null;
  19488. };
  19489. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  19490. if (ratio === void 0) { ratio = 1; }
  19491. if (this._geometryBufferRenderer) {
  19492. return this._geometryBufferRenderer;
  19493. }
  19494. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  19495. if (!this._geometryBufferRenderer.isSupported) {
  19496. this._geometryBufferRenderer = null;
  19497. }
  19498. return this._geometryBufferRenderer;
  19499. };
  19500. Scene.prototype.disableGeometryBufferRenderer = function () {
  19501. if (!this._geometryBufferRenderer) {
  19502. return;
  19503. }
  19504. this._geometryBufferRenderer.dispose();
  19505. this._geometryBufferRenderer = null;
  19506. };
  19507. Scene.prototype.freezeMaterials = function () {
  19508. for (var i = 0; i < this.materials.length; i++) {
  19509. this.materials[i].freeze();
  19510. }
  19511. };
  19512. Scene.prototype.unfreezeMaterials = function () {
  19513. for (var i = 0; i < this.materials.length; i++) {
  19514. this.materials[i].unfreeze();
  19515. }
  19516. };
  19517. Scene.prototype.dispose = function () {
  19518. this.beforeRender = null;
  19519. this.afterRender = null;
  19520. this.skeletons = [];
  19521. this.morphTargetManagers = [];
  19522. this.importedMeshesFiles = new Array();
  19523. this.resetCachedMaterial();
  19524. if (this._depthRenderer) {
  19525. this._depthRenderer.dispose();
  19526. }
  19527. if (this._gamepadManager) {
  19528. this._gamepadManager.dispose();
  19529. this._gamepadManager = null;
  19530. }
  19531. // Smart arrays
  19532. if (this.activeCamera) {
  19533. this.activeCamera._activeMeshes.dispose();
  19534. this.activeCamera = null;
  19535. }
  19536. this._activeMeshes.dispose();
  19537. this._renderingManager.dispose();
  19538. this._processedMaterials.dispose();
  19539. this._activeParticleSystems.dispose();
  19540. this._activeSkeletons.dispose();
  19541. this._softwareSkinnedMeshes.dispose();
  19542. this._renderTargets.dispose();
  19543. if (this._boundingBoxRenderer) {
  19544. this._boundingBoxRenderer.dispose();
  19545. }
  19546. this._meshesForIntersections.dispose();
  19547. this._toBeDisposed.dispose();
  19548. // Debug layer
  19549. if (this._debugLayer) {
  19550. this._debugLayer.hide();
  19551. }
  19552. // Events
  19553. this.onDisposeObservable.notifyObservers(this);
  19554. this.onDisposeObservable.clear();
  19555. this.onBeforeRenderObservable.clear();
  19556. this.onAfterRenderObservable.clear();
  19557. this.detachControl();
  19558. // Release sounds & sounds tracks
  19559. if (BABYLON.AudioEngine) {
  19560. this.disposeSounds();
  19561. }
  19562. // VR Helper
  19563. if (this.VRHelper) {
  19564. this.VRHelper.dispose();
  19565. }
  19566. // Detach cameras
  19567. var canvas = this._engine.getRenderingCanvas();
  19568. var index;
  19569. for (index = 0; index < this.cameras.length; index++) {
  19570. this.cameras[index].detachControl(canvas);
  19571. }
  19572. // Release lights
  19573. while (this.lights.length) {
  19574. this.lights[0].dispose();
  19575. }
  19576. // Release meshes
  19577. while (this.meshes.length) {
  19578. this.meshes[0].dispose(true);
  19579. }
  19580. // Release cameras
  19581. while (this.cameras.length) {
  19582. this.cameras[0].dispose();
  19583. }
  19584. // Release materials
  19585. if (this.defaultMaterial) {
  19586. this.defaultMaterial.dispose();
  19587. }
  19588. while (this.multiMaterials.length) {
  19589. this.multiMaterials[0].dispose();
  19590. }
  19591. while (this.materials.length) {
  19592. this.materials[0].dispose();
  19593. }
  19594. // Release particles
  19595. while (this.particleSystems.length) {
  19596. this.particleSystems[0].dispose();
  19597. }
  19598. // Release sprites
  19599. while (this.spriteManagers.length) {
  19600. this.spriteManagers[0].dispose();
  19601. }
  19602. // Release postProcesses
  19603. while (this.postProcesses.length) {
  19604. this.postProcesses[0].dispose();
  19605. }
  19606. // Release layers
  19607. while (this.layers.length) {
  19608. this.layers[0].dispose();
  19609. }
  19610. while (this.highlightLayers.length) {
  19611. this.highlightLayers[0].dispose();
  19612. }
  19613. // Release textures
  19614. while (this.textures.length) {
  19615. this.textures[0].dispose();
  19616. }
  19617. // Release UBO
  19618. this._sceneUbo.dispose();
  19619. if (this._alternateSceneUbo) {
  19620. this._alternateSceneUbo.dispose();
  19621. }
  19622. // Post-processes
  19623. this.postProcessManager.dispose();
  19624. if (this._postProcessRenderPipelineManager) {
  19625. this._postProcessRenderPipelineManager.dispose();
  19626. }
  19627. // Physics
  19628. if (this._physicsEngine) {
  19629. this.disablePhysicsEngine();
  19630. }
  19631. // Remove from engine
  19632. index = this._engine.scenes.indexOf(this);
  19633. if (index > -1) {
  19634. this._engine.scenes.splice(index, 1);
  19635. }
  19636. this._engine.wipeCaches();
  19637. this._engine = null;
  19638. this.defaultMaterial = null;
  19639. this.multiMaterials = null;
  19640. this.materials = null;
  19641. };
  19642. Object.defineProperty(Scene.prototype, "isDisposed", {
  19643. get: function () {
  19644. return !this._engine;
  19645. },
  19646. enumerable: true,
  19647. configurable: true
  19648. });
  19649. // Release sounds & sounds tracks
  19650. Scene.prototype.disposeSounds = function () {
  19651. if (!this._mainSoundTrack) {
  19652. return;
  19653. }
  19654. this.mainSoundTrack.dispose();
  19655. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  19656. this.soundTracks[scIndex].dispose();
  19657. }
  19658. };
  19659. // Octrees
  19660. Scene.prototype.getWorldExtends = function () {
  19661. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19662. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19663. for (var index = 0; index < this.meshes.length; index++) {
  19664. var mesh = this.meshes[index];
  19665. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  19666. continue;
  19667. }
  19668. mesh.computeWorldMatrix(true);
  19669. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  19670. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  19671. BABYLON.Tools.CheckExtends(minBox, min, max);
  19672. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19673. }
  19674. return {
  19675. min: min,
  19676. max: max
  19677. };
  19678. };
  19679. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  19680. if (maxCapacity === void 0) { maxCapacity = 64; }
  19681. if (maxDepth === void 0) { maxDepth = 2; }
  19682. if (!this._selectionOctree) {
  19683. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  19684. }
  19685. var worldExtends = this.getWorldExtends();
  19686. // Update octree
  19687. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  19688. return this._selectionOctree;
  19689. };
  19690. // Picking
  19691. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  19692. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  19693. var engine = this._engine;
  19694. if (!camera) {
  19695. if (!this.activeCamera)
  19696. throw new Error("Active camera not set");
  19697. camera = this.activeCamera;
  19698. }
  19699. var cameraViewport = camera.viewport;
  19700. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19701. // Moving coordinates to local viewport world
  19702. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19703. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19704. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  19705. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  19706. };
  19707. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  19708. if (!BABYLON.PickingInfo) {
  19709. return null;
  19710. }
  19711. var engine = this._engine;
  19712. if (!camera) {
  19713. if (!this.activeCamera)
  19714. throw new Error("Active camera not set");
  19715. camera = this.activeCamera;
  19716. }
  19717. var cameraViewport = camera.viewport;
  19718. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19719. var identity = BABYLON.Matrix.Identity();
  19720. // Moving coordinates to local viewport world
  19721. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19722. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19723. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  19724. };
  19725. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  19726. if (!BABYLON.PickingInfo) {
  19727. return null;
  19728. }
  19729. var pickingInfo = null;
  19730. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19731. var mesh = this.meshes[meshIndex];
  19732. if (predicate) {
  19733. if (!predicate(mesh)) {
  19734. continue;
  19735. }
  19736. }
  19737. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19738. continue;
  19739. }
  19740. var world = mesh.getWorldMatrix();
  19741. var ray = rayFunction(world);
  19742. var result = mesh.intersects(ray, fastCheck);
  19743. if (!result || !result.hit)
  19744. continue;
  19745. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19746. continue;
  19747. pickingInfo = result;
  19748. if (fastCheck) {
  19749. break;
  19750. }
  19751. }
  19752. return pickingInfo || new BABYLON.PickingInfo();
  19753. };
  19754. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  19755. if (!BABYLON.PickingInfo) {
  19756. return null;
  19757. }
  19758. var pickingInfos = new Array();
  19759. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19760. var mesh = this.meshes[meshIndex];
  19761. if (predicate) {
  19762. if (!predicate(mesh)) {
  19763. continue;
  19764. }
  19765. }
  19766. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19767. continue;
  19768. }
  19769. var world = mesh.getWorldMatrix();
  19770. var ray = rayFunction(world);
  19771. var result = mesh.intersects(ray, false);
  19772. if (!result || !result.hit)
  19773. continue;
  19774. pickingInfos.push(result);
  19775. }
  19776. return pickingInfos;
  19777. };
  19778. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  19779. if (!BABYLON.PickingInfo) {
  19780. return null;
  19781. }
  19782. var pickingInfo = null;
  19783. camera = camera || this.activeCamera;
  19784. if (this.spriteManagers.length > 0) {
  19785. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  19786. var spriteManager = this.spriteManagers[spriteIndex];
  19787. if (!spriteManager.isPickable) {
  19788. continue;
  19789. }
  19790. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  19791. if (!result || !result.hit)
  19792. continue;
  19793. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19794. continue;
  19795. pickingInfo = result;
  19796. if (fastCheck) {
  19797. break;
  19798. }
  19799. }
  19800. }
  19801. return pickingInfo || new BABYLON.PickingInfo();
  19802. };
  19803. /** Launch a ray to try to pick a mesh in the scene
  19804. * @param x position on screen
  19805. * @param y position on screen
  19806. * @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
  19807. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19808. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19809. */
  19810. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  19811. var _this = this;
  19812. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  19813. };
  19814. /** Launch a ray to try to pick a sprite in the scene
  19815. * @param x position on screen
  19816. * @param y position on screen
  19817. * @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
  19818. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19819. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19820. */
  19821. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  19822. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  19823. };
  19824. /** Use the given ray to pick a mesh in the scene
  19825. * @param ray The ray to use to pick meshes
  19826. * @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
  19827. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19828. */
  19829. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  19830. var _this = this;
  19831. return this._internalPick(function (world) {
  19832. if (!_this._pickWithRayInverseMatrix) {
  19833. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19834. }
  19835. world.invertToRef(_this._pickWithRayInverseMatrix);
  19836. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19837. }, predicate, fastCheck);
  19838. };
  19839. /**
  19840. * Launch a ray to try to pick a mesh in the scene
  19841. * @param x X position on screen
  19842. * @param y Y position on screen
  19843. * @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
  19844. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19845. */
  19846. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  19847. var _this = this;
  19848. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  19849. };
  19850. /**
  19851. * Launch a ray to try to pick a mesh in the scene
  19852. * @param ray Ray to use
  19853. * @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
  19854. */
  19855. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  19856. var _this = this;
  19857. return this._internalMultiPick(function (world) {
  19858. if (!_this._pickWithRayInverseMatrix) {
  19859. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19860. }
  19861. world.invertToRef(_this._pickWithRayInverseMatrix);
  19862. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19863. }, predicate);
  19864. };
  19865. Scene.prototype.setPointerOverMesh = function (mesh) {
  19866. if (this._pointerOverMesh === mesh) {
  19867. return;
  19868. }
  19869. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19870. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19871. }
  19872. this._pointerOverMesh = mesh;
  19873. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19874. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19875. }
  19876. };
  19877. Scene.prototype.getPointerOverMesh = function () {
  19878. return this._pointerOverMesh;
  19879. };
  19880. Scene.prototype.setPointerOverSprite = function (sprite) {
  19881. if (this._pointerOverSprite === sprite) {
  19882. return;
  19883. }
  19884. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19885. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19886. }
  19887. this._pointerOverSprite = sprite;
  19888. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19889. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19890. }
  19891. };
  19892. Scene.prototype.getPointerOverSprite = function () {
  19893. return this._pointerOverSprite;
  19894. };
  19895. // Physics
  19896. Scene.prototype.getPhysicsEngine = function () {
  19897. return this._physicsEngine;
  19898. };
  19899. /**
  19900. * Enables physics to the current scene
  19901. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19902. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19903. * @return {boolean} was the physics engine initialized
  19904. */
  19905. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19906. if (this._physicsEngine) {
  19907. return true;
  19908. }
  19909. try {
  19910. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19911. return true;
  19912. }
  19913. catch (e) {
  19914. BABYLON.Tools.Error(e.message);
  19915. return false;
  19916. }
  19917. };
  19918. Scene.prototype.disablePhysicsEngine = function () {
  19919. if (!this._physicsEngine) {
  19920. return;
  19921. }
  19922. this._physicsEngine.dispose();
  19923. this._physicsEngine = undefined;
  19924. };
  19925. Scene.prototype.isPhysicsEnabled = function () {
  19926. return this._physicsEngine !== undefined;
  19927. };
  19928. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19929. var mesh = compound.parts[0].mesh;
  19930. mesh.physicsImpostor.dispose();
  19931. mesh.physicsImpostor = null;
  19932. };
  19933. // Misc.
  19934. Scene.prototype._rebuildGeometries = function () {
  19935. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  19936. var geometry = _a[_i];
  19937. geometry._rebuild();
  19938. }
  19939. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  19940. var mesh = _c[_b];
  19941. mesh._rebuild();
  19942. }
  19943. if (this.postProcessManager) {
  19944. this.postProcessManager._rebuild();
  19945. }
  19946. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  19947. var layer = _e[_d];
  19948. layer._rebuild();
  19949. }
  19950. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  19951. var highlightLayer = _g[_f];
  19952. highlightLayer._rebuild();
  19953. }
  19954. if (this._boundingBoxRenderer) {
  19955. this._boundingBoxRenderer._rebuild();
  19956. }
  19957. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  19958. var system = _j[_h];
  19959. system.rebuild();
  19960. }
  19961. if (this._postProcessRenderPipelineManager) {
  19962. this._postProcessRenderPipelineManager._rebuild();
  19963. }
  19964. };
  19965. Scene.prototype._rebuildTextures = function () {
  19966. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  19967. var texture = _a[_i];
  19968. texture._rebuild();
  19969. }
  19970. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19971. };
  19972. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  19973. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19974. if (replace === void 0) { replace = false; }
  19975. if (attachCameraControls === void 0) { attachCameraControls = false; }
  19976. // Dispose existing camera or light in replace mode.
  19977. if (replace) {
  19978. if (this.activeCamera) {
  19979. this.activeCamera.dispose();
  19980. this.activeCamera = null;
  19981. }
  19982. if (this.lights) {
  19983. for (var i = 0; i < this.lights.length; i++) {
  19984. this.lights[i].dispose();
  19985. }
  19986. }
  19987. }
  19988. // Light
  19989. if (this.lights.length === 0) {
  19990. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19991. }
  19992. // Camera
  19993. if (!this.activeCamera) {
  19994. var worldExtends = this.getWorldExtends();
  19995. var worldSize = worldExtends.max.subtract(worldExtends.min);
  19996. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  19997. var camera;
  19998. var radius = worldSize.length() * 1.5;
  19999. if (createArcRotateCamera) {
  20000. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  20001. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  20002. arcRotateCamera.wheelPrecision = 100 / radius;
  20003. camera = arcRotateCamera;
  20004. }
  20005. else {
  20006. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  20007. freeCamera.setTarget(worldCenter);
  20008. camera = freeCamera;
  20009. }
  20010. camera.minZ = radius * 0.01;
  20011. camera.maxZ = radius * 100;
  20012. camera.speed = radius * 0.2;
  20013. this.activeCamera = camera;
  20014. if (attachCameraControls) {
  20015. camera.attachControl(this.getEngine().getRenderingCanvas());
  20016. }
  20017. }
  20018. };
  20019. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  20020. if (pbr === void 0) { pbr = false; }
  20021. if (scale === void 0) { scale = 1000; }
  20022. if (blur === void 0) { blur = 0; }
  20023. if (environmentTexture) {
  20024. this.environmentTexture = environmentTexture;
  20025. }
  20026. if (!this.environmentTexture) {
  20027. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  20028. return;
  20029. }
  20030. // Skybox
  20031. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  20032. if (pbr) {
  20033. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  20034. hdrSkyboxMaterial.backFaceCulling = false;
  20035. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20036. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20037. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  20038. hdrSkyboxMaterial.disableLighting = true;
  20039. hdrSkyboxMaterial.twoSidedLighting = true;
  20040. hdrSkybox.infiniteDistance = true;
  20041. hdrSkybox.material = hdrSkyboxMaterial;
  20042. }
  20043. else {
  20044. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  20045. skyboxMaterial.backFaceCulling = false;
  20046. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20047. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20048. skyboxMaterial.disableLighting = true;
  20049. hdrSkybox.infiniteDistance = true;
  20050. hdrSkybox.material = skyboxMaterial;
  20051. }
  20052. return hdrSkybox;
  20053. };
  20054. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  20055. if (webVROptions === void 0) { webVROptions = {}; }
  20056. this.VRHelper = new BABYLON.VRExperienceHelper(this, webVROptions);
  20057. };
  20058. // Tags
  20059. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  20060. if (tagsQuery === undefined) {
  20061. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  20062. return list;
  20063. }
  20064. var listByTags = [];
  20065. forEach = forEach || (function (item) { return; });
  20066. for (var i in list) {
  20067. var item = list[i];
  20068. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  20069. listByTags.push(item);
  20070. forEach(item);
  20071. }
  20072. }
  20073. return listByTags;
  20074. };
  20075. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  20076. return this._getByTags(this.meshes, tagsQuery, forEach);
  20077. };
  20078. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  20079. return this._getByTags(this.cameras, tagsQuery, forEach);
  20080. };
  20081. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  20082. return this._getByTags(this.lights, tagsQuery, forEach);
  20083. };
  20084. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  20085. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  20086. };
  20087. /**
  20088. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20089. * This allowed control for front to back rendering or reversly depending of the special needs.
  20090. *
  20091. * @param renderingGroupId The rendering group id corresponding to its index
  20092. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20093. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20094. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20095. */
  20096. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20097. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20098. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20099. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20100. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  20101. };
  20102. /**
  20103. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20104. *
  20105. * @param renderingGroupId The rendering group id corresponding to its index
  20106. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20107. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20108. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20109. */
  20110. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20111. if (depth === void 0) { depth = true; }
  20112. if (stencil === void 0) { stencil = true; }
  20113. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  20114. };
  20115. /**
  20116. * Will flag all materials as dirty to trigger new shader compilation
  20117. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  20118. */
  20119. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  20120. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  20121. var material = _a[_i];
  20122. if (predicate && !predicate(material)) {
  20123. continue;
  20124. }
  20125. material.markAsDirty(flag);
  20126. }
  20127. };
  20128. // Statics
  20129. Scene._FOGMODE_NONE = 0;
  20130. Scene._FOGMODE_EXP = 1;
  20131. Scene._FOGMODE_EXP2 = 2;
  20132. Scene._FOGMODE_LINEAR = 3;
  20133. Scene._uniqueIdCounter = 0;
  20134. Scene.MinDeltaTime = 1.0;
  20135. Scene.MaxDeltaTime = 1000.0;
  20136. /** The distance in pixel that you have to move to prevent some events */
  20137. Scene.DragMovementThreshold = 10; // in pixels
  20138. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  20139. Scene.LongPressDelay = 500; // in milliseconds
  20140. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  20141. Scene.DoubleClickDelay = 300; // in milliseconds
  20142. /** If you need to check double click without raising a single click at first click, enable this flag */
  20143. Scene.ExclusiveDoubleClickMode = false;
  20144. return Scene;
  20145. }());
  20146. BABYLON.Scene = Scene;
  20147. })(BABYLON || (BABYLON = {}));
  20148. //# sourceMappingURL=babylon.scene.js.map
  20149. var BABYLON;
  20150. (function (BABYLON) {
  20151. var Buffer = (function () {
  20152. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  20153. if (engine instanceof BABYLON.Mesh) {
  20154. this._engine = engine.getScene().getEngine();
  20155. }
  20156. else {
  20157. this._engine = engine;
  20158. }
  20159. this._updatable = updatable;
  20160. this._data = data;
  20161. this._strideSize = stride;
  20162. if (!postponeInternalCreation) {
  20163. this.create();
  20164. }
  20165. this._instanced = instanced;
  20166. this._instanceDivisor = instanced ? 1 : 0;
  20167. }
  20168. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  20169. // a lot of these parameters are ignored as they are overriden by the buffer
  20170. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  20171. };
  20172. // Properties
  20173. Buffer.prototype.isUpdatable = function () {
  20174. return this._updatable;
  20175. };
  20176. Buffer.prototype.getData = function () {
  20177. return this._data;
  20178. };
  20179. Buffer.prototype.getBuffer = function () {
  20180. return this._buffer;
  20181. };
  20182. Buffer.prototype.getStrideSize = function () {
  20183. return this._strideSize;
  20184. };
  20185. Buffer.prototype.getIsInstanced = function () {
  20186. return this._instanced;
  20187. };
  20188. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  20189. get: function () {
  20190. return this._instanceDivisor;
  20191. },
  20192. set: function (value) {
  20193. this._instanceDivisor = value;
  20194. if (value == 0) {
  20195. this._instanced = false;
  20196. }
  20197. else {
  20198. this._instanced = true;
  20199. }
  20200. },
  20201. enumerable: true,
  20202. configurable: true
  20203. });
  20204. // Methods
  20205. Buffer.prototype.create = function (data) {
  20206. if (!data && this._buffer) {
  20207. return; // nothing to do
  20208. }
  20209. data = data || this._data;
  20210. if (!this._buffer) {
  20211. if (this._updatable) {
  20212. this._buffer = this._engine.createDynamicVertexBuffer(data);
  20213. this._data = data;
  20214. }
  20215. else {
  20216. this._buffer = this._engine.createVertexBuffer(data);
  20217. }
  20218. }
  20219. else if (this._updatable) {
  20220. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  20221. this._data = data;
  20222. }
  20223. };
  20224. Buffer.prototype._rebuild = function () {
  20225. this._buffer = null;
  20226. this.create(this._data);
  20227. };
  20228. Buffer.prototype.update = function (data) {
  20229. this.create(data);
  20230. };
  20231. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  20232. if (!this._buffer) {
  20233. return;
  20234. }
  20235. if (this._updatable) {
  20236. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  20237. this._data = null;
  20238. }
  20239. };
  20240. Buffer.prototype.dispose = function () {
  20241. if (!this._buffer) {
  20242. return;
  20243. }
  20244. if (this._engine._releaseBuffer(this._buffer)) {
  20245. this._buffer = null;
  20246. }
  20247. };
  20248. return Buffer;
  20249. }());
  20250. BABYLON.Buffer = Buffer;
  20251. })(BABYLON || (BABYLON = {}));
  20252. //# sourceMappingURL=babylon.buffer.js.map
  20253. var BABYLON;
  20254. (function (BABYLON) {
  20255. var VertexBuffer = (function () {
  20256. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  20257. if (!stride) {
  20258. // Deduce stride from kind
  20259. switch (kind) {
  20260. case VertexBuffer.PositionKind:
  20261. stride = 3;
  20262. break;
  20263. case VertexBuffer.NormalKind:
  20264. stride = 3;
  20265. break;
  20266. case VertexBuffer.UVKind:
  20267. case VertexBuffer.UV2Kind:
  20268. case VertexBuffer.UV3Kind:
  20269. case VertexBuffer.UV4Kind:
  20270. case VertexBuffer.UV5Kind:
  20271. case VertexBuffer.UV6Kind:
  20272. stride = 2;
  20273. break;
  20274. case VertexBuffer.TangentKind:
  20275. case VertexBuffer.ColorKind:
  20276. stride = 4;
  20277. break;
  20278. case VertexBuffer.MatricesIndicesKind:
  20279. case VertexBuffer.MatricesIndicesExtraKind:
  20280. stride = 4;
  20281. break;
  20282. case VertexBuffer.MatricesWeightsKind:
  20283. case VertexBuffer.MatricesWeightsExtraKind:
  20284. stride = 4;
  20285. break;
  20286. }
  20287. }
  20288. if (data instanceof BABYLON.Buffer) {
  20289. if (!stride) {
  20290. stride = data.getStrideSize();
  20291. }
  20292. this._buffer = data;
  20293. this._ownsBuffer = false;
  20294. }
  20295. else {
  20296. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  20297. this._ownsBuffer = true;
  20298. }
  20299. this._stride = stride;
  20300. this._offset = offset ? offset : 0;
  20301. this._size = size ? size : stride;
  20302. this._kind = kind;
  20303. }
  20304. VertexBuffer.prototype._rebuild = function () {
  20305. if (!this._buffer) {
  20306. return;
  20307. }
  20308. this._buffer._rebuild();
  20309. };
  20310. /**
  20311. * Returns the kind of the VertexBuffer (string).
  20312. */
  20313. VertexBuffer.prototype.getKind = function () {
  20314. return this._kind;
  20315. };
  20316. // Properties
  20317. /**
  20318. * Boolean : is the VertexBuffer updatable ?
  20319. */
  20320. VertexBuffer.prototype.isUpdatable = function () {
  20321. return this._buffer.isUpdatable();
  20322. };
  20323. /**
  20324. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  20325. */
  20326. VertexBuffer.prototype.getData = function () {
  20327. return this._buffer.getData();
  20328. };
  20329. /**
  20330. * Returns the WebGLBuffer associated to the VertexBuffer.
  20331. */
  20332. VertexBuffer.prototype.getBuffer = function () {
  20333. return this._buffer.getBuffer();
  20334. };
  20335. /**
  20336. * Returns the stride of the VertexBuffer (integer).
  20337. */
  20338. VertexBuffer.prototype.getStrideSize = function () {
  20339. return this._stride;
  20340. };
  20341. /**
  20342. * Returns the offset (integer).
  20343. */
  20344. VertexBuffer.prototype.getOffset = function () {
  20345. return this._offset;
  20346. };
  20347. /**
  20348. * Returns the VertexBuffer total size (integer).
  20349. */
  20350. VertexBuffer.prototype.getSize = function () {
  20351. return this._size;
  20352. };
  20353. /**
  20354. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  20355. */
  20356. VertexBuffer.prototype.getIsInstanced = function () {
  20357. return this._buffer.getIsInstanced();
  20358. };
  20359. /**
  20360. * Returns the instancing divisor, zero for non-instanced (integer).
  20361. */
  20362. VertexBuffer.prototype.getInstanceDivisor = function () {
  20363. return this._buffer.instanceDivisor;
  20364. };
  20365. // Methods
  20366. /**
  20367. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  20368. * Returns the created WebGLBuffer.
  20369. */
  20370. VertexBuffer.prototype.create = function (data) {
  20371. return this._buffer.create(data);
  20372. };
  20373. /**
  20374. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  20375. * Returns the updated WebGLBuffer.
  20376. */
  20377. VertexBuffer.prototype.update = function (data) {
  20378. return this._buffer.update(data);
  20379. };
  20380. /**
  20381. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  20382. * Returns the directly updated WebGLBuffer.
  20383. */
  20384. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  20385. return this._buffer.updateDirectly(data, offset);
  20386. };
  20387. /**
  20388. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  20389. */
  20390. VertexBuffer.prototype.dispose = function () {
  20391. if (this._ownsBuffer) {
  20392. this._buffer.dispose();
  20393. }
  20394. };
  20395. Object.defineProperty(VertexBuffer, "PositionKind", {
  20396. get: function () {
  20397. return VertexBuffer._PositionKind;
  20398. },
  20399. enumerable: true,
  20400. configurable: true
  20401. });
  20402. Object.defineProperty(VertexBuffer, "NormalKind", {
  20403. get: function () {
  20404. return VertexBuffer._NormalKind;
  20405. },
  20406. enumerable: true,
  20407. configurable: true
  20408. });
  20409. Object.defineProperty(VertexBuffer, "TangentKind", {
  20410. get: function () {
  20411. return VertexBuffer._TangentKind;
  20412. },
  20413. enumerable: true,
  20414. configurable: true
  20415. });
  20416. Object.defineProperty(VertexBuffer, "UVKind", {
  20417. get: function () {
  20418. return VertexBuffer._UVKind;
  20419. },
  20420. enumerable: true,
  20421. configurable: true
  20422. });
  20423. Object.defineProperty(VertexBuffer, "UV2Kind", {
  20424. get: function () {
  20425. return VertexBuffer._UV2Kind;
  20426. },
  20427. enumerable: true,
  20428. configurable: true
  20429. });
  20430. Object.defineProperty(VertexBuffer, "UV3Kind", {
  20431. get: function () {
  20432. return VertexBuffer._UV3Kind;
  20433. },
  20434. enumerable: true,
  20435. configurable: true
  20436. });
  20437. Object.defineProperty(VertexBuffer, "UV4Kind", {
  20438. get: function () {
  20439. return VertexBuffer._UV4Kind;
  20440. },
  20441. enumerable: true,
  20442. configurable: true
  20443. });
  20444. Object.defineProperty(VertexBuffer, "UV5Kind", {
  20445. get: function () {
  20446. return VertexBuffer._UV5Kind;
  20447. },
  20448. enumerable: true,
  20449. configurable: true
  20450. });
  20451. Object.defineProperty(VertexBuffer, "UV6Kind", {
  20452. get: function () {
  20453. return VertexBuffer._UV6Kind;
  20454. },
  20455. enumerable: true,
  20456. configurable: true
  20457. });
  20458. Object.defineProperty(VertexBuffer, "ColorKind", {
  20459. get: function () {
  20460. return VertexBuffer._ColorKind;
  20461. },
  20462. enumerable: true,
  20463. configurable: true
  20464. });
  20465. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  20466. get: function () {
  20467. return VertexBuffer._MatricesIndicesKind;
  20468. },
  20469. enumerable: true,
  20470. configurable: true
  20471. });
  20472. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  20473. get: function () {
  20474. return VertexBuffer._MatricesWeightsKind;
  20475. },
  20476. enumerable: true,
  20477. configurable: true
  20478. });
  20479. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  20480. get: function () {
  20481. return VertexBuffer._MatricesIndicesExtraKind;
  20482. },
  20483. enumerable: true,
  20484. configurable: true
  20485. });
  20486. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  20487. get: function () {
  20488. return VertexBuffer._MatricesWeightsExtraKind;
  20489. },
  20490. enumerable: true,
  20491. configurable: true
  20492. });
  20493. // Enums
  20494. VertexBuffer._PositionKind = "position";
  20495. VertexBuffer._NormalKind = "normal";
  20496. VertexBuffer._TangentKind = "tangent";
  20497. VertexBuffer._UVKind = "uv";
  20498. VertexBuffer._UV2Kind = "uv2";
  20499. VertexBuffer._UV3Kind = "uv3";
  20500. VertexBuffer._UV4Kind = "uv4";
  20501. VertexBuffer._UV5Kind = "uv5";
  20502. VertexBuffer._UV6Kind = "uv6";
  20503. VertexBuffer._ColorKind = "color";
  20504. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  20505. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  20506. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  20507. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  20508. return VertexBuffer;
  20509. }());
  20510. BABYLON.VertexBuffer = VertexBuffer;
  20511. })(BABYLON || (BABYLON = {}));
  20512. //# sourceMappingURL=babylon.vertexBuffer.js.map
  20513. var BABYLON;
  20514. (function (BABYLON) {
  20515. var InternalTexture = (function () {
  20516. function InternalTexture(engine, dataSource) {
  20517. this.onLoadedObservable = new BABYLON.Observable();
  20518. // Private
  20519. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  20520. this._references = 1;
  20521. this._engine = engine;
  20522. this._dataSource = dataSource;
  20523. this._webGLTexture = engine._createTexture();
  20524. }
  20525. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  20526. get: function () {
  20527. return this._dataSource;
  20528. },
  20529. enumerable: true,
  20530. configurable: true
  20531. });
  20532. InternalTexture.prototype.incrementReferences = function () {
  20533. this._references++;
  20534. };
  20535. InternalTexture.prototype.updateSize = function (width, height) {
  20536. this.width = width;
  20537. this.height = height;
  20538. this._size = width * height;
  20539. this.baseWidth = width;
  20540. this.baseHeight = height;
  20541. };
  20542. InternalTexture.prototype._rebuild = function () {
  20543. var _this = this;
  20544. var proxy;
  20545. this.isReady = false;
  20546. this._cachedCoordinatesMode = null;
  20547. this._cachedWrapU = null;
  20548. this._cachedWrapV = null;
  20549. this._cachedAnisotropicFilteringLevel = null;
  20550. switch (this._dataSource) {
  20551. case InternalTexture.DATASOURCE_TEMP:
  20552. return;
  20553. case InternalTexture.DATASOURCE_URL:
  20554. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  20555. _this.isReady = true;
  20556. }, null, this._buffer, null, this.format);
  20557. proxy._swapAndDie(this);
  20558. return;
  20559. case InternalTexture.DATASOURCE_RAW:
  20560. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20561. proxy._swapAndDie(this);
  20562. this.isReady = true;
  20563. return;
  20564. case InternalTexture.DATASOURCE_DYNAMIC:
  20565. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  20566. proxy._swapAndDie(this);
  20567. // The engine will make sure to update content so no need to flag it as isReady = true
  20568. return;
  20569. case InternalTexture.DATASOURCE_RENDERTARGET:
  20570. var options = new BABYLON.RenderTargetCreationOptions();
  20571. options.generateDepthBuffer = this._generateDepthBuffer;
  20572. options.generateMipMaps = this.generateMipMaps;
  20573. options.generateStencilBuffer = this._generateStencilBuffer;
  20574. options.samplingMode = this.samplingMode;
  20575. options.type = this.type;
  20576. if (this.isCube) {
  20577. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  20578. }
  20579. else {
  20580. var size = {
  20581. width: this.width,
  20582. height: this.height
  20583. };
  20584. proxy = this._engine.createRenderTargetTexture(size, options);
  20585. }
  20586. proxy._swapAndDie(this);
  20587. this.isReady = true;
  20588. return;
  20589. case InternalTexture.DATASOURCE_CUBE:
  20590. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  20591. _this.isReady = true;
  20592. }, null, this.format, this._extension);
  20593. proxy._swapAndDie(this);
  20594. return;
  20595. case InternalTexture.DATASOURCE_CUBERAW:
  20596. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  20597. proxy._swapAndDie(this);
  20598. this.isReady = true;
  20599. return;
  20600. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  20601. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  20602. proxy._swapAndDie(_this);
  20603. _this.isReady = true;
  20604. }, null, this.format, this._extension);
  20605. return;
  20606. }
  20607. };
  20608. InternalTexture.prototype._swapAndDie = function (target) {
  20609. target._webGLTexture = this._webGLTexture;
  20610. if (this._framebuffer) {
  20611. target._framebuffer = this._framebuffer;
  20612. }
  20613. if (this._depthStencilBuffer) {
  20614. target._depthStencilBuffer = this._depthStencilBuffer;
  20615. }
  20616. if (this._lodTextureHigh) {
  20617. if (target._lodTextureHigh) {
  20618. target._lodTextureHigh.dispose();
  20619. }
  20620. target._lodTextureHigh = this._lodTextureHigh;
  20621. }
  20622. if (this._lodTextureMid) {
  20623. if (target._lodTextureMid) {
  20624. target._lodTextureMid.dispose();
  20625. }
  20626. target._lodTextureMid = this._lodTextureMid;
  20627. }
  20628. if (this._lodTextureLow) {
  20629. if (target._lodTextureLow) {
  20630. target._lodTextureLow.dispose();
  20631. }
  20632. target._lodTextureLow = this._lodTextureLow;
  20633. }
  20634. var cache = this._engine.getLoadedTexturesCache();
  20635. var index = cache.indexOf(this);
  20636. if (index !== -1) {
  20637. cache.splice(index, 1);
  20638. }
  20639. };
  20640. InternalTexture.prototype.dispose = function () {
  20641. if (!this._webGLTexture) {
  20642. return;
  20643. }
  20644. this._references--;
  20645. if (this._references === 0) {
  20646. this._engine._releaseTexture(this);
  20647. this._webGLTexture = null;
  20648. }
  20649. };
  20650. InternalTexture.DATASOURCE_UNKNOWN = 0;
  20651. InternalTexture.DATASOURCE_URL = 1;
  20652. InternalTexture.DATASOURCE_TEMP = 2;
  20653. InternalTexture.DATASOURCE_RAW = 3;
  20654. InternalTexture.DATASOURCE_DYNAMIC = 4;
  20655. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  20656. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  20657. InternalTexture.DATASOURCE_CUBE = 7;
  20658. InternalTexture.DATASOURCE_CUBERAW = 8;
  20659. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  20660. return InternalTexture;
  20661. }());
  20662. BABYLON.InternalTexture = InternalTexture;
  20663. })(BABYLON || (BABYLON = {}));
  20664. //# sourceMappingURL=babylon.internalTexture.js.map
  20665. var BABYLON;
  20666. (function (BABYLON) {
  20667. var BaseTexture = (function () {
  20668. function BaseTexture(scene) {
  20669. this._hasAlpha = false;
  20670. this.getAlphaFromRGB = false;
  20671. this.level = 1;
  20672. this.coordinatesIndex = 0;
  20673. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20674. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20675. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20676. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  20677. this.isCube = false;
  20678. this.gammaSpace = true;
  20679. this.invertZ = false;
  20680. this.lodLevelInAlpha = false;
  20681. this.lodGenerationOffset = 0.0;
  20682. this.lodGenerationScale = 0.8;
  20683. this.isRenderTarget = false;
  20684. this.animations = new Array();
  20685. /**
  20686. * An event triggered when the texture is disposed.
  20687. * @type {BABYLON.Observable}
  20688. */
  20689. this.onDisposeObservable = new BABYLON.Observable();
  20690. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20691. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  20692. this._scene.textures.push(this);
  20693. this._uid = null;
  20694. }
  20695. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  20696. get: function () {
  20697. return this._hasAlpha;
  20698. },
  20699. set: function (value) {
  20700. if (this._hasAlpha === value) {
  20701. return;
  20702. }
  20703. this._hasAlpha = value;
  20704. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20705. },
  20706. enumerable: true,
  20707. configurable: true
  20708. });
  20709. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  20710. get: function () {
  20711. return this._coordinatesMode;
  20712. },
  20713. set: function (value) {
  20714. if (this._coordinatesMode === value) {
  20715. return;
  20716. }
  20717. this._coordinatesMode = value;
  20718. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20719. },
  20720. enumerable: true,
  20721. configurable: true
  20722. });
  20723. Object.defineProperty(BaseTexture.prototype, "uid", {
  20724. get: function () {
  20725. if (!this._uid) {
  20726. this._uid = BABYLON.Tools.RandomId();
  20727. }
  20728. return this._uid;
  20729. },
  20730. enumerable: true,
  20731. configurable: true
  20732. });
  20733. BaseTexture.prototype.toString = function () {
  20734. return this.name;
  20735. };
  20736. BaseTexture.prototype.getClassName = function () {
  20737. return "BaseTexture";
  20738. };
  20739. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  20740. set: function (callback) {
  20741. if (this._onDisposeObserver) {
  20742. this.onDisposeObservable.remove(this._onDisposeObserver);
  20743. }
  20744. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20745. },
  20746. enumerable: true,
  20747. configurable: true
  20748. });
  20749. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  20750. get: function () {
  20751. return true;
  20752. },
  20753. enumerable: true,
  20754. configurable: true
  20755. });
  20756. BaseTexture.prototype.getScene = function () {
  20757. return this._scene;
  20758. };
  20759. BaseTexture.prototype.getTextureMatrix = function () {
  20760. return null;
  20761. };
  20762. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20763. return null;
  20764. };
  20765. BaseTexture.prototype.getInternalTexture = function () {
  20766. return this._texture;
  20767. };
  20768. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  20769. return !this.isBlocking || this.isReady();
  20770. };
  20771. BaseTexture.prototype.isReady = function () {
  20772. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20773. this.delayLoad();
  20774. return false;
  20775. }
  20776. if (this._texture) {
  20777. return this._texture.isReady;
  20778. }
  20779. return false;
  20780. };
  20781. BaseTexture.prototype.getSize = function () {
  20782. if (this._texture.width) {
  20783. return new BABYLON.Size(this._texture.width, this._texture.height);
  20784. }
  20785. if (this._texture._size) {
  20786. return new BABYLON.Size(this._texture._size, this._texture._size);
  20787. }
  20788. return BABYLON.Size.Zero();
  20789. };
  20790. BaseTexture.prototype.getBaseSize = function () {
  20791. if (!this.isReady() || !this._texture)
  20792. return BABYLON.Size.Zero();
  20793. if (this._texture._size) {
  20794. return new BABYLON.Size(this._texture._size, this._texture._size);
  20795. }
  20796. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  20797. };
  20798. BaseTexture.prototype.scale = function (ratio) {
  20799. };
  20800. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20801. get: function () {
  20802. return false;
  20803. },
  20804. enumerable: true,
  20805. configurable: true
  20806. });
  20807. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20808. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20809. for (var index = 0; index < texturesCache.length; index++) {
  20810. var texturesCacheEntry = texturesCache[index];
  20811. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  20812. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20813. texturesCacheEntry.incrementReferences();
  20814. return texturesCacheEntry;
  20815. }
  20816. }
  20817. }
  20818. return null;
  20819. };
  20820. BaseTexture.prototype._rebuild = function () {
  20821. };
  20822. BaseTexture.prototype.delayLoad = function () {
  20823. };
  20824. BaseTexture.prototype.clone = function () {
  20825. return null;
  20826. };
  20827. Object.defineProperty(BaseTexture.prototype, "textureType", {
  20828. get: function () {
  20829. if (!this._texture) {
  20830. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20831. }
  20832. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20833. },
  20834. enumerable: true,
  20835. configurable: true
  20836. });
  20837. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  20838. get: function () {
  20839. if (!this._texture) {
  20840. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20841. }
  20842. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20843. },
  20844. enumerable: true,
  20845. configurable: true
  20846. });
  20847. BaseTexture.prototype.readPixels = function (faceIndex) {
  20848. if (faceIndex === void 0) { faceIndex = 0; }
  20849. if (!this._texture) {
  20850. return null;
  20851. }
  20852. var size = this.getSize();
  20853. var engine = this.getScene().getEngine();
  20854. if (this._texture.isCube) {
  20855. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  20856. }
  20857. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  20858. };
  20859. BaseTexture.prototype.releaseInternalTexture = function () {
  20860. if (this._texture) {
  20861. this._texture.dispose();
  20862. this._texture = null;
  20863. }
  20864. };
  20865. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  20866. get: function () {
  20867. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  20868. return null;
  20869. }
  20870. if (!this._texture._sphericalPolynomial) {
  20871. this._texture._sphericalPolynomial =
  20872. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  20873. }
  20874. return this._texture._sphericalPolynomial;
  20875. },
  20876. set: function (value) {
  20877. if (this._texture) {
  20878. this._texture._sphericalPolynomial = value;
  20879. }
  20880. },
  20881. enumerable: true,
  20882. configurable: true
  20883. });
  20884. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  20885. get: function () {
  20886. if (this._texture) {
  20887. return this._texture._lodTextureHigh;
  20888. }
  20889. return null;
  20890. },
  20891. enumerable: true,
  20892. configurable: true
  20893. });
  20894. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  20895. get: function () {
  20896. if (this._texture) {
  20897. return this._texture._lodTextureMid;
  20898. }
  20899. return null;
  20900. },
  20901. enumerable: true,
  20902. configurable: true
  20903. });
  20904. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  20905. get: function () {
  20906. if (this._texture) {
  20907. return this._texture._lodTextureLow;
  20908. }
  20909. return null;
  20910. },
  20911. enumerable: true,
  20912. configurable: true
  20913. });
  20914. BaseTexture.prototype.dispose = function () {
  20915. // Animations
  20916. this.getScene().stopAnimation(this);
  20917. // Remove from scene
  20918. this._scene._removePendingData(this);
  20919. var index = this._scene.textures.indexOf(this);
  20920. if (index >= 0) {
  20921. this._scene.textures.splice(index, 1);
  20922. }
  20923. if (this._texture === undefined) {
  20924. return;
  20925. }
  20926. // Release
  20927. this.releaseInternalTexture();
  20928. // Callback
  20929. this.onDisposeObservable.notifyObservers(this);
  20930. this.onDisposeObservable.clear();
  20931. };
  20932. BaseTexture.prototype.serialize = function () {
  20933. if (!this.name) {
  20934. return null;
  20935. }
  20936. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20937. // Animations
  20938. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20939. return serializationObject;
  20940. };
  20941. BaseTexture.WhenAllReady = function (textures, callback) {
  20942. var numRemaining = textures.length;
  20943. if (numRemaining === 0) {
  20944. callback();
  20945. return;
  20946. }
  20947. var _loop_1 = function () {
  20948. texture = textures[i];
  20949. if (texture.isReady()) {
  20950. if (--numRemaining === 0) {
  20951. callback();
  20952. }
  20953. }
  20954. else {
  20955. onLoadObservable = texture.onLoadObservable;
  20956. var onLoadCallback_1 = function () {
  20957. onLoadObservable.removeCallback(onLoadCallback_1);
  20958. if (--numRemaining === 0) {
  20959. callback();
  20960. }
  20961. };
  20962. onLoadObservable.add(onLoadCallback_1);
  20963. }
  20964. };
  20965. var texture, onLoadObservable;
  20966. for (var i = 0; i < textures.length; i++) {
  20967. _loop_1();
  20968. }
  20969. };
  20970. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  20971. __decorate([
  20972. BABYLON.serialize()
  20973. ], BaseTexture.prototype, "name", void 0);
  20974. __decorate([
  20975. BABYLON.serialize("hasAlpha")
  20976. ], BaseTexture.prototype, "_hasAlpha", void 0);
  20977. __decorate([
  20978. BABYLON.serialize()
  20979. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20980. __decorate([
  20981. BABYLON.serialize()
  20982. ], BaseTexture.prototype, "level", void 0);
  20983. __decorate([
  20984. BABYLON.serialize()
  20985. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20986. __decorate([
  20987. BABYLON.serialize("coordinatesMode")
  20988. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  20989. __decorate([
  20990. BABYLON.serialize()
  20991. ], BaseTexture.prototype, "wrapU", void 0);
  20992. __decorate([
  20993. BABYLON.serialize()
  20994. ], BaseTexture.prototype, "wrapV", void 0);
  20995. __decorate([
  20996. BABYLON.serialize()
  20997. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20998. __decorate([
  20999. BABYLON.serialize()
  21000. ], BaseTexture.prototype, "isCube", void 0);
  21001. __decorate([
  21002. BABYLON.serialize()
  21003. ], BaseTexture.prototype, "gammaSpace", void 0);
  21004. __decorate([
  21005. BABYLON.serialize()
  21006. ], BaseTexture.prototype, "invertZ", void 0);
  21007. __decorate([
  21008. BABYLON.serialize()
  21009. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  21010. __decorate([
  21011. BABYLON.serialize()
  21012. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  21013. __decorate([
  21014. BABYLON.serialize()
  21015. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  21016. __decorate([
  21017. BABYLON.serialize()
  21018. ], BaseTexture.prototype, "isRenderTarget", void 0);
  21019. return BaseTexture;
  21020. }());
  21021. BABYLON.BaseTexture = BaseTexture;
  21022. })(BABYLON || (BABYLON = {}));
  21023. //# sourceMappingURL=babylon.baseTexture.js.map
  21024. var BABYLON;
  21025. (function (BABYLON) {
  21026. var Texture = (function (_super) {
  21027. __extends(Texture, _super);
  21028. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  21029. if (noMipmap === void 0) { noMipmap = false; }
  21030. if (invertY === void 0) { invertY = true; }
  21031. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21032. if (onLoad === void 0) { onLoad = null; }
  21033. if (onError === void 0) { onError = null; }
  21034. if (buffer === void 0) { buffer = null; }
  21035. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21036. var _this = _super.call(this, scene) || this;
  21037. _this.uOffset = 0;
  21038. _this.vOffset = 0;
  21039. _this.uScale = 1.0;
  21040. _this.vScale = 1.0;
  21041. _this.uAng = 0;
  21042. _this.vAng = 0;
  21043. _this.wAng = 0;
  21044. _this._isBlocking = true;
  21045. _this.name = url;
  21046. _this.url = url;
  21047. _this._noMipmap = noMipmap;
  21048. _this._invertY = invertY;
  21049. _this._samplingMode = samplingMode;
  21050. _this._buffer = buffer;
  21051. _this._deleteBuffer = deleteBuffer;
  21052. _this._format = format;
  21053. scene = _this.getScene();
  21054. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  21055. var load = function () {
  21056. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  21057. _this.onLoadObservable.notifyObservers(_this);
  21058. }
  21059. if (onLoad) {
  21060. onLoad();
  21061. }
  21062. if (!_this.isBlocking) {
  21063. scene.resetCachedMaterial();
  21064. }
  21065. };
  21066. if (!_this.url) {
  21067. _this._delayedOnLoad = load;
  21068. _this._delayedOnError = onError;
  21069. return _this;
  21070. }
  21071. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  21072. if (!_this._texture) {
  21073. if (!scene.useDelayedTextureLoading) {
  21074. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  21075. if (deleteBuffer) {
  21076. delete _this._buffer;
  21077. }
  21078. }
  21079. else {
  21080. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21081. _this._delayedOnLoad = load;
  21082. _this._delayedOnError = onError;
  21083. }
  21084. }
  21085. else {
  21086. if (_this._texture.isReady) {
  21087. BABYLON.Tools.SetImmediate(function () { return load(); });
  21088. }
  21089. else {
  21090. _this._texture.onLoadedObservable.add(load);
  21091. }
  21092. }
  21093. return _this;
  21094. }
  21095. Object.defineProperty(Texture.prototype, "noMipmap", {
  21096. get: function () {
  21097. return this._noMipmap;
  21098. },
  21099. enumerable: true,
  21100. configurable: true
  21101. });
  21102. Object.defineProperty(Texture.prototype, "isBlocking", {
  21103. get: function () {
  21104. return this._isBlocking;
  21105. },
  21106. set: function (value) {
  21107. this._isBlocking = value;
  21108. },
  21109. enumerable: true,
  21110. configurable: true
  21111. });
  21112. Object.defineProperty(Texture.prototype, "samplingMode", {
  21113. get: function () {
  21114. return this._samplingMode;
  21115. },
  21116. enumerable: true,
  21117. configurable: true
  21118. });
  21119. Texture.prototype.updateURL = function (url) {
  21120. this.url = url;
  21121. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21122. this.delayLoad();
  21123. };
  21124. Texture.prototype.delayLoad = function () {
  21125. var _this = this;
  21126. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21127. return;
  21128. }
  21129. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21130. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  21131. if (!this._texture) {
  21132. 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);
  21133. if (this._deleteBuffer) {
  21134. delete this._buffer;
  21135. }
  21136. }
  21137. else {
  21138. if (this._texture.isReady) {
  21139. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  21140. }
  21141. else {
  21142. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  21143. }
  21144. }
  21145. };
  21146. Texture.prototype.updateSamplingMode = function (samplingMode) {
  21147. if (!this._texture) {
  21148. return;
  21149. }
  21150. this._samplingMode = samplingMode;
  21151. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  21152. };
  21153. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  21154. x *= this.uScale;
  21155. y *= this.vScale;
  21156. x -= 0.5 * this.uScale;
  21157. y -= 0.5 * this.vScale;
  21158. z -= 0.5;
  21159. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  21160. t.x += 0.5 * this.uScale + this.uOffset;
  21161. t.y += 0.5 * this.vScale + this.vOffset;
  21162. t.z += 0.5;
  21163. };
  21164. Texture.prototype.getTextureMatrix = function () {
  21165. var _this = this;
  21166. if (this.uOffset === this._cachedUOffset &&
  21167. this.vOffset === this._cachedVOffset &&
  21168. this.uScale === this._cachedUScale &&
  21169. this.vScale === this._cachedVScale &&
  21170. this.uAng === this._cachedUAng &&
  21171. this.vAng === this._cachedVAng &&
  21172. this.wAng === this._cachedWAng) {
  21173. return this._cachedTextureMatrix;
  21174. }
  21175. this._cachedUOffset = this.uOffset;
  21176. this._cachedVOffset = this.vOffset;
  21177. this._cachedUScale = this.uScale;
  21178. this._cachedVScale = this.vScale;
  21179. this._cachedUAng = this.uAng;
  21180. this._cachedVAng = this.vAng;
  21181. this._cachedWAng = this.wAng;
  21182. if (!this._cachedTextureMatrix) {
  21183. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21184. this._rowGenerationMatrix = new BABYLON.Matrix();
  21185. this._t0 = BABYLON.Vector3.Zero();
  21186. this._t1 = BABYLON.Vector3.Zero();
  21187. this._t2 = BABYLON.Vector3.Zero();
  21188. }
  21189. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  21190. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  21191. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  21192. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  21193. this._t1.subtractInPlace(this._t0);
  21194. this._t2.subtractInPlace(this._t0);
  21195. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21196. this._cachedTextureMatrix.m[0] = this._t1.x;
  21197. this._cachedTextureMatrix.m[1] = this._t1.y;
  21198. this._cachedTextureMatrix.m[2] = this._t1.z;
  21199. this._cachedTextureMatrix.m[4] = this._t2.x;
  21200. this._cachedTextureMatrix.m[5] = this._t2.y;
  21201. this._cachedTextureMatrix.m[6] = this._t2.z;
  21202. this._cachedTextureMatrix.m[8] = this._t0.x;
  21203. this._cachedTextureMatrix.m[9] = this._t0.y;
  21204. this._cachedTextureMatrix.m[10] = this._t0.z;
  21205. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  21206. return mat.hasTexture(_this);
  21207. });
  21208. return this._cachedTextureMatrix;
  21209. };
  21210. Texture.prototype.getReflectionTextureMatrix = function () {
  21211. var _this = this;
  21212. var scene = this.getScene();
  21213. if (this.uOffset === this._cachedUOffset &&
  21214. this.vOffset === this._cachedVOffset &&
  21215. this.uScale === this._cachedUScale &&
  21216. this.vScale === this._cachedVScale &&
  21217. this.coordinatesMode === this._cachedCoordinatesMode) {
  21218. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  21219. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  21220. return this._cachedTextureMatrix;
  21221. }
  21222. }
  21223. else {
  21224. return this._cachedTextureMatrix;
  21225. }
  21226. }
  21227. if (!this._cachedTextureMatrix) {
  21228. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  21229. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  21230. }
  21231. this._cachedUOffset = this.uOffset;
  21232. this._cachedVOffset = this.vOffset;
  21233. this._cachedUScale = this.uScale;
  21234. this._cachedVScale = this.vScale;
  21235. this._cachedCoordinatesMode = this.coordinatesMode;
  21236. switch (this.coordinatesMode) {
  21237. case Texture.PLANAR_MODE:
  21238. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21239. this._cachedTextureMatrix[0] = this.uScale;
  21240. this._cachedTextureMatrix[5] = this.vScale;
  21241. this._cachedTextureMatrix[12] = this.uOffset;
  21242. this._cachedTextureMatrix[13] = this.vOffset;
  21243. break;
  21244. case Texture.PROJECTION_MODE:
  21245. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  21246. this._projectionModeMatrix.m[0] = 0.5;
  21247. this._projectionModeMatrix.m[5] = -0.5;
  21248. this._projectionModeMatrix.m[10] = 0.0;
  21249. this._projectionModeMatrix.m[12] = 0.5;
  21250. this._projectionModeMatrix.m[13] = 0.5;
  21251. this._projectionModeMatrix.m[14] = 1.0;
  21252. this._projectionModeMatrix.m[15] = 1.0;
  21253. var projectionMatrix = scene.getProjectionMatrix();
  21254. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  21255. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  21256. break;
  21257. default:
  21258. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  21259. break;
  21260. }
  21261. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  21262. return (mat.getActiveTextures().indexOf(_this) !== -1);
  21263. });
  21264. return this._cachedTextureMatrix;
  21265. };
  21266. Texture.prototype.clone = function () {
  21267. var _this = this;
  21268. return BABYLON.SerializationHelper.Clone(function () {
  21269. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  21270. }, this);
  21271. };
  21272. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  21273. get: function () {
  21274. if (!this._onLoadObservable) {
  21275. this._onLoadObservable = new BABYLON.Observable();
  21276. }
  21277. return this._onLoadObservable;
  21278. },
  21279. enumerable: true,
  21280. configurable: true
  21281. });
  21282. Texture.prototype.serialize = function () {
  21283. var serializationObject = _super.prototype.serialize.call(this);
  21284. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  21285. serializationObject.base64String = this._buffer;
  21286. serializationObject.name = serializationObject.name.replace("data:", "");
  21287. }
  21288. return serializationObject;
  21289. };
  21290. Texture.prototype.getClassName = function () {
  21291. return "Texture";
  21292. };
  21293. Texture.prototype.dispose = function () {
  21294. _super.prototype.dispose.call(this);
  21295. if (this.onLoadObservable) {
  21296. this.onLoadObservable.clear();
  21297. this._onLoadObservable = null;
  21298. }
  21299. this._delayedOnLoad = null;
  21300. this._delayedOnError = null;
  21301. };
  21302. // Statics
  21303. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  21304. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21305. if (onLoad === void 0) { onLoad = null; }
  21306. if (onError === void 0) { onError = null; }
  21307. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  21308. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  21309. };
  21310. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  21311. if (parsedTexture.customType) {
  21312. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  21313. // Update Sampling Mode
  21314. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  21315. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  21316. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  21317. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  21318. }
  21319. }
  21320. return parsedCustomTexture;
  21321. }
  21322. if (parsedTexture.isCube) {
  21323. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  21324. }
  21325. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  21326. return null;
  21327. }
  21328. var texture = BABYLON.SerializationHelper.Parse(function () {
  21329. if (parsedTexture.mirrorPlane) {
  21330. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21331. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  21332. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  21333. return mirrorTexture;
  21334. }
  21335. else if (parsedTexture.isRenderTarget) {
  21336. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  21337. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  21338. return renderTargetTexture;
  21339. }
  21340. else {
  21341. var texture;
  21342. if (parsedTexture.base64String) {
  21343. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  21344. }
  21345. else {
  21346. texture = new Texture(rootUrl + parsedTexture.name, scene);
  21347. }
  21348. return texture;
  21349. }
  21350. }, parsedTexture, scene);
  21351. // Update Sampling Mode
  21352. if (parsedTexture.samplingMode) {
  21353. var sampling = parsedTexture.samplingMode;
  21354. if (texture._samplingMode !== sampling) {
  21355. texture.updateSamplingMode(sampling);
  21356. }
  21357. }
  21358. // Animations
  21359. if (parsedTexture.animations) {
  21360. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  21361. var parsedAnimation = parsedTexture.animations[animationIndex];
  21362. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21363. }
  21364. }
  21365. return texture;
  21366. };
  21367. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  21368. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21369. if (noMipmap === void 0) { noMipmap = false; }
  21370. if (invertY === void 0) { invertY = true; }
  21371. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21372. if (onLoad === void 0) { onLoad = null; }
  21373. if (onError === void 0) { onError = null; }
  21374. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  21375. if (name.substr(0, 5) !== "data:") {
  21376. name = "data:" + name;
  21377. }
  21378. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  21379. };
  21380. // Constants
  21381. Texture.NEAREST_SAMPLINGMODE = 1;
  21382. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  21383. Texture.BILINEAR_SAMPLINGMODE = 2;
  21384. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  21385. Texture.TRILINEAR_SAMPLINGMODE = 3;
  21386. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  21387. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  21388. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  21389. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  21390. Texture.NEAREST_LINEAR = 7;
  21391. Texture.NEAREST_NEAREST = 8;
  21392. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  21393. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  21394. Texture.LINEAR_LINEAR = 11;
  21395. Texture.LINEAR_NEAREST = 12;
  21396. Texture.EXPLICIT_MODE = 0;
  21397. Texture.SPHERICAL_MODE = 1;
  21398. Texture.PLANAR_MODE = 2;
  21399. Texture.CUBIC_MODE = 3;
  21400. Texture.PROJECTION_MODE = 4;
  21401. Texture.SKYBOX_MODE = 5;
  21402. Texture.INVCUBIC_MODE = 6;
  21403. Texture.EQUIRECTANGULAR_MODE = 7;
  21404. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  21405. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  21406. Texture.CLAMP_ADDRESSMODE = 0;
  21407. Texture.WRAP_ADDRESSMODE = 1;
  21408. Texture.MIRROR_ADDRESSMODE = 2;
  21409. __decorate([
  21410. BABYLON.serialize()
  21411. ], Texture.prototype, "url", void 0);
  21412. __decorate([
  21413. BABYLON.serialize()
  21414. ], Texture.prototype, "uOffset", void 0);
  21415. __decorate([
  21416. BABYLON.serialize()
  21417. ], Texture.prototype, "vOffset", void 0);
  21418. __decorate([
  21419. BABYLON.serialize()
  21420. ], Texture.prototype, "uScale", void 0);
  21421. __decorate([
  21422. BABYLON.serialize()
  21423. ], Texture.prototype, "vScale", void 0);
  21424. __decorate([
  21425. BABYLON.serialize()
  21426. ], Texture.prototype, "uAng", void 0);
  21427. __decorate([
  21428. BABYLON.serialize()
  21429. ], Texture.prototype, "vAng", void 0);
  21430. __decorate([
  21431. BABYLON.serialize()
  21432. ], Texture.prototype, "wAng", void 0);
  21433. __decorate([
  21434. BABYLON.serialize()
  21435. ], Texture.prototype, "isBlocking", null);
  21436. return Texture;
  21437. }(BABYLON.BaseTexture));
  21438. BABYLON.Texture = Texture;
  21439. })(BABYLON || (BABYLON = {}));
  21440. //# sourceMappingURL=babylon.texture.js.map
  21441. var BABYLON;
  21442. (function (BABYLON) {
  21443. var _InstancesBatch = (function () {
  21444. function _InstancesBatch() {
  21445. this.mustReturn = false;
  21446. this.visibleInstances = new Array();
  21447. this.renderSelf = new Array();
  21448. }
  21449. return _InstancesBatch;
  21450. }());
  21451. BABYLON._InstancesBatch = _InstancesBatch;
  21452. var Mesh = (function (_super) {
  21453. __extends(Mesh, _super);
  21454. /**
  21455. * @constructor
  21456. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  21457. * @param {Scene} scene The scene to add this mesh to.
  21458. * @param {Node} parent The parent of this mesh, if it has one
  21459. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  21460. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  21461. * When false, achieved by calling a clone(), also passing False.
  21462. * This will make creation of children, recursive.
  21463. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  21464. */
  21465. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  21466. if (parent === void 0) { parent = null; }
  21467. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  21468. var _this = _super.call(this, name, scene) || this;
  21469. // Events
  21470. /**
  21471. * An event triggered before rendering the mesh
  21472. * @type {BABYLON.Observable}
  21473. */
  21474. _this.onBeforeRenderObservable = new BABYLON.Observable();
  21475. /**
  21476. * An event triggered after rendering the mesh
  21477. * @type {BABYLON.Observable}
  21478. */
  21479. _this.onAfterRenderObservable = new BABYLON.Observable();
  21480. /**
  21481. * An event triggered before drawing the mesh
  21482. * @type {BABYLON.Observable}
  21483. */
  21484. _this.onBeforeDrawObservable = new BABYLON.Observable();
  21485. // Members
  21486. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21487. _this.instances = new Array();
  21488. _this._LODLevels = new Array();
  21489. _this._visibleInstances = {};
  21490. _this._renderIdForInstances = new Array();
  21491. _this._batchCache = new _InstancesBatch();
  21492. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  21493. // Use by builder only to know what orientation were the mesh build in.
  21494. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  21495. _this.overrideMaterialSideOrientation = null;
  21496. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  21497. // Will be used to save a source mesh reference, If any
  21498. _this._source = null;
  21499. if (source) {
  21500. // Source mesh
  21501. _this._source = source;
  21502. // Geometry
  21503. if (source._geometry) {
  21504. source._geometry.applyToMesh(_this);
  21505. }
  21506. // Deep copy
  21507. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  21508. // Parent
  21509. _this.parent = source.parent;
  21510. // Pivot
  21511. _this.setPivotMatrix(source.getPivotMatrix());
  21512. _this.id = name + "." + source.id;
  21513. // Material
  21514. _this.material = source.material;
  21515. var index;
  21516. if (!doNotCloneChildren) {
  21517. // Children
  21518. for (index = 0; index < scene.meshes.length; index++) {
  21519. var mesh = scene.meshes[index];
  21520. if (mesh.parent === source) {
  21521. // doNotCloneChildren is always going to be False
  21522. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  21523. }
  21524. }
  21525. }
  21526. // Physics clone
  21527. var physicsEngine = _this.getScene().getPhysicsEngine();
  21528. if (clonePhysicsImpostor && physicsEngine) {
  21529. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  21530. if (impostor) {
  21531. _this.physicsImpostor = impostor.clone(_this);
  21532. }
  21533. }
  21534. // Particles
  21535. for (index = 0; index < scene.particleSystems.length; index++) {
  21536. var system = scene.particleSystems[index];
  21537. if (system.emitter === source) {
  21538. system.clone(system.name, _this);
  21539. }
  21540. }
  21541. _this.computeWorldMatrix(true);
  21542. }
  21543. // Parent
  21544. if (parent !== null) {
  21545. _this.parent = parent;
  21546. }
  21547. return _this;
  21548. }
  21549. Object.defineProperty(Mesh, "FRONTSIDE", {
  21550. /**
  21551. * Mesh side orientation : usually the external or front surface
  21552. */
  21553. get: function () {
  21554. return Mesh._FRONTSIDE;
  21555. },
  21556. enumerable: true,
  21557. configurable: true
  21558. });
  21559. Object.defineProperty(Mesh, "BACKSIDE", {
  21560. /**
  21561. * Mesh side orientation : usually the internal or back surface
  21562. */
  21563. get: function () {
  21564. return Mesh._BACKSIDE;
  21565. },
  21566. enumerable: true,
  21567. configurable: true
  21568. });
  21569. Object.defineProperty(Mesh, "DOUBLESIDE", {
  21570. /**
  21571. * Mesh side orientation : both internal and external or front and back surfaces
  21572. */
  21573. get: function () {
  21574. return Mesh._DOUBLESIDE;
  21575. },
  21576. enumerable: true,
  21577. configurable: true
  21578. });
  21579. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  21580. /**
  21581. * Mesh side orientation : by default, `FRONTSIDE`
  21582. */
  21583. get: function () {
  21584. return Mesh._DEFAULTSIDE;
  21585. },
  21586. enumerable: true,
  21587. configurable: true
  21588. });
  21589. Object.defineProperty(Mesh, "NO_CAP", {
  21590. /**
  21591. * Mesh cap setting : no cap
  21592. */
  21593. get: function () {
  21594. return Mesh._NO_CAP;
  21595. },
  21596. enumerable: true,
  21597. configurable: true
  21598. });
  21599. Object.defineProperty(Mesh, "CAP_START", {
  21600. /**
  21601. * Mesh cap setting : one cap at the beginning of the mesh
  21602. */
  21603. get: function () {
  21604. return Mesh._CAP_START;
  21605. },
  21606. enumerable: true,
  21607. configurable: true
  21608. });
  21609. Object.defineProperty(Mesh, "CAP_END", {
  21610. /**
  21611. * Mesh cap setting : one cap at the end of the mesh
  21612. */
  21613. get: function () {
  21614. return Mesh._CAP_END;
  21615. },
  21616. enumerable: true,
  21617. configurable: true
  21618. });
  21619. Object.defineProperty(Mesh, "CAP_ALL", {
  21620. /**
  21621. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  21622. */
  21623. get: function () {
  21624. return Mesh._CAP_ALL;
  21625. },
  21626. enumerable: true,
  21627. configurable: true
  21628. });
  21629. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  21630. set: function (callback) {
  21631. if (this._onBeforeDrawObserver) {
  21632. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  21633. }
  21634. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  21635. },
  21636. enumerable: true,
  21637. configurable: true
  21638. });
  21639. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  21640. get: function () {
  21641. return this._morphTargetManager;
  21642. },
  21643. set: function (value) {
  21644. if (this._morphTargetManager === value) {
  21645. return;
  21646. }
  21647. this._morphTargetManager = value;
  21648. this._syncGeometryWithMorphTargetManager();
  21649. },
  21650. enumerable: true,
  21651. configurable: true
  21652. });
  21653. Object.defineProperty(Mesh.prototype, "source", {
  21654. get: function () {
  21655. return this._source;
  21656. },
  21657. enumerable: true,
  21658. configurable: true
  21659. });
  21660. // Methods
  21661. /**
  21662. * Returns the string "Mesh".
  21663. */
  21664. Mesh.prototype.getClassName = function () {
  21665. return "Mesh";
  21666. };
  21667. /**
  21668. * Returns a string.
  21669. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21670. */
  21671. Mesh.prototype.toString = function (fullDetails) {
  21672. var ret = _super.prototype.toString.call(this, fullDetails);
  21673. ret += ", n vertices: " + this.getTotalVertices();
  21674. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  21675. if (this.animations) {
  21676. for (var i = 0; i < this.animations.length; i++) {
  21677. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21678. }
  21679. }
  21680. if (fullDetails) {
  21681. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  21682. }
  21683. return ret;
  21684. };
  21685. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  21686. /**
  21687. * True if the mesh has some Levels Of Details (LOD).
  21688. * Returns a boolean.
  21689. */
  21690. get: function () {
  21691. return this._LODLevels.length > 0;
  21692. },
  21693. enumerable: true,
  21694. configurable: true
  21695. });
  21696. Mesh.prototype._sortLODLevels = function () {
  21697. this._LODLevels.sort(function (a, b) {
  21698. if (a.distance < b.distance) {
  21699. return 1;
  21700. }
  21701. if (a.distance > b.distance) {
  21702. return -1;
  21703. }
  21704. return 0;
  21705. });
  21706. };
  21707. /**
  21708. * Add a mesh as LOD level triggered at the given distance.
  21709. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21710. * @param {number} distance The distance from the center of the object to show this level
  21711. * @param {Mesh} mesh The mesh to be added as LOD level
  21712. * @return {Mesh} This mesh (for chaining)
  21713. */
  21714. Mesh.prototype.addLODLevel = function (distance, mesh) {
  21715. if (mesh && mesh._masterMesh) {
  21716. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  21717. return this;
  21718. }
  21719. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  21720. this._LODLevels.push(level);
  21721. if (mesh) {
  21722. mesh._masterMesh = this;
  21723. }
  21724. this._sortLODLevels();
  21725. return this;
  21726. };
  21727. /**
  21728. * Returns the LOD level mesh at the passed distance or null if not found.
  21729. * It is related to the method `addLODLevel(distance, mesh)`.
  21730. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21731. * Returns an object Mesh or `null`.
  21732. */
  21733. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  21734. for (var index = 0; index < this._LODLevels.length; index++) {
  21735. var level = this._LODLevels[index];
  21736. if (level.distance === distance) {
  21737. return level.mesh;
  21738. }
  21739. }
  21740. return null;
  21741. };
  21742. /**
  21743. * Remove a mesh from the LOD array
  21744. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21745. * @param {Mesh} mesh The mesh to be removed.
  21746. * @return {Mesh} This mesh (for chaining)
  21747. */
  21748. Mesh.prototype.removeLODLevel = function (mesh) {
  21749. for (var index = 0; index < this._LODLevels.length; index++) {
  21750. if (this._LODLevels[index].mesh === mesh) {
  21751. this._LODLevels.splice(index, 1);
  21752. if (mesh) {
  21753. mesh._masterMesh = null;
  21754. }
  21755. }
  21756. }
  21757. this._sortLODLevels();
  21758. return this;
  21759. };
  21760. /**
  21761. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  21762. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21763. */
  21764. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  21765. if (!this._LODLevels || this._LODLevels.length === 0) {
  21766. return this;
  21767. }
  21768. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  21769. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  21770. if (this.onLODLevelSelection) {
  21771. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  21772. }
  21773. return this;
  21774. }
  21775. for (var index = 0; index < this._LODLevels.length; index++) {
  21776. var level = this._LODLevels[index];
  21777. if (level.distance < distanceToCamera) {
  21778. if (level.mesh) {
  21779. level.mesh._preActivate();
  21780. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21781. }
  21782. if (this.onLODLevelSelection) {
  21783. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  21784. }
  21785. return level.mesh;
  21786. }
  21787. }
  21788. if (this.onLODLevelSelection) {
  21789. this.onLODLevelSelection(distanceToCamera, this, this);
  21790. }
  21791. return this;
  21792. };
  21793. Object.defineProperty(Mesh.prototype, "geometry", {
  21794. /**
  21795. * Returns the mesh internal Geometry object.
  21796. */
  21797. get: function () {
  21798. return this._geometry;
  21799. },
  21800. enumerable: true,
  21801. configurable: true
  21802. });
  21803. /**
  21804. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  21805. */
  21806. Mesh.prototype.getTotalVertices = function () {
  21807. if (!this._geometry) {
  21808. return 0;
  21809. }
  21810. return this._geometry.getTotalVertices();
  21811. };
  21812. /**
  21813. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  21814. * 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.
  21815. * You can force the copy with forceCopy === true
  21816. * Returns null if the mesh has no geometry or no vertex buffer.
  21817. * Possible `kind` values :
  21818. * - BABYLON.VertexBuffer.PositionKind
  21819. * - BABYLON.VertexBuffer.UVKind
  21820. * - BABYLON.VertexBuffer.UV2Kind
  21821. * - BABYLON.VertexBuffer.UV3Kind
  21822. * - BABYLON.VertexBuffer.UV4Kind
  21823. * - BABYLON.VertexBuffer.UV5Kind
  21824. * - BABYLON.VertexBuffer.UV6Kind
  21825. * - BABYLON.VertexBuffer.ColorKind
  21826. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21827. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21828. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21829. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21830. */
  21831. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  21832. if (!this._geometry) {
  21833. return null;
  21834. }
  21835. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  21836. };
  21837. /**
  21838. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  21839. * Returns `undefined` if the mesh has no geometry.
  21840. * Possible `kind` values :
  21841. * - BABYLON.VertexBuffer.PositionKind
  21842. * - BABYLON.VertexBuffer.UVKind
  21843. * - BABYLON.VertexBuffer.UV2Kind
  21844. * - BABYLON.VertexBuffer.UV3Kind
  21845. * - BABYLON.VertexBuffer.UV4Kind
  21846. * - BABYLON.VertexBuffer.UV5Kind
  21847. * - BABYLON.VertexBuffer.UV6Kind
  21848. * - BABYLON.VertexBuffer.ColorKind
  21849. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21850. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21851. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21852. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21853. */
  21854. Mesh.prototype.getVertexBuffer = function (kind) {
  21855. if (!this._geometry) {
  21856. return undefined;
  21857. }
  21858. return this._geometry.getVertexBuffer(kind);
  21859. };
  21860. /**
  21861. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  21862. * Possible `kind` values :
  21863. * - BABYLON.VertexBuffer.PositionKind
  21864. * - BABYLON.VertexBuffer.UVKind
  21865. * - BABYLON.VertexBuffer.UV2Kind
  21866. * - BABYLON.VertexBuffer.UV3Kind
  21867. * - BABYLON.VertexBuffer.UV4Kind
  21868. * - BABYLON.VertexBuffer.UV5Kind
  21869. * - BABYLON.VertexBuffer.UV6Kind
  21870. * - BABYLON.VertexBuffer.ColorKind
  21871. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21872. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21873. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21874. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21875. */
  21876. Mesh.prototype.isVerticesDataPresent = function (kind) {
  21877. if (!this._geometry) {
  21878. if (this._delayInfo) {
  21879. return this._delayInfo.indexOf(kind) !== -1;
  21880. }
  21881. return false;
  21882. }
  21883. return this._geometry.isVerticesDataPresent(kind);
  21884. };
  21885. /**
  21886. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  21887. * Possible `kind` values :
  21888. * - BABYLON.VertexBuffer.PositionKind
  21889. * - BABYLON.VertexBuffer.UVKind
  21890. * - BABYLON.VertexBuffer.UV2Kind
  21891. * - BABYLON.VertexBuffer.UV3Kind
  21892. * - BABYLON.VertexBuffer.UV4Kind
  21893. * - BABYLON.VertexBuffer.UV5Kind
  21894. * - BABYLON.VertexBuffer.UV6Kind
  21895. * - BABYLON.VertexBuffer.ColorKind
  21896. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21897. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21898. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21899. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21900. */
  21901. Mesh.prototype.getVerticesDataKinds = function () {
  21902. if (!this._geometry) {
  21903. var result = new Array();
  21904. if (this._delayInfo) {
  21905. this._delayInfo.forEach(function (kind, index, array) {
  21906. result.push(kind);
  21907. });
  21908. }
  21909. return result;
  21910. }
  21911. return this._geometry.getVerticesDataKinds();
  21912. };
  21913. /**
  21914. * Returns a positive integer : the total number of indices in this mesh geometry.
  21915. * Returns zero if the mesh has no geometry.
  21916. */
  21917. Mesh.prototype.getTotalIndices = function () {
  21918. if (!this._geometry) {
  21919. return 0;
  21920. }
  21921. return this._geometry.getTotalIndices();
  21922. };
  21923. /**
  21924. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  21925. * 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.
  21926. * Returns an empty array if the mesh has no geometry.
  21927. */
  21928. Mesh.prototype.getIndices = function (copyWhenShared) {
  21929. if (!this._geometry) {
  21930. return [];
  21931. }
  21932. return this._geometry.getIndices(copyWhenShared);
  21933. };
  21934. Object.defineProperty(Mesh.prototype, "isBlocked", {
  21935. get: function () {
  21936. return this._masterMesh !== null && this._masterMesh !== undefined;
  21937. },
  21938. enumerable: true,
  21939. configurable: true
  21940. });
  21941. /**
  21942. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  21943. */
  21944. Mesh.prototype.isReady = function () {
  21945. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21946. return false;
  21947. }
  21948. return _super.prototype.isReady.call(this);
  21949. };
  21950. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  21951. /**
  21952. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  21953. * This property is pertinent only for updatable parametric shapes.
  21954. */
  21955. get: function () {
  21956. return this._areNormalsFrozen;
  21957. },
  21958. enumerable: true,
  21959. configurable: true
  21960. });
  21961. /**
  21962. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21963. * It has no effect at all on other shapes.
  21964. * It prevents the mesh normals from being recomputed on next `positions` array update.
  21965. * Returns the Mesh.
  21966. */
  21967. Mesh.prototype.freezeNormals = function () {
  21968. this._areNormalsFrozen = true;
  21969. return this;
  21970. };
  21971. /**
  21972. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21973. * It has no effect at all on other shapes.
  21974. * It reactivates the mesh normals computation if it was previously frozen.
  21975. * Returns the Mesh.
  21976. */
  21977. Mesh.prototype.unfreezeNormals = function () {
  21978. this._areNormalsFrozen = false;
  21979. return this;
  21980. };
  21981. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  21982. /**
  21983. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  21984. */
  21985. set: function (count) {
  21986. this._overridenInstanceCount = count;
  21987. },
  21988. enumerable: true,
  21989. configurable: true
  21990. });
  21991. // Methods
  21992. Mesh.prototype._preActivate = function () {
  21993. var sceneRenderId = this.getScene().getRenderId();
  21994. if (this._preActivateId === sceneRenderId) {
  21995. return this;
  21996. }
  21997. this._preActivateId = sceneRenderId;
  21998. this._visibleInstances = null;
  21999. return this;
  22000. };
  22001. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  22002. if (this._visibleInstances) {
  22003. this._visibleInstances.intermediateDefaultRenderId = renderId;
  22004. }
  22005. return this;
  22006. };
  22007. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  22008. if (!this._visibleInstances) {
  22009. this._visibleInstances = {};
  22010. this._visibleInstances.defaultRenderId = renderId;
  22011. this._visibleInstances.selfDefaultRenderId = this._renderId;
  22012. }
  22013. if (!this._visibleInstances[renderId]) {
  22014. this._visibleInstances[renderId] = new Array();
  22015. }
  22016. this._visibleInstances[renderId].push(instance);
  22017. return this;
  22018. };
  22019. /**
  22020. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  22021. * This means the mesh underlying bounding box and sphere are recomputed.
  22022. * Returns the Mesh.
  22023. */
  22024. Mesh.prototype.refreshBoundingInfo = function () {
  22025. if (this._boundingInfo.isLocked) {
  22026. return;
  22027. }
  22028. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22029. if (data) {
  22030. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  22031. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22032. }
  22033. if (this.subMeshes) {
  22034. for (var index = 0; index < this.subMeshes.length; index++) {
  22035. this.subMeshes[index].refreshBoundingInfo();
  22036. }
  22037. }
  22038. this._updateBoundingInfo();
  22039. return this;
  22040. };
  22041. Mesh.prototype._createGlobalSubMesh = function (force) {
  22042. var totalVertices = this.getTotalVertices();
  22043. if (!totalVertices || !this.getIndices()) {
  22044. return null;
  22045. }
  22046. // Check if we need to recreate the submeshes
  22047. if (this.subMeshes && this.subMeshes.length > 0) {
  22048. var totalIndices = this.getIndices().length;
  22049. var needToRecreate = false;
  22050. if (force) {
  22051. needToRecreate = true;
  22052. }
  22053. else {
  22054. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  22055. var submesh = _a[_i];
  22056. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  22057. needToRecreate = true;
  22058. break;
  22059. }
  22060. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  22061. needToRecreate = true;
  22062. break;
  22063. }
  22064. }
  22065. }
  22066. if (!needToRecreate) {
  22067. return;
  22068. }
  22069. }
  22070. this.releaseSubMeshes();
  22071. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  22072. };
  22073. Mesh.prototype.subdivide = function (count) {
  22074. if (count < 1) {
  22075. return;
  22076. }
  22077. var totalIndices = this.getTotalIndices();
  22078. var subdivisionSize = (totalIndices / count) | 0;
  22079. var offset = 0;
  22080. // Ensure that subdivisionSize is a multiple of 3
  22081. while (subdivisionSize % 3 !== 0) {
  22082. subdivisionSize++;
  22083. }
  22084. this.releaseSubMeshes();
  22085. for (var index = 0; index < count; index++) {
  22086. if (offset >= totalIndices) {
  22087. break;
  22088. }
  22089. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  22090. offset += subdivisionSize;
  22091. }
  22092. this.synchronizeInstances();
  22093. };
  22094. /**
  22095. * Sets the vertex data of the mesh geometry for the requested `kind`.
  22096. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  22097. * The `data` are either a numeric array either a Float32Array.
  22098. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  22099. * 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).
  22100. * Note that a new underlying VertexBuffer object is created each call.
  22101. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  22102. *
  22103. * Possible `kind` values :
  22104. * - BABYLON.VertexBuffer.PositionKind
  22105. * - BABYLON.VertexBuffer.UVKind
  22106. * - BABYLON.VertexBuffer.UV2Kind
  22107. * - BABYLON.VertexBuffer.UV3Kind
  22108. * - BABYLON.VertexBuffer.UV4Kind
  22109. * - BABYLON.VertexBuffer.UV5Kind
  22110. * - BABYLON.VertexBuffer.UV6Kind
  22111. * - BABYLON.VertexBuffer.ColorKind
  22112. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22113. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22114. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22115. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22116. *
  22117. * Returns the Mesh.
  22118. */
  22119. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  22120. if (!this._geometry) {
  22121. var vertexData = new BABYLON.VertexData();
  22122. vertexData.set(data, kind);
  22123. var scene = this.getScene();
  22124. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  22125. }
  22126. else {
  22127. this._geometry.setVerticesData(kind, data, updatable, stride);
  22128. }
  22129. return this;
  22130. };
  22131. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  22132. if (updatable === void 0) { updatable = true; }
  22133. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  22134. return;
  22135. }
  22136. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  22137. };
  22138. /**
  22139. * Sets the mesh VertexBuffer.
  22140. * Returns the Mesh.
  22141. */
  22142. Mesh.prototype.setVerticesBuffer = function (buffer) {
  22143. if (!this._geometry) {
  22144. var scene = this.getScene();
  22145. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  22146. }
  22147. this._geometry.setVerticesBuffer(buffer);
  22148. return this;
  22149. };
  22150. /**
  22151. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  22152. * If the mesh has no geometry, it is simply returned as it is.
  22153. * The `data` are either a numeric array either a Float32Array.
  22154. * No new underlying VertexBuffer object is created.
  22155. * 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.
  22156. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  22157. *
  22158. * Possible `kind` values :
  22159. * - BABYLON.VertexBuffer.PositionKind
  22160. * - BABYLON.VertexBuffer.UVKind
  22161. * - BABYLON.VertexBuffer.UV2Kind
  22162. * - BABYLON.VertexBuffer.UV3Kind
  22163. * - BABYLON.VertexBuffer.UV4Kind
  22164. * - BABYLON.VertexBuffer.UV5Kind
  22165. * - BABYLON.VertexBuffer.UV6Kind
  22166. * - BABYLON.VertexBuffer.ColorKind
  22167. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22168. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22169. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22170. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22171. *
  22172. * Returns the Mesh.
  22173. */
  22174. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  22175. if (!this._geometry) {
  22176. return;
  22177. }
  22178. if (!makeItUnique) {
  22179. this._geometry.updateVerticesData(kind, data, updateExtends);
  22180. }
  22181. else {
  22182. this.makeGeometryUnique();
  22183. this.updateVerticesData(kind, data, updateExtends, false);
  22184. }
  22185. return this;
  22186. };
  22187. /**
  22188. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  22189. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  22190. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  22191. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  22192. * Returns the Mesh.
  22193. */
  22194. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  22195. if (computeNormals === void 0) { computeNormals = true; }
  22196. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22197. positionFunction(positions);
  22198. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  22199. if (computeNormals) {
  22200. var indices = this.getIndices();
  22201. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22202. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  22203. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  22204. }
  22205. return this;
  22206. };
  22207. /**
  22208. * Creates a un-shared specific occurence of the geometry for the mesh.
  22209. * Returns the Mesh.
  22210. */
  22211. Mesh.prototype.makeGeometryUnique = function () {
  22212. if (!this._geometry) {
  22213. return;
  22214. }
  22215. var oldGeometry = this._geometry;
  22216. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  22217. oldGeometry.releaseForMesh(this, true);
  22218. geometry.applyToMesh(this);
  22219. return this;
  22220. };
  22221. /**
  22222. * Sets the mesh indices.
  22223. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  22224. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  22225. * This method creates a new index buffer each call.
  22226. * Returns the Mesh.
  22227. */
  22228. Mesh.prototype.setIndices = function (indices, totalVertices) {
  22229. if (!this._geometry) {
  22230. var vertexData = new BABYLON.VertexData();
  22231. vertexData.indices = indices;
  22232. var scene = this.getScene();
  22233. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  22234. }
  22235. else {
  22236. this._geometry.setIndices(indices, totalVertices);
  22237. }
  22238. return this;
  22239. };
  22240. /**
  22241. * Invert the geometry to move from a right handed system to a left handed one.
  22242. * Returns the Mesh.
  22243. */
  22244. Mesh.prototype.toLeftHanded = function () {
  22245. if (!this._geometry) {
  22246. return;
  22247. }
  22248. this._geometry.toLeftHanded();
  22249. return this;
  22250. };
  22251. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  22252. var engine = this.getScene().getEngine();
  22253. // Wireframe
  22254. var indexToBind;
  22255. if (this._unIndexed) {
  22256. indexToBind = null;
  22257. }
  22258. else {
  22259. switch (fillMode) {
  22260. case BABYLON.Material.PointFillMode:
  22261. indexToBind = null;
  22262. break;
  22263. case BABYLON.Material.WireFrameFillMode:
  22264. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  22265. break;
  22266. default:
  22267. case BABYLON.Material.TriangleFillMode:
  22268. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  22269. break;
  22270. }
  22271. }
  22272. // VBOs
  22273. this._geometry._bind(effect, indexToBind);
  22274. return this;
  22275. };
  22276. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  22277. if (alternate === void 0) { alternate = false; }
  22278. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  22279. return this;
  22280. }
  22281. this.onBeforeDrawObservable.notifyObservers(this);
  22282. var scene = this.getScene();
  22283. var engine = scene.getEngine();
  22284. // Draw order
  22285. switch (fillMode) {
  22286. case BABYLON.Material.PointFillMode:
  22287. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22288. break;
  22289. case BABYLON.Material.WireFrameFillMode:
  22290. if (this._unIndexed) {
  22291. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22292. }
  22293. else {
  22294. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  22295. }
  22296. break;
  22297. default:
  22298. if (this._unIndexed) {
  22299. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  22300. }
  22301. else {
  22302. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  22303. }
  22304. }
  22305. if (scene._isAlternateRenderingEnabled && !alternate) {
  22306. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  22307. scene._switchToAlternateCameraConfiguration(true);
  22308. this._effectiveMaterial.bindView(effect);
  22309. this._effectiveMaterial.bindViewProjection(effect);
  22310. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  22311. this._draw(subMesh, fillMode, instancesCount, true);
  22312. engine.setViewport(scene.activeCamera.viewport);
  22313. scene._switchToAlternateCameraConfiguration(false);
  22314. this._effectiveMaterial.bindView(effect);
  22315. this._effectiveMaterial.bindViewProjection(effect);
  22316. }
  22317. return this;
  22318. };
  22319. /**
  22320. * Registers for this mesh a javascript function called just before the rendering process.
  22321. * This function is passed the current mesh.
  22322. * Return the Mesh.
  22323. */
  22324. Mesh.prototype.registerBeforeRender = function (func) {
  22325. this.onBeforeRenderObservable.add(func);
  22326. return this;
  22327. };
  22328. /**
  22329. * Disposes a previously registered javascript function called before the rendering.
  22330. * This function is passed the current mesh.
  22331. * Returns the Mesh.
  22332. */
  22333. Mesh.prototype.unregisterBeforeRender = function (func) {
  22334. this.onBeforeRenderObservable.removeCallback(func);
  22335. return this;
  22336. };
  22337. /**
  22338. * Registers for this mesh a javascript function called just after the rendering is complete.
  22339. * This function is passed the current mesh.
  22340. * Returns the Mesh.
  22341. */
  22342. Mesh.prototype.registerAfterRender = function (func) {
  22343. this.onAfterRenderObservable.add(func);
  22344. return this;
  22345. };
  22346. /**
  22347. * Disposes a previously registered javascript function called after the rendering.
  22348. * This function is passed the current mesh.
  22349. * Return the Mesh.
  22350. */
  22351. Mesh.prototype.unregisterAfterRender = function (func) {
  22352. this.onAfterRenderObservable.removeCallback(func);
  22353. return this;
  22354. };
  22355. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  22356. var scene = this.getScene();
  22357. this._batchCache.mustReturn = false;
  22358. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  22359. this._batchCache.visibleInstances[subMeshId] = null;
  22360. if (this._visibleInstances) {
  22361. var currentRenderId = scene.getRenderId();
  22362. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  22363. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  22364. var selfRenderId = this._renderId;
  22365. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  22366. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  22367. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  22368. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  22369. }
  22370. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  22371. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  22372. this._batchCache.mustReturn = true;
  22373. return this._batchCache;
  22374. }
  22375. if (currentRenderId !== selfRenderId) {
  22376. this._batchCache.renderSelf[subMeshId] = false;
  22377. }
  22378. }
  22379. this._renderIdForInstances[subMeshId] = currentRenderId;
  22380. }
  22381. return this._batchCache;
  22382. };
  22383. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  22384. var visibleInstances = batch.visibleInstances[subMesh._id];
  22385. var matricesCount = visibleInstances.length + 1;
  22386. var bufferSize = matricesCount * 16 * 4;
  22387. var currentInstancesBufferSize = this._instancesBufferSize;
  22388. var instancesBuffer = this._instancesBuffer;
  22389. while (this._instancesBufferSize < bufferSize) {
  22390. this._instancesBufferSize *= 2;
  22391. }
  22392. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  22393. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  22394. }
  22395. var offset = 0;
  22396. var instancesCount = 0;
  22397. var world = this.getWorldMatrix();
  22398. if (batch.renderSelf[subMesh._id]) {
  22399. world.copyToArray(this._instancesData, offset);
  22400. offset += 16;
  22401. instancesCount++;
  22402. }
  22403. if (visibleInstances) {
  22404. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  22405. var instance = visibleInstances[instanceIndex];
  22406. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  22407. offset += 16;
  22408. instancesCount++;
  22409. }
  22410. }
  22411. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  22412. if (instancesBuffer) {
  22413. instancesBuffer.dispose();
  22414. }
  22415. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  22416. this._instancesBuffer = instancesBuffer;
  22417. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  22418. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  22419. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  22420. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  22421. }
  22422. else {
  22423. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  22424. }
  22425. this._bind(subMesh, effect, fillMode);
  22426. this._draw(subMesh, fillMode, instancesCount);
  22427. engine.unbindInstanceAttributes();
  22428. return this;
  22429. };
  22430. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  22431. var scene = this.getScene();
  22432. var engine = scene.getEngine();
  22433. if (hardwareInstancedRendering) {
  22434. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  22435. }
  22436. else {
  22437. if (batch.renderSelf[subMesh._id]) {
  22438. // Draw
  22439. if (onBeforeDraw) {
  22440. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  22441. }
  22442. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  22443. }
  22444. if (batch.visibleInstances[subMesh._id]) {
  22445. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  22446. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  22447. // World
  22448. var world = instance.getWorldMatrix();
  22449. if (onBeforeDraw) {
  22450. onBeforeDraw(true, world, effectiveMaterial);
  22451. }
  22452. // Draw
  22453. this._draw(subMesh, fillMode);
  22454. }
  22455. }
  22456. }
  22457. return this;
  22458. };
  22459. /**
  22460. * Triggers the draw call for the mesh.
  22461. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  22462. * Returns the Mesh.
  22463. */
  22464. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  22465. this.checkOcclusionQuery();
  22466. if (this._isOccluded) {
  22467. return;
  22468. }
  22469. var scene = this.getScene();
  22470. // Managing instances
  22471. var batch = this._getInstancesRenderList(subMesh._id);
  22472. if (batch.mustReturn) {
  22473. return this;
  22474. }
  22475. // Checking geometry state
  22476. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  22477. return this;
  22478. }
  22479. var callbackIndex;
  22480. this.onBeforeRenderObservable.notifyObservers(this);
  22481. var engine = scene.getEngine();
  22482. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  22483. // Material
  22484. this._effectiveMaterial = subMesh.getMaterial();
  22485. if (!this._effectiveMaterial) {
  22486. return this;
  22487. }
  22488. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  22489. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  22490. return this;
  22491. }
  22492. }
  22493. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  22494. return this;
  22495. }
  22496. // Alpha mode
  22497. if (enableAlphaMode) {
  22498. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  22499. }
  22500. // Outline - step 1
  22501. var savedDepthWrite = engine.getDepthWrite();
  22502. if (this.renderOutline) {
  22503. engine.setDepthWrite(false);
  22504. scene.getOutlineRenderer().render(subMesh, batch);
  22505. engine.setDepthWrite(savedDepthWrite);
  22506. }
  22507. var effect;
  22508. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  22509. effect = subMesh.effect;
  22510. }
  22511. else {
  22512. effect = this._effectiveMaterial.getEffect();
  22513. }
  22514. var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
  22515. if (this._effectiveMaterial.forceDepthWrite) {
  22516. engine.setDepthWrite(true);
  22517. }
  22518. // Bind
  22519. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  22520. if (!hardwareInstancedRendering) {
  22521. this._bind(subMesh, effect, fillMode);
  22522. }
  22523. var world = this.getWorldMatrix();
  22524. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  22525. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  22526. }
  22527. else {
  22528. this._effectiveMaterial.bind(world, this);
  22529. }
  22530. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  22531. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  22532. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  22533. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  22534. }
  22535. // Draw
  22536. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  22537. // Unbind
  22538. this._effectiveMaterial.unbind();
  22539. // Outline - step 2
  22540. if (this.renderOutline && savedDepthWrite) {
  22541. engine.setDepthWrite(true);
  22542. engine.setColorWrite(false);
  22543. scene.getOutlineRenderer().render(subMesh, batch);
  22544. engine.setColorWrite(true);
  22545. }
  22546. // Overlay
  22547. if (this.renderOverlay) {
  22548. var currentMode = engine.getAlphaMode();
  22549. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  22550. scene.getOutlineRenderer().render(subMesh, batch, true);
  22551. engine.setAlphaMode(currentMode);
  22552. }
  22553. this.onAfterRenderObservable.notifyObservers(this);
  22554. return this;
  22555. };
  22556. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  22557. if (isInstance) {
  22558. effectiveMaterial.bindOnlyWorldMatrix(world);
  22559. }
  22560. return this;
  22561. };
  22562. /**
  22563. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  22564. */
  22565. Mesh.prototype.getEmittedParticleSystems = function () {
  22566. var results = new Array();
  22567. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22568. var particleSystem = this.getScene().particleSystems[index];
  22569. if (particleSystem.emitter === this) {
  22570. results.push(particleSystem);
  22571. }
  22572. }
  22573. return results;
  22574. };
  22575. /**
  22576. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  22577. */
  22578. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  22579. var results = new Array();
  22580. var descendants = this.getDescendants();
  22581. descendants.push(this);
  22582. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  22583. var particleSystem = this.getScene().particleSystems[index];
  22584. var emitter = particleSystem.emitter;
  22585. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  22586. results.push(particleSystem);
  22587. }
  22588. }
  22589. return results;
  22590. };
  22591. Mesh.prototype._checkDelayState = function () {
  22592. var scene = this.getScene();
  22593. if (this._geometry) {
  22594. this._geometry.load(scene);
  22595. }
  22596. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22597. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  22598. this._queueLoad(this, scene);
  22599. }
  22600. return this;
  22601. };
  22602. Mesh.prototype._queueLoad = function (mesh, scene) {
  22603. var _this = this;
  22604. scene._addPendingData(mesh);
  22605. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  22606. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  22607. if (data instanceof ArrayBuffer) {
  22608. _this._delayLoadingFunction(data, _this);
  22609. }
  22610. else {
  22611. _this._delayLoadingFunction(JSON.parse(data), _this);
  22612. }
  22613. _this.instances.forEach(function (instance) {
  22614. instance._syncSubMeshes();
  22615. });
  22616. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22617. scene._removePendingData(_this);
  22618. }, function () { }, scene.database, getBinaryData);
  22619. return this;
  22620. };
  22621. /**
  22622. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  22623. */
  22624. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  22625. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22626. return false;
  22627. }
  22628. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  22629. return false;
  22630. }
  22631. this._checkDelayState();
  22632. return true;
  22633. };
  22634. /**
  22635. * Sets the mesh material by the material or multiMaterial `id` property.
  22636. * The material `id` is a string identifying the material or the multiMaterial.
  22637. * This method returns the Mesh.
  22638. */
  22639. Mesh.prototype.setMaterialByID = function (id) {
  22640. var materials = this.getScene().materials;
  22641. var index;
  22642. for (index = materials.length - 1; index > -1; index--) {
  22643. if (materials[index].id === id) {
  22644. this.material = materials[index];
  22645. return this;
  22646. }
  22647. }
  22648. // Multi
  22649. var multiMaterials = this.getScene().multiMaterials;
  22650. for (index = multiMaterials.length - 1; index > -1; index--) {
  22651. if (multiMaterials[index].id === id) {
  22652. this.material = multiMaterials[index];
  22653. return this;
  22654. }
  22655. }
  22656. return this;
  22657. };
  22658. /**
  22659. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  22660. */
  22661. Mesh.prototype.getAnimatables = function () {
  22662. var results = new Array();
  22663. if (this.material) {
  22664. results.push(this.material);
  22665. }
  22666. if (this.skeleton) {
  22667. results.push(this.skeleton);
  22668. }
  22669. return results;
  22670. };
  22671. /**
  22672. * Modifies the mesh geometry according to the passed transformation matrix.
  22673. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  22674. * The mesh normals are modified accordingly the same transformation.
  22675. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22676. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22677. * Returns the Mesh.
  22678. */
  22679. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  22680. // Position
  22681. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22682. return this;
  22683. }
  22684. var submeshes = this.subMeshes.splice(0);
  22685. this._resetPointsArrayCache();
  22686. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22687. var temp = new Array();
  22688. var index;
  22689. for (index = 0; index < data.length; index += 3) {
  22690. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  22691. }
  22692. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  22693. // Normals
  22694. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22695. return this;
  22696. }
  22697. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22698. temp = [];
  22699. for (index = 0; index < data.length; index += 3) {
  22700. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  22701. }
  22702. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  22703. // flip faces?
  22704. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  22705. this.flipFaces();
  22706. }
  22707. // Restore submeshes
  22708. this.releaseSubMeshes();
  22709. this.subMeshes = submeshes;
  22710. return this;
  22711. };
  22712. /**
  22713. * Modifies the mesh geometry according to its own current World Matrix.
  22714. * The mesh World Matrix is then reset.
  22715. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  22716. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22717. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22718. * Returns the Mesh.
  22719. */
  22720. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  22721. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  22722. this.scaling.copyFromFloats(1, 1, 1);
  22723. this.position.copyFromFloats(0, 0, 0);
  22724. this.rotation.copyFromFloats(0, 0, 0);
  22725. //only if quaternion is already set
  22726. if (this.rotationQuaternion) {
  22727. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  22728. }
  22729. this._worldMatrix = BABYLON.Matrix.Identity();
  22730. return this;
  22731. };
  22732. Object.defineProperty(Mesh.prototype, "_positions", {
  22733. // Cache
  22734. get: function () {
  22735. if (this._geometry) {
  22736. return this._geometry._positions;
  22737. }
  22738. return null;
  22739. },
  22740. enumerable: true,
  22741. configurable: true
  22742. });
  22743. Mesh.prototype._resetPointsArrayCache = function () {
  22744. if (this._geometry) {
  22745. this._geometry._resetPointsArrayCache();
  22746. }
  22747. return this;
  22748. };
  22749. Mesh.prototype._generatePointsArray = function () {
  22750. if (this._geometry) {
  22751. return this._geometry._generatePointsArray();
  22752. }
  22753. return false;
  22754. };
  22755. /**
  22756. * Returns a new Mesh object generated from the current mesh properties.
  22757. * This method must not get confused with createInstance().
  22758. * The parameter `name` is a string, the name given to the new mesh.
  22759. * The optional parameter `newParent` can be any Node object (default `null`).
  22760. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  22761. * 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.
  22762. */
  22763. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  22764. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22765. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  22766. };
  22767. /**
  22768. * Disposes the mesh.
  22769. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  22770. */
  22771. Mesh.prototype.dispose = function (doNotRecurse) {
  22772. var _this = this;
  22773. this.morphTargetManager = undefined;
  22774. if (this._geometry) {
  22775. this._geometry.releaseForMesh(this, true);
  22776. }
  22777. // Sources
  22778. var meshes = this.getScene().meshes;
  22779. meshes.forEach(function (mesh) {
  22780. if (mesh._source && mesh._source === _this) {
  22781. mesh._source = null;
  22782. }
  22783. });
  22784. this._source = null;
  22785. // Instances
  22786. if (this._instancesBuffer) {
  22787. this._instancesBuffer.dispose();
  22788. this._instancesBuffer = null;
  22789. }
  22790. while (this.instances.length) {
  22791. this.instances[0].dispose();
  22792. }
  22793. // Highlight layers.
  22794. var highlightLayers = this.getScene().highlightLayers;
  22795. for (var i = 0; i < highlightLayers.length; i++) {
  22796. var highlightLayer = highlightLayers[i];
  22797. if (highlightLayer) {
  22798. highlightLayer.removeMesh(this);
  22799. highlightLayer.removeExcludedMesh(this);
  22800. }
  22801. }
  22802. _super.prototype.dispose.call(this, doNotRecurse);
  22803. };
  22804. /**
  22805. * Modifies the mesh geometry according to a displacement map.
  22806. * 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.
  22807. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22808. * This method returns nothing.
  22809. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  22810. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22811. * 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.
  22812. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22813. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22814. *
  22815. * Returns the Mesh.
  22816. */
  22817. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  22818. var _this = this;
  22819. var scene = this.getScene();
  22820. var onload = function (img) {
  22821. // Getting height map data
  22822. var canvas = document.createElement("canvas");
  22823. var context = canvas.getContext("2d");
  22824. var heightMapWidth = img.width;
  22825. var heightMapHeight = img.height;
  22826. canvas.width = heightMapWidth;
  22827. canvas.height = heightMapHeight;
  22828. context.drawImage(img, 0, 0);
  22829. // Create VertexData from map data
  22830. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22831. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  22832. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  22833. //execute success callback, if set
  22834. if (onSuccess) {
  22835. onSuccess(_this);
  22836. }
  22837. };
  22838. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22839. return this;
  22840. };
  22841. /**
  22842. * Modifies the mesh geometry according to a displacementMap buffer.
  22843. * 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.
  22844. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22845. * This method returns nothing.
  22846. * 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.
  22847. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  22848. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22849. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22850. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22851. *
  22852. * Returns the Mesh.
  22853. */
  22854. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  22855. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  22856. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  22857. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22858. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  22859. return this;
  22860. }
  22861. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22862. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22863. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22864. var position = BABYLON.Vector3.Zero();
  22865. var normal = BABYLON.Vector3.Zero();
  22866. var uv = BABYLON.Vector2.Zero();
  22867. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  22868. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  22869. for (var index = 0; index < positions.length; index += 3) {
  22870. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  22871. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  22872. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  22873. // Compute height
  22874. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  22875. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  22876. var pos = (u + v * heightMapWidth) * 4;
  22877. var r = buffer[pos] / 255.0;
  22878. var g = buffer[pos + 1] / 255.0;
  22879. var b = buffer[pos + 2] / 255.0;
  22880. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22881. normal.normalize();
  22882. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  22883. position = position.add(normal);
  22884. position.toArray(positions, index);
  22885. }
  22886. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  22887. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  22888. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  22889. return this;
  22890. };
  22891. /**
  22892. * Modify the mesh to get a flat shading rendering.
  22893. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  22894. * This method returns the Mesh.
  22895. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  22896. */
  22897. Mesh.prototype.convertToFlatShadedMesh = function () {
  22898. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  22899. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22900. var kinds = this.getVerticesDataKinds();
  22901. var vbs = {};
  22902. var data = {};
  22903. var newdata = {};
  22904. var updatableNormals = false;
  22905. var kindIndex;
  22906. var kind;
  22907. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22908. kind = kinds[kindIndex];
  22909. var vertexBuffer = this.getVertexBuffer(kind);
  22910. if (kind === BABYLON.VertexBuffer.NormalKind) {
  22911. updatableNormals = vertexBuffer.isUpdatable();
  22912. kinds.splice(kindIndex, 1);
  22913. kindIndex--;
  22914. continue;
  22915. }
  22916. vbs[kind] = vertexBuffer;
  22917. data[kind] = vbs[kind].getData();
  22918. newdata[kind] = [];
  22919. }
  22920. // Save previous submeshes
  22921. var previousSubmeshes = this.subMeshes.slice(0);
  22922. var indices = this.getIndices();
  22923. var totalIndices = this.getTotalIndices();
  22924. // Generating unique vertices per face
  22925. var index;
  22926. for (index = 0; index < totalIndices; index++) {
  22927. var vertexIndex = indices[index];
  22928. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22929. kind = kinds[kindIndex];
  22930. var stride = vbs[kind].getStrideSize();
  22931. for (var offset = 0; offset < stride; offset++) {
  22932. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22933. }
  22934. }
  22935. }
  22936. // Updating faces & normal
  22937. var normals = [];
  22938. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  22939. for (index = 0; index < totalIndices; index += 3) {
  22940. indices[index] = index;
  22941. indices[index + 1] = index + 1;
  22942. indices[index + 2] = index + 2;
  22943. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  22944. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  22945. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  22946. var p1p2 = p1.subtract(p2);
  22947. var p3p2 = p3.subtract(p2);
  22948. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22949. // Store same normals for every vertex
  22950. for (var localIndex = 0; localIndex < 3; localIndex++) {
  22951. normals.push(normal.x);
  22952. normals.push(normal.y);
  22953. normals.push(normal.z);
  22954. }
  22955. }
  22956. this.setIndices(indices);
  22957. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  22958. // Updating vertex buffers
  22959. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22960. kind = kinds[kindIndex];
  22961. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22962. }
  22963. // Updating submeshes
  22964. this.releaseSubMeshes();
  22965. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22966. var previousOne = previousSubmeshes[submeshIndex];
  22967. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22968. }
  22969. this.synchronizeInstances();
  22970. return this;
  22971. };
  22972. /**
  22973. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  22974. * In other words, more vertices, no more indices and a single bigger VBO.
  22975. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  22976. * Returns the Mesh.
  22977. */
  22978. Mesh.prototype.convertToUnIndexedMesh = function () {
  22979. /// <summary>Remove indices by unfolding faces into buffers</summary>
  22980. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22981. var kinds = this.getVerticesDataKinds();
  22982. var vbs = {};
  22983. var data = {};
  22984. var newdata = {};
  22985. var updatableNormals = false;
  22986. var kindIndex;
  22987. var kind;
  22988. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22989. kind = kinds[kindIndex];
  22990. var vertexBuffer = this.getVertexBuffer(kind);
  22991. vbs[kind] = vertexBuffer;
  22992. data[kind] = vbs[kind].getData();
  22993. newdata[kind] = [];
  22994. }
  22995. // Save previous submeshes
  22996. var previousSubmeshes = this.subMeshes.slice(0);
  22997. var indices = this.getIndices();
  22998. var totalIndices = this.getTotalIndices();
  22999. // Generating unique vertices per face
  23000. var index;
  23001. for (index = 0; index < totalIndices; index++) {
  23002. var vertexIndex = indices[index];
  23003. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23004. kind = kinds[kindIndex];
  23005. var stride = vbs[kind].getStrideSize();
  23006. for (var offset = 0; offset < stride; offset++) {
  23007. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23008. }
  23009. }
  23010. }
  23011. // Updating indices
  23012. for (index = 0; index < totalIndices; index += 3) {
  23013. indices[index] = index;
  23014. indices[index + 1] = index + 1;
  23015. indices[index + 2] = index + 2;
  23016. }
  23017. this.setIndices(indices);
  23018. // Updating vertex buffers
  23019. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23020. kind = kinds[kindIndex];
  23021. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23022. }
  23023. // Updating submeshes
  23024. this.releaseSubMeshes();
  23025. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23026. var previousOne = previousSubmeshes[submeshIndex];
  23027. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  23028. }
  23029. this._unIndexed = true;
  23030. this.synchronizeInstances();
  23031. return this;
  23032. };
  23033. /**
  23034. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  23035. * This method returns the Mesh.
  23036. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  23037. */
  23038. Mesh.prototype.flipFaces = function (flipNormals) {
  23039. if (flipNormals === void 0) { flipNormals = false; }
  23040. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  23041. var i;
  23042. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23043. for (i = 0; i < vertex_data.normals.length; i++) {
  23044. vertex_data.normals[i] *= -1;
  23045. }
  23046. }
  23047. var temp;
  23048. for (i = 0; i < vertex_data.indices.length; i += 3) {
  23049. // reassign indices
  23050. temp = vertex_data.indices[i + 1];
  23051. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  23052. vertex_data.indices[i + 2] = temp;
  23053. }
  23054. vertex_data.applyToMesh(this);
  23055. return this;
  23056. };
  23057. // Instances
  23058. /**
  23059. * Creates a new InstancedMesh object from the mesh model.
  23060. * An instance shares the same properties and the same material than its model.
  23061. * Only these properties of each instance can then be set individually :
  23062. * - position
  23063. * - rotation
  23064. * - rotationQuaternion
  23065. * - setPivotMatrix
  23066. * - scaling
  23067. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  23068. * Warning : this method is not supported for Line mesh and LineSystem
  23069. */
  23070. Mesh.prototype.createInstance = function (name) {
  23071. return new BABYLON.InstancedMesh(name, this);
  23072. };
  23073. /**
  23074. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  23075. * After this call, all the mesh instances have the same submeshes than the current mesh.
  23076. * This method returns the Mesh.
  23077. */
  23078. Mesh.prototype.synchronizeInstances = function () {
  23079. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  23080. var instance = this.instances[instanceIndex];
  23081. instance._syncSubMeshes();
  23082. }
  23083. return this;
  23084. };
  23085. /**
  23086. * Simplify the mesh according to the given array of settings.
  23087. * Function will return immediately and will simplify async. It returns the Mesh.
  23088. * @param settings a collection of simplification settings.
  23089. * @param parallelProcessing should all levels calculate parallel or one after the other.
  23090. * @param type the type of simplification to run.
  23091. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  23092. */
  23093. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  23094. if (parallelProcessing === void 0) { parallelProcessing = true; }
  23095. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  23096. this.getScene().simplificationQueue.addTask({
  23097. settings: settings,
  23098. parallelProcessing: parallelProcessing,
  23099. mesh: this,
  23100. simplificationType: simplificationType,
  23101. successCallback: successCallback
  23102. });
  23103. return this;
  23104. };
  23105. /**
  23106. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  23107. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  23108. * This should be used together with the simplification to avoid disappearing triangles.
  23109. * Returns the Mesh.
  23110. * @param successCallback an optional success callback to be called after the optimization finished.
  23111. */
  23112. Mesh.prototype.optimizeIndices = function (successCallback) {
  23113. var _this = this;
  23114. var indices = this.getIndices();
  23115. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23116. var vectorPositions = new Array();
  23117. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  23118. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  23119. }
  23120. var dupes = new Array();
  23121. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  23122. var realPos = vectorPositions.length - 1 - iteration;
  23123. var testedPosition = vectorPositions[realPos];
  23124. for (var j = 0; j < realPos; ++j) {
  23125. var againstPosition = vectorPositions[j];
  23126. if (testedPosition.equals(againstPosition)) {
  23127. dupes[realPos] = j;
  23128. break;
  23129. }
  23130. }
  23131. }, function () {
  23132. for (var i = 0; i < indices.length; ++i) {
  23133. indices[i] = dupes[indices[i]] || indices[i];
  23134. }
  23135. //indices are now reordered
  23136. var originalSubMeshes = _this.subMeshes.slice(0);
  23137. _this.setIndices(indices);
  23138. _this.subMeshes = originalSubMeshes;
  23139. if (successCallback) {
  23140. successCallback(_this);
  23141. }
  23142. });
  23143. return this;
  23144. };
  23145. Mesh.prototype.serialize = function (serializationObject) {
  23146. serializationObject.name = this.name;
  23147. serializationObject.id = this.id;
  23148. serializationObject.type = this.getClassName();
  23149. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  23150. serializationObject.tags = BABYLON.Tags.GetTags(this);
  23151. }
  23152. serializationObject.position = this.position.asArray();
  23153. if (this.rotationQuaternion) {
  23154. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  23155. }
  23156. else if (this.rotation) {
  23157. serializationObject.rotation = this.rotation.asArray();
  23158. }
  23159. serializationObject.scaling = this.scaling.asArray();
  23160. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  23161. serializationObject.isEnabled = this.isEnabled();
  23162. serializationObject.isVisible = this.isVisible;
  23163. serializationObject.infiniteDistance = this.infiniteDistance;
  23164. serializationObject.pickable = this.isPickable;
  23165. serializationObject.receiveShadows = this.receiveShadows;
  23166. serializationObject.billboardMode = this.billboardMode;
  23167. serializationObject.visibility = this.visibility;
  23168. serializationObject.checkCollisions = this.checkCollisions;
  23169. serializationObject.isBlocker = this.isBlocker;
  23170. // Parent
  23171. if (this.parent) {
  23172. serializationObject.parentId = this.parent.id;
  23173. }
  23174. // Geometry
  23175. var geometry = this._geometry;
  23176. if (geometry) {
  23177. var geometryId = geometry.id;
  23178. serializationObject.geometryId = geometryId;
  23179. // SubMeshes
  23180. serializationObject.subMeshes = [];
  23181. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  23182. var subMesh = this.subMeshes[subIndex];
  23183. serializationObject.subMeshes.push({
  23184. materialIndex: subMesh.materialIndex,
  23185. verticesStart: subMesh.verticesStart,
  23186. verticesCount: subMesh.verticesCount,
  23187. indexStart: subMesh.indexStart,
  23188. indexCount: subMesh.indexCount
  23189. });
  23190. }
  23191. }
  23192. // Material
  23193. if (this.material) {
  23194. serializationObject.materialId = this.material.id;
  23195. }
  23196. else {
  23197. this.material = null;
  23198. }
  23199. // Morph targets
  23200. if (this.morphTargetManager) {
  23201. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  23202. }
  23203. // Skeleton
  23204. if (this.skeleton) {
  23205. serializationObject.skeletonId = this.skeleton.id;
  23206. }
  23207. // Physics
  23208. //TODO implement correct serialization for physics impostors.
  23209. if (this.getPhysicsImpostor()) {
  23210. var impostor = this.getPhysicsImpostor();
  23211. serializationObject.physicsMass = impostor.getParam("mass");
  23212. serializationObject.physicsFriction = impostor.getParam("friction");
  23213. serializationObject.physicsRestitution = impostor.getParam("mass");
  23214. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  23215. }
  23216. // Metadata
  23217. if (this.metadata) {
  23218. serializationObject.metadata = this.metadata;
  23219. }
  23220. // Instances
  23221. serializationObject.instances = [];
  23222. for (var index = 0; index < this.instances.length; index++) {
  23223. var instance = this.instances[index];
  23224. var serializationInstance = {
  23225. name: instance.name,
  23226. position: instance.position.asArray(),
  23227. scaling: instance.scaling.asArray()
  23228. };
  23229. if (instance.rotationQuaternion) {
  23230. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  23231. }
  23232. else if (instance.rotation) {
  23233. serializationInstance.rotation = instance.rotation.asArray();
  23234. }
  23235. serializationObject.instances.push(serializationInstance);
  23236. // Animations
  23237. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  23238. serializationInstance.ranges = instance.serializeAnimationRanges();
  23239. }
  23240. //
  23241. // Animations
  23242. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23243. serializationObject.ranges = this.serializeAnimationRanges();
  23244. // Layer mask
  23245. serializationObject.layerMask = this.layerMask;
  23246. // Alpha
  23247. serializationObject.alphaIndex = this.alphaIndex;
  23248. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  23249. // Overlay
  23250. serializationObject.overlayAlpha = this.overlayAlpha;
  23251. serializationObject.overlayColor = this.overlayColor.asArray();
  23252. serializationObject.renderOverlay = this.renderOverlay;
  23253. // Fog
  23254. serializationObject.applyFog = this.applyFog;
  23255. // Action Manager
  23256. if (this.actionManager) {
  23257. serializationObject.actions = this.actionManager.serialize(this.name);
  23258. }
  23259. };
  23260. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  23261. if (!this.geometry) {
  23262. return;
  23263. }
  23264. this._markSubMeshesAsAttributesDirty();
  23265. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  23266. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  23267. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  23268. this.morphTargetManager = undefined;
  23269. return;
  23270. }
  23271. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  23272. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  23273. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  23274. if (morphTarget.hasNormals) {
  23275. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  23276. }
  23277. if (morphTarget.hasTangents) {
  23278. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  23279. }
  23280. }
  23281. }
  23282. else {
  23283. var index = 0;
  23284. // Positions
  23285. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  23286. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  23287. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  23288. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  23289. }
  23290. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  23291. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  23292. }
  23293. index++;
  23294. }
  23295. }
  23296. };
  23297. // Statics
  23298. /**
  23299. * Returns a new Mesh object what is a deep copy of the passed mesh.
  23300. * The parameter `parsedMesh` is the mesh to be copied.
  23301. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  23302. */
  23303. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  23304. var mesh;
  23305. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  23306. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  23307. }
  23308. else {
  23309. mesh = new Mesh(parsedMesh.name, scene);
  23310. }
  23311. mesh.id = parsedMesh.id;
  23312. if (BABYLON.Tags) {
  23313. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  23314. }
  23315. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  23316. if (parsedMesh.metadata !== undefined) {
  23317. mesh.metadata = parsedMesh.metadata;
  23318. }
  23319. if (parsedMesh.rotationQuaternion) {
  23320. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  23321. }
  23322. else if (parsedMesh.rotation) {
  23323. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  23324. }
  23325. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  23326. if (parsedMesh.localMatrix) {
  23327. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  23328. }
  23329. else if (parsedMesh.pivotMatrix) {
  23330. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  23331. }
  23332. mesh.setEnabled(parsedMesh.isEnabled);
  23333. mesh.isVisible = parsedMesh.isVisible;
  23334. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  23335. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  23336. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  23337. if (parsedMesh.applyFog !== undefined) {
  23338. mesh.applyFog = parsedMesh.applyFog;
  23339. }
  23340. if (parsedMesh.pickable !== undefined) {
  23341. mesh.isPickable = parsedMesh.pickable;
  23342. }
  23343. if (parsedMesh.alphaIndex !== undefined) {
  23344. mesh.alphaIndex = parsedMesh.alphaIndex;
  23345. }
  23346. mesh.receiveShadows = parsedMesh.receiveShadows;
  23347. mesh.billboardMode = parsedMesh.billboardMode;
  23348. if (parsedMesh.visibility !== undefined) {
  23349. mesh.visibility = parsedMesh.visibility;
  23350. }
  23351. mesh.checkCollisions = parsedMesh.checkCollisions;
  23352. if (parsedMesh.isBlocker !== undefined) {
  23353. mesh.isBlocker = parsedMesh.isBlocker;
  23354. }
  23355. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  23356. // freezeWorldMatrix
  23357. if (parsedMesh.freezeWorldMatrix) {
  23358. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  23359. }
  23360. // Parent
  23361. if (parsedMesh.parentId) {
  23362. mesh._waitingParentId = parsedMesh.parentId;
  23363. }
  23364. // Actions
  23365. if (parsedMesh.actions !== undefined) {
  23366. mesh._waitingActions = parsedMesh.actions;
  23367. }
  23368. // Overlay
  23369. if (parsedMesh.overlayAlpha !== undefined) {
  23370. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  23371. }
  23372. if (parsedMesh.overlayColor !== undefined) {
  23373. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  23374. }
  23375. if (parsedMesh.renderOverlay !== undefined) {
  23376. mesh.renderOverlay = parsedMesh.renderOverlay;
  23377. }
  23378. // Geometry
  23379. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  23380. if (parsedMesh.delayLoadingFile) {
  23381. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23382. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  23383. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  23384. if (parsedMesh._binaryInfo) {
  23385. mesh._binaryInfo = parsedMesh._binaryInfo;
  23386. }
  23387. mesh._delayInfo = [];
  23388. if (parsedMesh.hasUVs) {
  23389. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  23390. }
  23391. if (parsedMesh.hasUVs2) {
  23392. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  23393. }
  23394. if (parsedMesh.hasUVs3) {
  23395. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  23396. }
  23397. if (parsedMesh.hasUVs4) {
  23398. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  23399. }
  23400. if (parsedMesh.hasUVs5) {
  23401. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  23402. }
  23403. if (parsedMesh.hasUVs6) {
  23404. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  23405. }
  23406. if (parsedMesh.hasColors) {
  23407. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  23408. }
  23409. if (parsedMesh.hasMatricesIndices) {
  23410. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23411. }
  23412. if (parsedMesh.hasMatricesWeights) {
  23413. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23414. }
  23415. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  23416. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  23417. mesh._checkDelayState();
  23418. }
  23419. }
  23420. else {
  23421. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  23422. }
  23423. // Material
  23424. if (parsedMesh.materialId) {
  23425. mesh.setMaterialByID(parsedMesh.materialId);
  23426. }
  23427. else {
  23428. mesh.material = null;
  23429. }
  23430. // Morph targets
  23431. if (parsedMesh.morphTargetManagerId > -1) {
  23432. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  23433. }
  23434. // Skeleton
  23435. if (parsedMesh.skeletonId > -1) {
  23436. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  23437. if (parsedMesh.numBoneInfluencers) {
  23438. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  23439. }
  23440. }
  23441. // Animations
  23442. if (parsedMesh.animations) {
  23443. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23444. var parsedAnimation = parsedMesh.animations[animationIndex];
  23445. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23446. }
  23447. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  23448. }
  23449. if (parsedMesh.autoAnimate) {
  23450. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  23451. }
  23452. // Layer Mask
  23453. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  23454. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  23455. }
  23456. else {
  23457. mesh.layerMask = 0x0FFFFFFF;
  23458. }
  23459. // Physics
  23460. if (parsedMesh.physicsImpostor) {
  23461. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  23462. mass: parsedMesh.physicsMass,
  23463. friction: parsedMesh.physicsFriction,
  23464. restitution: parsedMesh.physicsRestitution
  23465. }, scene);
  23466. }
  23467. // Instances
  23468. if (parsedMesh.instances) {
  23469. for (var index = 0; index < parsedMesh.instances.length; index++) {
  23470. var parsedInstance = parsedMesh.instances[index];
  23471. var instance = mesh.createInstance(parsedInstance.name);
  23472. if (BABYLON.Tags) {
  23473. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  23474. }
  23475. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  23476. if (parsedInstance.parentId) {
  23477. instance._waitingParentId = parsedInstance.parentId;
  23478. }
  23479. if (parsedInstance.rotationQuaternion) {
  23480. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  23481. }
  23482. else if (parsedInstance.rotation) {
  23483. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  23484. }
  23485. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  23486. instance.checkCollisions = mesh.checkCollisions;
  23487. if (parsedMesh.animations) {
  23488. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  23489. parsedAnimation = parsedMesh.animations[animationIndex];
  23490. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23491. }
  23492. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  23493. }
  23494. }
  23495. }
  23496. return mesh;
  23497. };
  23498. /**
  23499. * Creates a ribbon mesh.
  23500. * Please consider using the same method from the MeshBuilder class instead.
  23501. * 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.
  23502. *
  23503. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  23504. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  23505. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  23506. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  23507. * 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.
  23508. * 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.
  23509. * 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
  23510. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23511. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23512. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23513. */
  23514. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  23515. return BABYLON.MeshBuilder.CreateRibbon(name, {
  23516. pathArray: pathArray,
  23517. closeArray: closeArray,
  23518. closePath: closePath,
  23519. offset: offset,
  23520. updatable: updatable,
  23521. sideOrientation: sideOrientation,
  23522. instance: instance
  23523. }, scene);
  23524. };
  23525. /**
  23526. * Creates a plane polygonal mesh. By default, this is a disc.
  23527. * Please consider using the same method from the MeshBuilder class instead.
  23528. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  23529. * 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.
  23530. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23531. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23532. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23533. */
  23534. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  23535. var options = {
  23536. radius: radius,
  23537. tessellation: tessellation,
  23538. sideOrientation: sideOrientation,
  23539. updatable: updatable
  23540. };
  23541. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  23542. };
  23543. /**
  23544. * Creates a box mesh.
  23545. * Please consider using the same method from the MeshBuilder class instead.
  23546. * The parameter `size` sets the size (float) of each box side (default 1).
  23547. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23548. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23549. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23550. */
  23551. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  23552. var options = {
  23553. size: size,
  23554. sideOrientation: sideOrientation,
  23555. updatable: updatable
  23556. };
  23557. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  23558. };
  23559. /**
  23560. * Creates a sphere mesh.
  23561. * Please consider using the same method from the MeshBuilder class instead.
  23562. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  23563. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  23564. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23565. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23566. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23567. */
  23568. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  23569. var options = {
  23570. segments: segments,
  23571. diameterX: diameter,
  23572. diameterY: diameter,
  23573. diameterZ: diameter,
  23574. sideOrientation: sideOrientation,
  23575. updatable: updatable
  23576. };
  23577. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  23578. };
  23579. /**
  23580. * Creates a cylinder or a cone mesh.
  23581. * Please consider using the same method from the MeshBuilder class instead.
  23582. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  23583. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  23584. * 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.
  23585. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  23586. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  23587. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23588. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23589. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23590. */
  23591. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  23592. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  23593. if (scene !== undefined) {
  23594. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  23595. updatable = scene;
  23596. }
  23597. scene = subdivisions;
  23598. subdivisions = 1;
  23599. }
  23600. var options = {
  23601. height: height,
  23602. diameterTop: diameterTop,
  23603. diameterBottom: diameterBottom,
  23604. tessellation: tessellation,
  23605. subdivisions: subdivisions,
  23606. sideOrientation: sideOrientation,
  23607. updatable: updatable
  23608. };
  23609. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  23610. };
  23611. // Torus (Code from SharpDX.org)
  23612. /**
  23613. * Creates a torus mesh.
  23614. * Please consider using the same method from the MeshBuilder class instead.
  23615. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  23616. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  23617. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  23618. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23619. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23620. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23621. */
  23622. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  23623. var options = {
  23624. diameter: diameter,
  23625. thickness: thickness,
  23626. tessellation: tessellation,
  23627. sideOrientation: sideOrientation,
  23628. updatable: updatable
  23629. };
  23630. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  23631. };
  23632. /**
  23633. * Creates a torus knot mesh.
  23634. * Please consider using the same method from the MeshBuilder class instead.
  23635. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  23636. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  23637. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  23638. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  23639. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23640. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23641. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23642. */
  23643. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  23644. var options = {
  23645. radius: radius,
  23646. tube: tube,
  23647. radialSegments: radialSegments,
  23648. tubularSegments: tubularSegments,
  23649. p: p,
  23650. q: q,
  23651. sideOrientation: sideOrientation,
  23652. updatable: updatable
  23653. };
  23654. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  23655. };
  23656. /**
  23657. * Creates a line mesh.
  23658. * Please consider using the same method from the MeshBuilder class instead.
  23659. * 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.
  23660. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23661. * The parameter `points` is an array successive Vector3.
  23662. * 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
  23663. * When updating an instance, remember that only point positions can change, not the number of points.
  23664. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23665. */
  23666. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  23667. var options = {
  23668. points: points,
  23669. updatable: updatable,
  23670. instance: instance
  23671. };
  23672. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  23673. };
  23674. /**
  23675. * Creates a dashed line mesh.
  23676. * Please consider using the same method from the MeshBuilder class instead.
  23677. * 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.
  23678. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23679. * The parameter `points` is an array successive Vector3.
  23680. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  23681. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  23682. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  23683. * 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
  23684. * When updating an instance, remember that only point positions can change, not the number of points.
  23685. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23686. */
  23687. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  23688. var options = {
  23689. points: points,
  23690. dashSize: dashSize,
  23691. gapSize: gapSize,
  23692. dashNb: dashNb,
  23693. updatable: updatable,
  23694. instance: instance
  23695. };
  23696. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  23697. };
  23698. /**
  23699. * Creates a polygon mesh.
  23700. * Please consider using the same method from the MeshBuilder class instead.
  23701. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  23702. * 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.
  23703. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23704. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23705. * Remember you can only change the shape positions, not their number when updating a polygon.
  23706. */
  23707. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  23708. var options = {
  23709. shape: shape,
  23710. holes: holes,
  23711. updatable: updatable,
  23712. sideOrientation: sideOrientation
  23713. };
  23714. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  23715. };
  23716. /**
  23717. * Creates an extruded polygon mesh, with depth in the Y direction.
  23718. * Please consider using the same method from the MeshBuilder class instead.
  23719. */
  23720. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  23721. var options = {
  23722. shape: shape,
  23723. holes: holes,
  23724. depth: depth,
  23725. updatable: updatable,
  23726. sideOrientation: sideOrientation
  23727. };
  23728. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  23729. };
  23730. /**
  23731. * Creates an extruded shape mesh.
  23732. * 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.
  23733. * Please consider using the same method from the MeshBuilder class instead.
  23734. *
  23735. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23736. * 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
  23737. * extruded along the Z axis.
  23738. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23739. * 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.
  23740. * The parameter `scale` (float, default 1) is the value to scale the shape.
  23741. * 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
  23742. * 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
  23743. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23744. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23745. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23746. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23747. */
  23748. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  23749. var options = {
  23750. shape: shape,
  23751. path: path,
  23752. scale: scale,
  23753. rotation: rotation,
  23754. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23755. sideOrientation: sideOrientation,
  23756. instance: instance,
  23757. updatable: updatable
  23758. };
  23759. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  23760. };
  23761. /**
  23762. * Creates an custom extruded shape mesh.
  23763. * 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.
  23764. * Please consider using the same method from the MeshBuilder class instead.
  23765. *
  23766. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23767. * 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
  23768. * extruded along the Z axis.
  23769. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23770. * 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
  23771. * and the distance of this point from the begining of the path :
  23772. * ```javascript
  23773. * var rotationFunction = function(i, distance) {
  23774. * // do things
  23775. * return rotationValue; }
  23776. * ```
  23777. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  23778. * 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
  23779. * and the distance of this point from the begining of the path :
  23780. * ```javascript
  23781. * var scaleFunction = function(i, distance) {
  23782. * // do things
  23783. * return scaleValue;}
  23784. * ```
  23785. * It must returns a float value that will be the scale value applied to the shape on each path point.
  23786. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  23787. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  23788. * 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
  23789. * 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
  23790. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23791. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23792. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23793. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23794. */
  23795. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  23796. var options = {
  23797. shape: shape,
  23798. path: path,
  23799. scaleFunction: scaleFunction,
  23800. rotationFunction: rotationFunction,
  23801. ribbonCloseArray: ribbonCloseArray,
  23802. ribbonClosePath: ribbonClosePath,
  23803. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23804. sideOrientation: sideOrientation,
  23805. instance: instance,
  23806. updatable: updatable
  23807. };
  23808. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  23809. };
  23810. /**
  23811. * Creates lathe mesh.
  23812. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  23813. * Please consider using the same method from the MeshBuilder class instead.
  23814. * 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
  23815. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  23816. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  23817. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  23818. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23819. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23820. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23821. */
  23822. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  23823. var options = {
  23824. shape: shape,
  23825. radius: radius,
  23826. tessellation: tessellation,
  23827. sideOrientation: sideOrientation,
  23828. updatable: updatable
  23829. };
  23830. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  23831. };
  23832. /**
  23833. * Creates a plane mesh.
  23834. * Please consider using the same method from the MeshBuilder class instead.
  23835. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  23836. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23837. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23838. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23839. */
  23840. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  23841. var options = {
  23842. size: size,
  23843. width: size,
  23844. height: size,
  23845. sideOrientation: sideOrientation,
  23846. updatable: updatable
  23847. };
  23848. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  23849. };
  23850. /**
  23851. * Creates a ground mesh.
  23852. * Please consider using the same method from the MeshBuilder class instead.
  23853. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  23854. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  23855. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23856. */
  23857. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  23858. var options = {
  23859. width: width,
  23860. height: height,
  23861. subdivisions: subdivisions,
  23862. updatable: updatable
  23863. };
  23864. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  23865. };
  23866. /**
  23867. * Creates a tiled ground mesh.
  23868. * Please consider using the same method from the MeshBuilder class instead.
  23869. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  23870. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  23871. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  23872. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  23873. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  23874. * numbers of subdivisions on the ground width and height of each tile.
  23875. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23876. */
  23877. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  23878. var options = {
  23879. xmin: xmin,
  23880. zmin: zmin,
  23881. xmax: xmax,
  23882. zmax: zmax,
  23883. subdivisions: subdivisions,
  23884. precision: precision,
  23885. updatable: updatable
  23886. };
  23887. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  23888. };
  23889. /**
  23890. * Creates a ground mesh from a height map.
  23891. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  23892. * Please consider using the same method from the MeshBuilder class instead.
  23893. * The parameter `url` sets the URL of the height map image resource.
  23894. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  23895. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  23896. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  23897. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  23898. * 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).
  23899. * This function is passed the newly built mesh :
  23900. * ```javascript
  23901. * function(mesh) { // do things
  23902. * return; }
  23903. * ```
  23904. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23905. */
  23906. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  23907. var options = {
  23908. width: width,
  23909. height: height,
  23910. subdivisions: subdivisions,
  23911. minHeight: minHeight,
  23912. maxHeight: maxHeight,
  23913. updatable: updatable,
  23914. onReady: onReady
  23915. };
  23916. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  23917. };
  23918. /**
  23919. * Creates a tube mesh.
  23920. * 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.
  23921. * Please consider using the same method from the MeshBuilder class instead.
  23922. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  23923. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  23924. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  23925. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  23926. * 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.
  23927. * It must return a radius value (positive float) :
  23928. * ```javascript
  23929. * var radiusFunction = function(i, distance) {
  23930. * // do things
  23931. * return radius; }
  23932. * ```
  23933. * 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
  23934. * 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
  23935. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23936. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23937. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23938. */
  23939. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  23940. var options = {
  23941. path: path,
  23942. radius: radius,
  23943. tessellation: tessellation,
  23944. radiusFunction: radiusFunction,
  23945. arc: 1,
  23946. cap: cap,
  23947. updatable: updatable,
  23948. sideOrientation: sideOrientation,
  23949. instance: instance
  23950. };
  23951. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  23952. };
  23953. /**
  23954. * Creates a polyhedron mesh.
  23955. * Please consider using the same method from the MeshBuilder class instead.
  23956. * 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
  23957. * to choose the wanted type.
  23958. * The parameter `size` (positive float, default 1) sets the polygon size.
  23959. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23960. * 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`.
  23961. * 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
  23962. * 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)`).
  23963. * 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
  23964. * 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.
  23965. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23966. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23967. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23968. */
  23969. Mesh.CreatePolyhedron = function (name, options, scene) {
  23970. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  23971. };
  23972. /**
  23973. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  23974. * Please consider using the same method from the MeshBuilder class instead.
  23975. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  23976. * 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`).
  23977. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  23978. * 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.
  23979. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23980. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23981. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23982. */
  23983. Mesh.CreateIcoSphere = function (name, options, scene) {
  23984. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  23985. };
  23986. /**
  23987. * Creates a decal mesh.
  23988. * Please consider using the same method from the MeshBuilder class instead.
  23989. * 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.
  23990. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23991. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23992. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23993. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23994. */
  23995. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  23996. var options = {
  23997. position: position,
  23998. normal: normal,
  23999. size: size,
  24000. angle: angle
  24001. };
  24002. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  24003. };
  24004. // Skeletons
  24005. /**
  24006. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  24007. */
  24008. Mesh.prototype.setPositionsForCPUSkinning = function () {
  24009. var source;
  24010. if (!this._sourcePositions) {
  24011. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24012. this._sourcePositions = new Float32Array(source);
  24013. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  24014. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  24015. }
  24016. }
  24017. return this._sourcePositions;
  24018. };
  24019. /**
  24020. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  24021. */
  24022. Mesh.prototype.setNormalsForCPUSkinning = function () {
  24023. var source;
  24024. if (!this._sourceNormals) {
  24025. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24026. this._sourceNormals = new Float32Array(source);
  24027. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  24028. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  24029. }
  24030. }
  24031. return this._sourceNormals;
  24032. };
  24033. /**
  24034. * Updates the vertex buffer by applying transformation from the bones.
  24035. * Returns the Mesh.
  24036. *
  24037. * @param {skeleton} skeleton to apply
  24038. */
  24039. Mesh.prototype.applySkeleton = function (skeleton) {
  24040. if (!this.geometry) {
  24041. return this;
  24042. }
  24043. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  24044. return this;
  24045. }
  24046. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  24047. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24048. return this;
  24049. }
  24050. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24051. return this;
  24052. }
  24053. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24054. return this;
  24055. }
  24056. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24057. return this;
  24058. }
  24059. if (!this._sourcePositions) {
  24060. var submeshes = this.subMeshes.slice();
  24061. this.setPositionsForCPUSkinning();
  24062. this.subMeshes = submeshes;
  24063. }
  24064. if (!this._sourceNormals) {
  24065. this.setNormalsForCPUSkinning();
  24066. }
  24067. // positionsData checks for not being Float32Array will only pass at most once
  24068. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24069. if (!(positionsData instanceof Float32Array)) {
  24070. positionsData = new Float32Array(positionsData);
  24071. }
  24072. // normalsData checks for not being Float32Array will only pass at most once
  24073. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24074. if (!(normalsData instanceof Float32Array)) {
  24075. normalsData = new Float32Array(normalsData);
  24076. }
  24077. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  24078. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  24079. var needExtras = this.numBoneInfluencers > 4;
  24080. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  24081. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  24082. var skeletonMatrices = skeleton.getTransformMatrices(this);
  24083. var tempVector3 = BABYLON.Vector3.Zero();
  24084. var finalMatrix = new BABYLON.Matrix();
  24085. var tempMatrix = new BABYLON.Matrix();
  24086. var matWeightIdx = 0;
  24087. var inf;
  24088. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  24089. var weight;
  24090. for (inf = 0; inf < 4; inf++) {
  24091. weight = matricesWeightsData[matWeightIdx + inf];
  24092. if (weight > 0) {
  24093. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24094. finalMatrix.addToSelf(tempMatrix);
  24095. }
  24096. else
  24097. break;
  24098. }
  24099. if (needExtras) {
  24100. for (inf = 0; inf < 4; inf++) {
  24101. weight = matricesWeightsExtraData[matWeightIdx + inf];
  24102. if (weight > 0) {
  24103. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24104. finalMatrix.addToSelf(tempMatrix);
  24105. }
  24106. else
  24107. break;
  24108. }
  24109. }
  24110. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  24111. tempVector3.toArray(positionsData, index);
  24112. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  24113. tempVector3.toArray(normalsData, index);
  24114. finalMatrix.reset();
  24115. }
  24116. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  24117. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  24118. return this;
  24119. };
  24120. // Tools
  24121. /**
  24122. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  24123. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  24124. */
  24125. Mesh.MinMax = function (meshes) {
  24126. var minVector = null;
  24127. var maxVector = null;
  24128. meshes.forEach(function (mesh, index, array) {
  24129. var boundingBox = mesh.getBoundingInfo().boundingBox;
  24130. if (!minVector) {
  24131. minVector = boundingBox.minimumWorld;
  24132. maxVector = boundingBox.maximumWorld;
  24133. }
  24134. else {
  24135. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  24136. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  24137. }
  24138. });
  24139. return {
  24140. min: minVector,
  24141. max: maxVector
  24142. };
  24143. };
  24144. /**
  24145. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  24146. */
  24147. Mesh.Center = function (meshesOrMinMaxVector) {
  24148. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  24149. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  24150. };
  24151. /**
  24152. * Merge the array of meshes into a single mesh for performance reasons.
  24153. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  24154. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  24155. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  24156. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  24157. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  24158. */
  24159. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  24160. if (disposeSource === void 0) { disposeSource = true; }
  24161. var index;
  24162. if (!allow32BitsIndices) {
  24163. var totalVertices = 0;
  24164. // Counting vertices
  24165. for (index = 0; index < meshes.length; index++) {
  24166. if (meshes[index]) {
  24167. totalVertices += meshes[index].getTotalVertices();
  24168. if (totalVertices > 65536) {
  24169. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  24170. return null;
  24171. }
  24172. }
  24173. }
  24174. }
  24175. // Merge
  24176. var vertexData;
  24177. var otherVertexData;
  24178. var indiceArray = new Array();
  24179. var source;
  24180. for (index = 0; index < meshes.length; index++) {
  24181. if (meshes[index]) {
  24182. meshes[index].computeWorldMatrix(true);
  24183. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  24184. otherVertexData.transform(meshes[index].getWorldMatrix());
  24185. if (vertexData) {
  24186. vertexData.merge(otherVertexData);
  24187. }
  24188. else {
  24189. vertexData = otherVertexData;
  24190. source = meshes[index];
  24191. }
  24192. if (subdivideWithSubMeshes) {
  24193. indiceArray.push(meshes[index].getTotalIndices());
  24194. }
  24195. }
  24196. }
  24197. if (!meshSubclass) {
  24198. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  24199. }
  24200. vertexData.applyToMesh(meshSubclass);
  24201. // Setting properties
  24202. meshSubclass.material = source.material;
  24203. meshSubclass.checkCollisions = source.checkCollisions;
  24204. // Cleaning
  24205. if (disposeSource) {
  24206. for (index = 0; index < meshes.length; index++) {
  24207. if (meshes[index]) {
  24208. meshes[index].dispose();
  24209. }
  24210. }
  24211. }
  24212. // Subdivide
  24213. if (subdivideWithSubMeshes) {
  24214. //-- Suppresions du submesh global
  24215. meshSubclass.releaseSubMeshes();
  24216. index = 0;
  24217. var offset = 0;
  24218. //-- aplique la subdivision en fonction du tableau d'indices
  24219. while (index < indiceArray.length) {
  24220. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  24221. offset += indiceArray[index];
  24222. index++;
  24223. }
  24224. }
  24225. return meshSubclass;
  24226. };
  24227. // Consts
  24228. Mesh._FRONTSIDE = 0;
  24229. Mesh._BACKSIDE = 1;
  24230. Mesh._DOUBLESIDE = 2;
  24231. Mesh._DEFAULTSIDE = 0;
  24232. Mesh._NO_CAP = 0;
  24233. Mesh._CAP_START = 1;
  24234. Mesh._CAP_END = 2;
  24235. Mesh._CAP_ALL = 3;
  24236. return Mesh;
  24237. }(BABYLON.AbstractMesh));
  24238. BABYLON.Mesh = Mesh;
  24239. })(BABYLON || (BABYLON = {}));
  24240. //# sourceMappingURL=babylon.mesh.js.map
  24241. var BABYLON;
  24242. (function (BABYLON) {
  24243. var BaseSubMesh = (function () {
  24244. function BaseSubMesh() {
  24245. }
  24246. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  24247. get: function () {
  24248. return this._materialEffect;
  24249. },
  24250. enumerable: true,
  24251. configurable: true
  24252. });
  24253. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  24254. if (this._materialEffect === effect) {
  24255. if (!effect) {
  24256. this._materialDefines = undefined;
  24257. }
  24258. return;
  24259. }
  24260. this._materialDefines = defines;
  24261. this._materialEffect = effect;
  24262. };
  24263. return BaseSubMesh;
  24264. }());
  24265. BABYLON.BaseSubMesh = BaseSubMesh;
  24266. var SubMesh = (function (_super) {
  24267. __extends(SubMesh, _super);
  24268. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  24269. if (createBoundingBox === void 0) { createBoundingBox = true; }
  24270. var _this = _super.call(this) || this;
  24271. _this.materialIndex = materialIndex;
  24272. _this.verticesStart = verticesStart;
  24273. _this.verticesCount = verticesCount;
  24274. _this.indexStart = indexStart;
  24275. _this.indexCount = indexCount;
  24276. _this._renderId = 0;
  24277. _this._mesh = mesh;
  24278. _this._renderingMesh = renderingMesh || mesh;
  24279. mesh.subMeshes.push(_this);
  24280. _this._trianglePlanes = [];
  24281. _this._id = mesh.subMeshes.length - 1;
  24282. if (createBoundingBox) {
  24283. _this.refreshBoundingInfo();
  24284. mesh.computeWorldMatrix(true);
  24285. }
  24286. return _this;
  24287. }
  24288. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  24289. get: function () {
  24290. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  24291. },
  24292. enumerable: true,
  24293. configurable: true
  24294. });
  24295. /**
  24296. * Returns the submesh BoudingInfo object.
  24297. */
  24298. SubMesh.prototype.getBoundingInfo = function () {
  24299. if (this.IsGlobal) {
  24300. return this._mesh.getBoundingInfo();
  24301. }
  24302. return this._boundingInfo;
  24303. };
  24304. /**
  24305. * Sets the submesh BoundingInfo.
  24306. * Return the SubMesh.
  24307. */
  24308. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  24309. this._boundingInfo = boundingInfo;
  24310. return this;
  24311. };
  24312. /**
  24313. * Returns the mesh of the current submesh.
  24314. */
  24315. SubMesh.prototype.getMesh = function () {
  24316. return this._mesh;
  24317. };
  24318. /**
  24319. * Returns the rendering mesh of the submesh.
  24320. */
  24321. SubMesh.prototype.getRenderingMesh = function () {
  24322. return this._renderingMesh;
  24323. };
  24324. /**
  24325. * Returns the submesh material.
  24326. */
  24327. SubMesh.prototype.getMaterial = function () {
  24328. var rootMaterial = this._renderingMesh.material;
  24329. if (rootMaterial && rootMaterial.getSubMaterial) {
  24330. var multiMaterial = rootMaterial;
  24331. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  24332. if (this._currentMaterial !== effectiveMaterial) {
  24333. this._currentMaterial = effectiveMaterial;
  24334. this._materialDefines = undefined;
  24335. }
  24336. return effectiveMaterial;
  24337. }
  24338. if (!rootMaterial) {
  24339. return this._mesh.getScene().defaultMaterial;
  24340. }
  24341. return rootMaterial;
  24342. };
  24343. // Methods
  24344. /**
  24345. * Sets a new updated BoundingInfo object to the submesh.
  24346. * Returns the SubMesh.
  24347. */
  24348. SubMesh.prototype.refreshBoundingInfo = function () {
  24349. this._lastColliderWorldVertices = null;
  24350. if (this.IsGlobal) {
  24351. return;
  24352. }
  24353. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24354. if (!data) {
  24355. this._boundingInfo = this._mesh._boundingInfo;
  24356. return;
  24357. }
  24358. var indices = this._renderingMesh.getIndices();
  24359. var extend;
  24360. //is this the only submesh?
  24361. if (this.indexStart === 0 && this.indexCount === indices.length) {
  24362. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  24363. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  24364. }
  24365. else {
  24366. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  24367. }
  24368. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24369. return this;
  24370. };
  24371. SubMesh.prototype._checkCollision = function (collider) {
  24372. return this.getBoundingInfo()._checkCollision(collider);
  24373. };
  24374. /**
  24375. * Updates the submesh BoundingInfo.
  24376. * Returns the Submesh.
  24377. */
  24378. SubMesh.prototype.updateBoundingInfo = function (world) {
  24379. if (!this.getBoundingInfo()) {
  24380. this.refreshBoundingInfo();
  24381. }
  24382. this.getBoundingInfo().update(world);
  24383. return this;
  24384. };
  24385. /**
  24386. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  24387. * Boolean returned.
  24388. */
  24389. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  24390. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  24391. };
  24392. /**
  24393. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  24394. * Boolean returned.
  24395. */
  24396. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  24397. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  24398. };
  24399. /**
  24400. * Renders the submesh.
  24401. * Returns it.
  24402. */
  24403. SubMesh.prototype.render = function (enableAlphaMode) {
  24404. this._renderingMesh.render(this, enableAlphaMode);
  24405. return this;
  24406. };
  24407. /**
  24408. * Returns a new Index Buffer.
  24409. * Type returned : WebGLBuffer.
  24410. */
  24411. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  24412. if (!this._linesIndexBuffer) {
  24413. var linesIndices = [];
  24414. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24415. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  24416. }
  24417. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  24418. this.linesIndexCount = linesIndices.length;
  24419. }
  24420. return this._linesIndexBuffer;
  24421. };
  24422. /**
  24423. * True is the passed Ray intersects the submesh bounding box.
  24424. * Boolean returned.
  24425. */
  24426. SubMesh.prototype.canIntersects = function (ray) {
  24427. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  24428. };
  24429. /**
  24430. * Returns an object IntersectionInfo.
  24431. */
  24432. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  24433. var intersectInfo = null;
  24434. // LineMesh first as it's also a Mesh...
  24435. if (this._mesh instanceof BABYLON.LinesMesh) {
  24436. var lineMesh = this._mesh;
  24437. // Line test
  24438. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  24439. var p0 = positions[indices[index]];
  24440. var p1 = positions[indices[index + 1]];
  24441. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  24442. if (length < 0) {
  24443. continue;
  24444. }
  24445. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  24446. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  24447. if (fastCheck) {
  24448. break;
  24449. }
  24450. }
  24451. }
  24452. }
  24453. else {
  24454. // Triangles test
  24455. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  24456. var p0 = positions[indices[index]];
  24457. var p1 = positions[indices[index + 1]];
  24458. var p2 = positions[indices[index + 2]];
  24459. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  24460. if (currentIntersectInfo) {
  24461. if (currentIntersectInfo.distance < 0) {
  24462. continue;
  24463. }
  24464. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  24465. intersectInfo = currentIntersectInfo;
  24466. intersectInfo.faceId = index / 3;
  24467. if (fastCheck) {
  24468. break;
  24469. }
  24470. }
  24471. }
  24472. }
  24473. }
  24474. return intersectInfo;
  24475. };
  24476. SubMesh.prototype._rebuild = function () {
  24477. if (this._linesIndexBuffer) {
  24478. this._linesIndexBuffer = null;
  24479. }
  24480. };
  24481. // Clone
  24482. /**
  24483. * Creates a new Submesh from the passed Mesh.
  24484. */
  24485. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  24486. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  24487. if (!this.IsGlobal) {
  24488. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  24489. }
  24490. return result;
  24491. };
  24492. // Dispose
  24493. /**
  24494. * Disposes the Submesh.
  24495. * Returns nothing.
  24496. */
  24497. SubMesh.prototype.dispose = function () {
  24498. if (this._linesIndexBuffer) {
  24499. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  24500. this._linesIndexBuffer = null;
  24501. }
  24502. // Remove from mesh
  24503. var index = this._mesh.subMeshes.indexOf(this);
  24504. this._mesh.subMeshes.splice(index, 1);
  24505. };
  24506. // Statics
  24507. /**
  24508. * Creates a new Submesh from the passed parameters :
  24509. * - materialIndex (integer) : the index of the main mesh material.
  24510. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  24511. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  24512. * - mesh (Mesh) : the main mesh to create the submesh from.
  24513. * - renderingMesh (optional Mesh) : rendering mesh.
  24514. */
  24515. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  24516. var minVertexIndex = Number.MAX_VALUE;
  24517. var maxVertexIndex = -Number.MAX_VALUE;
  24518. renderingMesh = renderingMesh || mesh;
  24519. var indices = renderingMesh.getIndices();
  24520. for (var index = startIndex; index < startIndex + indexCount; index++) {
  24521. var vertexIndex = indices[index];
  24522. if (vertexIndex < minVertexIndex)
  24523. minVertexIndex = vertexIndex;
  24524. if (vertexIndex > maxVertexIndex)
  24525. maxVertexIndex = vertexIndex;
  24526. }
  24527. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  24528. };
  24529. return SubMesh;
  24530. }(BaseSubMesh));
  24531. BABYLON.SubMesh = SubMesh;
  24532. })(BABYLON || (BABYLON = {}));
  24533. //# sourceMappingURL=babylon.subMesh.js.map
  24534. var BABYLON;
  24535. (function (BABYLON) {
  24536. var EffectFallbacks = (function () {
  24537. function EffectFallbacks() {
  24538. this._defines = {};
  24539. this._currentRank = 32;
  24540. this._maxRank = -1;
  24541. }
  24542. EffectFallbacks.prototype.unBindMesh = function () {
  24543. this._mesh = null;
  24544. };
  24545. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24546. if (!this._defines[rank]) {
  24547. if (rank < this._currentRank) {
  24548. this._currentRank = rank;
  24549. }
  24550. if (rank > this._maxRank) {
  24551. this._maxRank = rank;
  24552. }
  24553. this._defines[rank] = new Array();
  24554. }
  24555. this._defines[rank].push(define);
  24556. };
  24557. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  24558. this._meshRank = rank;
  24559. this._mesh = mesh;
  24560. if (rank < this._currentRank) {
  24561. this._currentRank = rank;
  24562. }
  24563. if (rank > this._maxRank) {
  24564. this._maxRank = rank;
  24565. }
  24566. };
  24567. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  24568. get: function () {
  24569. return this._currentRank <= this._maxRank;
  24570. },
  24571. enumerable: true,
  24572. configurable: true
  24573. });
  24574. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24575. // First we try to switch to CPU skinning
  24576. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  24577. this._mesh.computeBonesUsingShaders = false;
  24578. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  24579. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24580. var scene = this._mesh.getScene();
  24581. for (var index = 0; index < scene.meshes.length; index++) {
  24582. var otherMesh = scene.meshes[index];
  24583. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  24584. otherMesh.computeBonesUsingShaders = false;
  24585. }
  24586. }
  24587. }
  24588. else {
  24589. var currentFallbacks = this._defines[this._currentRank];
  24590. if (currentFallbacks) {
  24591. for (var index = 0; index < currentFallbacks.length; index++) {
  24592. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24593. }
  24594. }
  24595. this._currentRank++;
  24596. }
  24597. return currentDefines;
  24598. };
  24599. return EffectFallbacks;
  24600. }());
  24601. BABYLON.EffectFallbacks = EffectFallbacks;
  24602. var EffectCreationOptions = (function () {
  24603. function EffectCreationOptions() {
  24604. }
  24605. return EffectCreationOptions;
  24606. }());
  24607. BABYLON.EffectCreationOptions = EffectCreationOptions;
  24608. var Effect = (function () {
  24609. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24610. var _this = this;
  24611. this.uniqueId = 0;
  24612. this.onCompileObservable = new BABYLON.Observable();
  24613. this.onErrorObservable = new BABYLON.Observable();
  24614. this.onBindObservable = new BABYLON.Observable();
  24615. this._uniformBuffersNames = {};
  24616. this._isReady = false;
  24617. this._compilationError = "";
  24618. this.name = baseName;
  24619. if (attributesNamesOrOptions.attributes) {
  24620. var options = attributesNamesOrOptions;
  24621. this._engine = uniformsNamesOrEngine;
  24622. this._attributesNames = options.attributes;
  24623. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  24624. this._samplers = options.samplers;
  24625. this.defines = options.defines;
  24626. this.onError = options.onError;
  24627. this.onCompiled = options.onCompiled;
  24628. this._fallbacks = options.fallbacks;
  24629. this._indexParameters = options.indexParameters;
  24630. if (options.uniformBuffersNames) {
  24631. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  24632. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  24633. }
  24634. }
  24635. }
  24636. else {
  24637. this._engine = engine;
  24638. this.defines = defines;
  24639. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  24640. this._samplers = samplers;
  24641. this._attributesNames = attributesNamesOrOptions;
  24642. this.onError = onError;
  24643. this.onCompiled = onCompiled;
  24644. this._indexParameters = indexParameters;
  24645. this._fallbacks = fallbacks;
  24646. }
  24647. this.uniqueId = Effect._uniqueIdSeed++;
  24648. var vertexSource;
  24649. var fragmentSource;
  24650. if (baseName.vertexElement) {
  24651. vertexSource = document.getElementById(baseName.vertexElement);
  24652. if (!vertexSource) {
  24653. vertexSource = baseName.vertexElement;
  24654. }
  24655. }
  24656. else {
  24657. vertexSource = baseName.vertex || baseName;
  24658. }
  24659. if (baseName.fragmentElement) {
  24660. fragmentSource = document.getElementById(baseName.fragmentElement);
  24661. if (!fragmentSource) {
  24662. fragmentSource = baseName.fragmentElement;
  24663. }
  24664. }
  24665. else {
  24666. fragmentSource = baseName.fragment || baseName;
  24667. }
  24668. this._loadVertexShader(vertexSource, function (vertexCode) {
  24669. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24670. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  24671. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24672. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24673. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  24674. if (baseName) {
  24675. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  24676. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  24677. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  24678. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  24679. }
  24680. else {
  24681. _this._vertexSourceCode = migratedVertexCode;
  24682. _this._fragmentSourceCode = migratedFragmentCode;
  24683. }
  24684. _this._prepareEffect();
  24685. });
  24686. });
  24687. });
  24688. });
  24689. });
  24690. });
  24691. }
  24692. Object.defineProperty(Effect.prototype, "key", {
  24693. get: function () {
  24694. return this._key;
  24695. },
  24696. enumerable: true,
  24697. configurable: true
  24698. });
  24699. // Properties
  24700. Effect.prototype.isReady = function () {
  24701. return this._isReady;
  24702. };
  24703. Effect.prototype.getEngine = function () {
  24704. return this._engine;
  24705. };
  24706. Effect.prototype.getProgram = function () {
  24707. return this._program;
  24708. };
  24709. Effect.prototype.getAttributesNames = function () {
  24710. return this._attributesNames;
  24711. };
  24712. Effect.prototype.getAttributeLocation = function (index) {
  24713. return this._attributes[index];
  24714. };
  24715. Effect.prototype.getAttributeLocationByName = function (name) {
  24716. var index = this._attributesNames.indexOf(name);
  24717. return this._attributes[index];
  24718. };
  24719. Effect.prototype.getAttributesCount = function () {
  24720. return this._attributes.length;
  24721. };
  24722. Effect.prototype.getUniformIndex = function (uniformName) {
  24723. return this._uniformsNames.indexOf(uniformName);
  24724. };
  24725. Effect.prototype.getUniform = function (uniformName) {
  24726. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24727. };
  24728. Effect.prototype.getSamplers = function () {
  24729. return this._samplers;
  24730. };
  24731. Effect.prototype.getCompilationError = function () {
  24732. return this._compilationError;
  24733. };
  24734. // Methods
  24735. Effect.prototype.executeWhenCompiled = function (func) {
  24736. if (this.isReady()) {
  24737. func(this);
  24738. return;
  24739. }
  24740. this.onCompileObservable.add(function (effect) {
  24741. func(effect);
  24742. });
  24743. };
  24744. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24745. if (BABYLON.Tools.IsWindowObjectExist()) {
  24746. // DOM element ?
  24747. if (vertex instanceof HTMLElement) {
  24748. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24749. callback(vertexCode);
  24750. return;
  24751. }
  24752. }
  24753. // Base64 encoded ?
  24754. if (vertex.substr(0, 7) === "base64:") {
  24755. var vertexBinary = window.atob(vertex.substr(7));
  24756. callback(vertexBinary);
  24757. return;
  24758. }
  24759. // Is in local store ?
  24760. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24761. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24762. return;
  24763. }
  24764. var vertexShaderUrl;
  24765. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24766. vertexShaderUrl = vertex;
  24767. }
  24768. else {
  24769. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24770. }
  24771. // Vertex shader
  24772. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24773. };
  24774. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24775. if (BABYLON.Tools.IsWindowObjectExist()) {
  24776. // DOM element ?
  24777. if (fragment instanceof HTMLElement) {
  24778. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24779. callback(fragmentCode);
  24780. return;
  24781. }
  24782. }
  24783. // Base64 encoded ?
  24784. if (fragment.substr(0, 7) === "base64:") {
  24785. var fragmentBinary = window.atob(fragment.substr(7));
  24786. callback(fragmentBinary);
  24787. return;
  24788. }
  24789. // Is in local store ?
  24790. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24791. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24792. return;
  24793. }
  24794. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24795. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24796. return;
  24797. }
  24798. var fragmentShaderUrl;
  24799. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24800. fragmentShaderUrl = fragment;
  24801. }
  24802. else {
  24803. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24804. }
  24805. // Fragment shader
  24806. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24807. };
  24808. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  24809. // Rebuild shaders source code
  24810. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  24811. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  24812. vertexCode = prefix + vertexCode;
  24813. fragmentCode = prefix + fragmentCode;
  24814. // Number lines of shaders source code
  24815. var i = 2;
  24816. var regex = /\n/gm;
  24817. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24818. i = 2;
  24819. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24820. // Dump shaders name and formatted source code
  24821. if (this.name.vertexElement) {
  24822. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  24823. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  24824. }
  24825. else if (this.name.vertex) {
  24826. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  24827. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  24828. }
  24829. else {
  24830. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  24831. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  24832. }
  24833. };
  24834. ;
  24835. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  24836. var preparedSourceCode = this._processPrecision(sourceCode);
  24837. if (this._engine.webGLVersion == 1) {
  24838. callback(preparedSourceCode);
  24839. return;
  24840. }
  24841. // Already converted
  24842. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  24843. callback(preparedSourceCode.replace("#version 300 es", ""));
  24844. return;
  24845. }
  24846. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  24847. // Remove extensions
  24848. // #extension GL_OES_standard_derivatives : enable
  24849. // #extension GL_EXT_shader_texture_lod : enable
  24850. // #extension GL_EXT_frag_depth : enable
  24851. // #extension GL_EXT_draw_buffers : require
  24852. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  24853. var result = preparedSourceCode.replace(regex, "");
  24854. // Migrate to GLSL v300
  24855. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  24856. result = result.replace(/attribute[ \t]/g, "in ");
  24857. result = result.replace(/[ \t]attribute/g, " in");
  24858. if (isFragment) {
  24859. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  24860. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  24861. result = result.replace(/texture2D\s*\(/g, "texture(");
  24862. result = result.replace(/textureCube\s*\(/g, "texture(");
  24863. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  24864. result = result.replace(/gl_FragColor/g, "glFragColor");
  24865. result = result.replace(/gl_FragData/g, "glFragData");
  24866. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  24867. }
  24868. callback(result);
  24869. };
  24870. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24871. var _this = this;
  24872. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24873. var match = regex.exec(sourceCode);
  24874. var returnValue = new String(sourceCode);
  24875. while (match != null) {
  24876. var includeFile = match[1];
  24877. // Uniform declaration
  24878. if (includeFile.indexOf("__decl__") !== -1) {
  24879. includeFile = includeFile.replace(/__decl__/, "");
  24880. if (this._engine.supportsUniformBuffers) {
  24881. includeFile = includeFile.replace(/Vertex/, "Ubo");
  24882. includeFile = includeFile.replace(/Fragment/, "Ubo");
  24883. }
  24884. includeFile = includeFile + "Declaration";
  24885. }
  24886. if (Effect.IncludesShadersStore[includeFile]) {
  24887. // Substitution
  24888. var includeContent = Effect.IncludesShadersStore[includeFile];
  24889. if (match[2]) {
  24890. var splits = match[3].split(",");
  24891. for (var index = 0; index < splits.length; index += 2) {
  24892. var source = new RegExp(splits[index], "g");
  24893. var dest = splits[index + 1];
  24894. includeContent = includeContent.replace(source, dest);
  24895. }
  24896. }
  24897. if (match[4]) {
  24898. var indexString = match[5];
  24899. if (indexString.indexOf("..") !== -1) {
  24900. var indexSplits = indexString.split("..");
  24901. var minIndex = parseInt(indexSplits[0]);
  24902. var maxIndex = parseInt(indexSplits[1]);
  24903. var sourceIncludeContent = includeContent.slice(0);
  24904. includeContent = "";
  24905. if (isNaN(maxIndex)) {
  24906. maxIndex = this._indexParameters[indexSplits[1]];
  24907. }
  24908. for (var i = minIndex; i < maxIndex; i++) {
  24909. if (!this._engine.supportsUniformBuffers) {
  24910. // Ubo replacement
  24911. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24912. return p1 + "{X}";
  24913. });
  24914. }
  24915. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  24916. }
  24917. }
  24918. else {
  24919. if (!this._engine.supportsUniformBuffers) {
  24920. // Ubo replacement
  24921. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24922. return p1 + "{X}";
  24923. });
  24924. }
  24925. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24926. }
  24927. }
  24928. // Replace
  24929. returnValue = returnValue.replace(match[0], includeContent);
  24930. }
  24931. else {
  24932. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24933. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24934. Effect.IncludesShadersStore[includeFile] = fileContent;
  24935. _this._processIncludes(returnValue, callback);
  24936. });
  24937. return;
  24938. }
  24939. match = regex.exec(sourceCode);
  24940. }
  24941. callback(returnValue);
  24942. };
  24943. Effect.prototype._processPrecision = function (source) {
  24944. if (source.indexOf("precision highp float") === -1) {
  24945. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24946. source = "precision mediump float;\n" + source;
  24947. }
  24948. else {
  24949. source = "precision highp float;\n" + source;
  24950. }
  24951. }
  24952. else {
  24953. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24954. source = source.replace("precision highp float", "precision mediump float");
  24955. }
  24956. }
  24957. return source;
  24958. };
  24959. Effect.prototype._prepareEffect = function () {
  24960. var attributesNames = this._attributesNames;
  24961. var defines = this.defines;
  24962. var fallbacks = this._fallbacks;
  24963. this._valueCache = {};
  24964. try {
  24965. var engine = this._engine;
  24966. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24967. if (engine.webGLVersion > 1) {
  24968. for (var name in this._uniformBuffersNames) {
  24969. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  24970. }
  24971. }
  24972. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24973. this._attributes = engine.getAttributes(this._program, attributesNames);
  24974. var index;
  24975. for (index = 0; index < this._samplers.length; index++) {
  24976. var sampler = this.getUniform(this._samplers[index]);
  24977. if (sampler == null) {
  24978. this._samplers.splice(index, 1);
  24979. index--;
  24980. }
  24981. }
  24982. engine.bindSamplers(this);
  24983. this._compilationError = "";
  24984. this._isReady = true;
  24985. if (this.onCompiled) {
  24986. this.onCompiled(this);
  24987. }
  24988. this.onCompileObservable.notifyObservers(this);
  24989. this.onCompileObservable.clear();
  24990. // Unbind mesh reference in fallbacks
  24991. if (this._fallbacks) {
  24992. this._fallbacks.unBindMesh();
  24993. }
  24994. }
  24995. catch (e) {
  24996. this._compilationError = e.message;
  24997. // Let's go through fallbacks then
  24998. BABYLON.Tools.Error("Unable to compile effect:");
  24999. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  25000. return " " + uniform;
  25001. }));
  25002. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  25003. return " " + attribute;
  25004. }));
  25005. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  25006. BABYLON.Tools.Error("Error: " + this._compilationError);
  25007. if (fallbacks && fallbacks.isMoreFallbacks) {
  25008. BABYLON.Tools.Error("Trying next fallback.");
  25009. this.defines = fallbacks.reduce(this.defines);
  25010. this._prepareEffect();
  25011. }
  25012. else {
  25013. if (this.onError) {
  25014. this.onError(this, this._compilationError);
  25015. }
  25016. this.onErrorObservable.notifyObservers(this);
  25017. this.onErrorObservable.clear();
  25018. // Unbind mesh reference in fallbacks
  25019. if (this._fallbacks) {
  25020. this._fallbacks.unBindMesh();
  25021. }
  25022. }
  25023. }
  25024. };
  25025. Object.defineProperty(Effect.prototype, "isSupported", {
  25026. get: function () {
  25027. return this._compilationError === "";
  25028. },
  25029. enumerable: true,
  25030. configurable: true
  25031. });
  25032. Effect.prototype._bindTexture = function (channel, texture) {
  25033. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  25034. };
  25035. Effect.prototype.setTexture = function (channel, texture) {
  25036. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  25037. };
  25038. Effect.prototype.setTextureArray = function (channel, textures) {
  25039. if (this._samplers.indexOf(channel + "Ex") === -1) {
  25040. var initialPos = this._samplers.indexOf(channel);
  25041. for (var index = 1; index < textures.length; index++) {
  25042. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  25043. }
  25044. }
  25045. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  25046. };
  25047. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  25048. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  25049. };
  25050. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  25051. var cache = this._valueCache[uniformName];
  25052. var flag = matrix.updateFlag;
  25053. if (cache !== undefined && cache === flag) {
  25054. return false;
  25055. }
  25056. this._valueCache[uniformName] = flag;
  25057. return true;
  25058. };
  25059. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  25060. var cache = this._valueCache[uniformName];
  25061. if (!cache) {
  25062. cache = [x, y];
  25063. this._valueCache[uniformName] = cache;
  25064. return true;
  25065. }
  25066. var changed = false;
  25067. if (cache[0] !== x) {
  25068. cache[0] = x;
  25069. changed = true;
  25070. }
  25071. if (cache[1] !== y) {
  25072. cache[1] = y;
  25073. changed = true;
  25074. }
  25075. return changed;
  25076. };
  25077. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  25078. var cache = this._valueCache[uniformName];
  25079. if (!cache) {
  25080. cache = [x, y, z];
  25081. this._valueCache[uniformName] = cache;
  25082. return true;
  25083. }
  25084. var changed = false;
  25085. if (cache[0] !== x) {
  25086. cache[0] = x;
  25087. changed = true;
  25088. }
  25089. if (cache[1] !== y) {
  25090. cache[1] = y;
  25091. changed = true;
  25092. }
  25093. if (cache[2] !== z) {
  25094. cache[2] = z;
  25095. changed = true;
  25096. }
  25097. return changed;
  25098. };
  25099. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  25100. var cache = this._valueCache[uniformName];
  25101. if (!cache) {
  25102. cache = [x, y, z, w];
  25103. this._valueCache[uniformName] = cache;
  25104. return true;
  25105. }
  25106. var changed = false;
  25107. if (cache[0] !== x) {
  25108. cache[0] = x;
  25109. changed = true;
  25110. }
  25111. if (cache[1] !== y) {
  25112. cache[1] = y;
  25113. changed = true;
  25114. }
  25115. if (cache[2] !== z) {
  25116. cache[2] = z;
  25117. changed = true;
  25118. }
  25119. if (cache[3] !== w) {
  25120. cache[3] = w;
  25121. changed = true;
  25122. }
  25123. return changed;
  25124. };
  25125. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  25126. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  25127. return;
  25128. }
  25129. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  25130. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  25131. };
  25132. Effect.prototype.bindUniformBlock = function (blockName, index) {
  25133. this._engine.bindUniformBlock(this._program, blockName, index);
  25134. };
  25135. Effect.prototype.setIntArray = function (uniformName, array) {
  25136. this._valueCache[uniformName] = null;
  25137. this._engine.setIntArray(this.getUniform(uniformName), array);
  25138. return this;
  25139. };
  25140. Effect.prototype.setIntArray2 = function (uniformName, array) {
  25141. this._valueCache[uniformName] = null;
  25142. this._engine.setIntArray2(this.getUniform(uniformName), array);
  25143. return this;
  25144. };
  25145. Effect.prototype.setIntArray3 = function (uniformName, array) {
  25146. this._valueCache[uniformName] = null;
  25147. this._engine.setIntArray3(this.getUniform(uniformName), array);
  25148. return this;
  25149. };
  25150. Effect.prototype.setIntArray4 = function (uniformName, array) {
  25151. this._valueCache[uniformName] = null;
  25152. this._engine.setIntArray4(this.getUniform(uniformName), array);
  25153. return this;
  25154. };
  25155. Effect.prototype.setFloatArray = function (uniformName, array) {
  25156. this._valueCache[uniformName] = null;
  25157. this._engine.setFloatArray(this.getUniform(uniformName), array);
  25158. return this;
  25159. };
  25160. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  25161. this._valueCache[uniformName] = null;
  25162. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  25163. return this;
  25164. };
  25165. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  25166. this._valueCache[uniformName] = null;
  25167. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  25168. return this;
  25169. };
  25170. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  25171. this._valueCache[uniformName] = null;
  25172. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  25173. return this;
  25174. };
  25175. Effect.prototype.setArray = function (uniformName, array) {
  25176. this._valueCache[uniformName] = null;
  25177. this._engine.setArray(this.getUniform(uniformName), array);
  25178. return this;
  25179. };
  25180. Effect.prototype.setArray2 = function (uniformName, array) {
  25181. this._valueCache[uniformName] = null;
  25182. this._engine.setArray2(this.getUniform(uniformName), array);
  25183. return this;
  25184. };
  25185. Effect.prototype.setArray3 = function (uniformName, array) {
  25186. this._valueCache[uniformName] = null;
  25187. this._engine.setArray3(this.getUniform(uniformName), array);
  25188. return this;
  25189. };
  25190. Effect.prototype.setArray4 = function (uniformName, array) {
  25191. this._valueCache[uniformName] = null;
  25192. this._engine.setArray4(this.getUniform(uniformName), array);
  25193. return this;
  25194. };
  25195. Effect.prototype.setMatrices = function (uniformName, matrices) {
  25196. if (!matrices) {
  25197. return;
  25198. }
  25199. this._valueCache[uniformName] = null;
  25200. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  25201. return this;
  25202. };
  25203. Effect.prototype.setMatrix = function (uniformName, matrix) {
  25204. if (this._cacheMatrix(uniformName, matrix)) {
  25205. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  25206. }
  25207. return this;
  25208. };
  25209. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  25210. this._valueCache[uniformName] = null;
  25211. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  25212. return this;
  25213. };
  25214. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  25215. this._valueCache[uniformName] = null;
  25216. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  25217. return this;
  25218. };
  25219. Effect.prototype.setFloat = function (uniformName, value) {
  25220. var cache = this._valueCache[uniformName];
  25221. if (cache !== undefined && cache === value)
  25222. return this;
  25223. this._valueCache[uniformName] = value;
  25224. this._engine.setFloat(this.getUniform(uniformName), value);
  25225. return this;
  25226. };
  25227. Effect.prototype.setBool = function (uniformName, bool) {
  25228. var cache = this._valueCache[uniformName];
  25229. if (cache !== undefined && cache === bool)
  25230. return this;
  25231. this._valueCache[uniformName] = bool;
  25232. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  25233. return this;
  25234. };
  25235. Effect.prototype.setVector2 = function (uniformName, vector2) {
  25236. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  25237. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  25238. }
  25239. return this;
  25240. };
  25241. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  25242. if (this._cacheFloat2(uniformName, x, y)) {
  25243. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  25244. }
  25245. return this;
  25246. };
  25247. Effect.prototype.setVector3 = function (uniformName, vector3) {
  25248. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  25249. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  25250. }
  25251. return this;
  25252. };
  25253. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  25254. if (this._cacheFloat3(uniformName, x, y, z)) {
  25255. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  25256. }
  25257. return this;
  25258. };
  25259. Effect.prototype.setVector4 = function (uniformName, vector4) {
  25260. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  25261. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  25262. }
  25263. return this;
  25264. };
  25265. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  25266. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  25267. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  25268. }
  25269. return this;
  25270. };
  25271. Effect.prototype.setColor3 = function (uniformName, color3) {
  25272. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  25273. this._engine.setColor3(this.getUniform(uniformName), color3);
  25274. }
  25275. return this;
  25276. };
  25277. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  25278. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  25279. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  25280. }
  25281. return this;
  25282. };
  25283. Effect.ResetCache = function () {
  25284. Effect._baseCache = {};
  25285. };
  25286. Effect._uniqueIdSeed = 0;
  25287. Effect._baseCache = {};
  25288. // Statics
  25289. Effect.ShadersStore = {};
  25290. Effect.IncludesShadersStore = {};
  25291. return Effect;
  25292. }());
  25293. BABYLON.Effect = Effect;
  25294. })(BABYLON || (BABYLON = {}));
  25295. //# sourceMappingURL=babylon.effect.js.map
  25296. var BABYLON;
  25297. (function (BABYLON) {
  25298. var MaterialHelper = (function () {
  25299. function MaterialHelper() {
  25300. }
  25301. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  25302. defines._needUVs = true;
  25303. defines[key] = true;
  25304. if (texture.getTextureMatrix().isIdentity(true)) {
  25305. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  25306. if (texture.coordinatesIndex === 0) {
  25307. defines["MAINUV1"] = true;
  25308. }
  25309. else {
  25310. defines["MAINUV2"] = true;
  25311. }
  25312. }
  25313. else {
  25314. defines[key + "DIRECTUV"] = 0;
  25315. }
  25316. };
  25317. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  25318. var matrix = texture.getTextureMatrix();
  25319. if (!matrix.isIdentity(true)) {
  25320. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  25321. }
  25322. };
  25323. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  25324. if (defines._areMiscDirty) {
  25325. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  25326. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  25327. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  25328. }
  25329. };
  25330. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  25331. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  25332. var changed = false;
  25333. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  25334. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  25335. changed = true;
  25336. }
  25337. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  25338. defines["ALPHATEST"] = !defines["ALPHATEST"];
  25339. changed = true;
  25340. }
  25341. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  25342. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  25343. changed = true;
  25344. }
  25345. if (defines["INSTANCES"] !== useInstances) {
  25346. defines["INSTANCES"] = useInstances;
  25347. changed = true;
  25348. }
  25349. if (changed) {
  25350. defines.markAsUnprocessed();
  25351. }
  25352. };
  25353. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  25354. if (useMorphTargets === void 0) { useMorphTargets = false; }
  25355. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  25356. return false;
  25357. }
  25358. defines._normals = defines._needNormals;
  25359. defines._uvs = defines._needUVs;
  25360. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  25361. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25362. defines["TANGENT"] = true;
  25363. }
  25364. if (defines._needUVs) {
  25365. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  25366. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  25367. }
  25368. else {
  25369. defines["UV1"] = false;
  25370. defines["UV2"] = false;
  25371. }
  25372. if (useVertexColor) {
  25373. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  25374. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  25375. }
  25376. if (useBones) {
  25377. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  25378. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  25379. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  25380. }
  25381. else {
  25382. defines["NUM_BONE_INFLUENCERS"] = 0;
  25383. defines["BonesPerMesh"] = 0;
  25384. }
  25385. }
  25386. if (useMorphTargets) {
  25387. if (mesh.morphTargetManager) {
  25388. var manager = mesh.morphTargetManager;
  25389. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  25390. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  25391. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  25392. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  25393. }
  25394. else {
  25395. defines["MORPHTARGETS_TANGENT"] = false;
  25396. defines["MORPHTARGETS_NORMAL"] = false;
  25397. defines["MORPHTARGETS"] = false;
  25398. defines["NUM_MORPH_INFLUENCERS"] = 0;
  25399. }
  25400. }
  25401. return true;
  25402. };
  25403. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  25404. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25405. if (disableLighting === void 0) { disableLighting = false; }
  25406. if (!defines._areLightsDirty) {
  25407. return defines._needNormals;
  25408. }
  25409. var lightIndex = 0;
  25410. var needNormals = false;
  25411. var needRebuild = false;
  25412. var lightmapMode = false;
  25413. var shadowEnabled = false;
  25414. var specularEnabled = false;
  25415. if (scene.lightsEnabled && !disableLighting) {
  25416. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  25417. var light = _a[_i];
  25418. needNormals = true;
  25419. if (defines["LIGHT" + lightIndex] === undefined) {
  25420. needRebuild = true;
  25421. }
  25422. defines["LIGHT" + lightIndex] = true;
  25423. defines["SPOTLIGHT" + lightIndex] = false;
  25424. defines["HEMILIGHT" + lightIndex] = false;
  25425. defines["POINTLIGHT" + lightIndex] = false;
  25426. defines["DIRLIGHT" + lightIndex] = false;
  25427. var type;
  25428. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  25429. type = "SPOTLIGHT" + lightIndex;
  25430. }
  25431. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  25432. type = "HEMILIGHT" + lightIndex;
  25433. }
  25434. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  25435. type = "POINTLIGHT" + lightIndex;
  25436. }
  25437. else {
  25438. type = "DIRLIGHT" + lightIndex;
  25439. }
  25440. defines[type] = true;
  25441. // Specular
  25442. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  25443. specularEnabled = true;
  25444. }
  25445. // Shadows
  25446. defines["SHADOW" + lightIndex] = false;
  25447. defines["SHADOWPCF" + lightIndex] = false;
  25448. defines["SHADOWESM" + lightIndex] = false;
  25449. defines["SHADOWCUBE" + lightIndex] = false;
  25450. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  25451. var shadowGenerator = light.getShadowGenerator();
  25452. if (shadowGenerator) {
  25453. shadowEnabled = true;
  25454. shadowGenerator.prepareDefines(defines, lightIndex);
  25455. }
  25456. }
  25457. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  25458. lightmapMode = true;
  25459. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  25460. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  25461. }
  25462. else {
  25463. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  25464. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  25465. }
  25466. lightIndex++;
  25467. if (lightIndex === maxSimultaneousLights)
  25468. break;
  25469. }
  25470. }
  25471. defines["SPECULARTERM"] = specularEnabled;
  25472. defines["SHADOWS"] = shadowEnabled;
  25473. // Resetting all other lights if any
  25474. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  25475. if (defines["LIGHT" + index] !== undefined) {
  25476. defines["LIGHT" + index] = false;
  25477. defines["HEMILIGHT" + lightIndex] = false;
  25478. defines["POINTLIGHT" + lightIndex] = false;
  25479. defines["DIRLIGHT" + lightIndex] = false;
  25480. defines["SPOTLIGHT" + lightIndex] = false;
  25481. defines["SHADOW" + lightIndex] = false;
  25482. }
  25483. }
  25484. var caps = scene.getEngine().getCaps();
  25485. if (defines["SHADOWFLOAT"] === undefined) {
  25486. needRebuild = true;
  25487. }
  25488. defines["SHADOWFLOAT"] = shadowEnabled &&
  25489. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  25490. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  25491. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  25492. if (needRebuild) {
  25493. defines.rebuild();
  25494. }
  25495. return needNormals;
  25496. };
  25497. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  25498. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25499. var uniformsList, uniformBuffersList, samplersList, defines;
  25500. if (uniformsListOrOptions.uniformsNames) {
  25501. var options = uniformsListOrOptions;
  25502. uniformsList = options.uniformsNames;
  25503. uniformBuffersList = options.uniformBuffersNames;
  25504. samplersList = options.samplers;
  25505. defines = options.defines;
  25506. maxSimultaneousLights = options.maxSimultaneousLights;
  25507. }
  25508. else {
  25509. uniformsList = uniformsListOrOptions;
  25510. }
  25511. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25512. if (!defines["LIGHT" + lightIndex]) {
  25513. break;
  25514. }
  25515. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  25516. if (uniformBuffersList) {
  25517. uniformBuffersList.push("Light" + lightIndex);
  25518. }
  25519. samplersList.push("shadowSampler" + lightIndex);
  25520. }
  25521. if (defines["NUM_MORPH_INFLUENCERS"]) {
  25522. uniformsList.push("morphTargetInfluences");
  25523. }
  25524. };
  25525. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  25526. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25527. if (!defines["SHADOWS"]) {
  25528. return;
  25529. }
  25530. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25531. if (!defines["LIGHT" + lightIndex]) {
  25532. break;
  25533. }
  25534. if (lightIndex > 0) {
  25535. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  25536. }
  25537. if (defines["SHADOW" + lightIndex]) {
  25538. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  25539. }
  25540. if (defines["SHADOWPCF" + lightIndex]) {
  25541. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  25542. }
  25543. if (defines["SHADOWESM" + lightIndex]) {
  25544. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  25545. }
  25546. }
  25547. };
  25548. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  25549. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  25550. if (influencers > 0) {
  25551. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  25552. var manager = mesh.morphTargetManager;
  25553. var normal = manager.supportsNormals && defines["NORMAL"];
  25554. var tangent = manager.supportsTangents && defines["TANGENT"];
  25555. for (var index = 0; index < influencers; index++) {
  25556. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  25557. if (normal) {
  25558. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  25559. }
  25560. if (tangent) {
  25561. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  25562. }
  25563. if (attribs.length > maxAttributesCount) {
  25564. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  25565. }
  25566. }
  25567. }
  25568. };
  25569. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  25570. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  25571. fallbacks.addCPUSkinningFallback(0, mesh);
  25572. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25573. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25574. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  25575. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  25576. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  25577. }
  25578. }
  25579. };
  25580. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  25581. if (defines["INSTANCES"]) {
  25582. attribs.push("world0");
  25583. attribs.push("world1");
  25584. attribs.push("world2");
  25585. attribs.push("world3");
  25586. }
  25587. };
  25588. // Bindings
  25589. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  25590. if (light.shadowEnabled && mesh.receiveShadows) {
  25591. var shadowGenerator = light.getShadowGenerator();
  25592. if (shadowGenerator) {
  25593. shadowGenerator.bindShadowLight(lightIndex, effect);
  25594. }
  25595. }
  25596. };
  25597. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25598. light.transferToEffect(effect, lightIndex + "");
  25599. };
  25600. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  25601. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25602. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  25603. var lightIndex = 0;
  25604. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  25605. var light = _a[_i];
  25606. var scaledIntensity = light.getScaledIntensity();
  25607. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  25608. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25609. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  25610. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  25611. if (defines["SPECULARTERM"]) {
  25612. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  25613. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  25614. }
  25615. // Shadows
  25616. if (scene.shadowsEnabled) {
  25617. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  25618. }
  25619. light._uniformBuffer.update();
  25620. lightIndex++;
  25621. if (lightIndex === maxSimultaneousLights)
  25622. break;
  25623. }
  25624. };
  25625. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25626. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25627. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25628. effect.setColor3("vFogColor", scene.fogColor);
  25629. }
  25630. };
  25631. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25632. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25633. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25634. if (matrices) {
  25635. effect.setMatrices("mBones", matrices);
  25636. }
  25637. }
  25638. };
  25639. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  25640. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  25641. return;
  25642. }
  25643. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  25644. };
  25645. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25646. if (defines["LOGARITHMICDEPTH"]) {
  25647. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25648. }
  25649. };
  25650. MaterialHelper.BindClipPlane = function (effect, scene) {
  25651. if (scene.clipPlane) {
  25652. var clipPlane = scene.clipPlane;
  25653. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25654. }
  25655. };
  25656. return MaterialHelper;
  25657. }());
  25658. BABYLON.MaterialHelper = MaterialHelper;
  25659. })(BABYLON || (BABYLON = {}));
  25660. //# sourceMappingURL=babylon.materialHelper.js.map
  25661. var BABYLON;
  25662. (function (BABYLON) {
  25663. var MaterialDefines = (function () {
  25664. function MaterialDefines() {
  25665. this._isDirty = true;
  25666. this._areLightsDirty = true;
  25667. this._areAttributesDirty = true;
  25668. this._areTexturesDirty = true;
  25669. this._areFresnelDirty = true;
  25670. this._areMiscDirty = true;
  25671. this._areImageProcessingDirty = true;
  25672. this._normals = false;
  25673. this._uvs = false;
  25674. this._needNormals = false;
  25675. this._needUVs = false;
  25676. }
  25677. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  25678. get: function () {
  25679. return this._isDirty;
  25680. },
  25681. enumerable: true,
  25682. configurable: true
  25683. });
  25684. MaterialDefines.prototype.markAsProcessed = function () {
  25685. this._isDirty = false;
  25686. this._areAttributesDirty = false;
  25687. this._areTexturesDirty = false;
  25688. this._areFresnelDirty = false;
  25689. this._areLightsDirty = false;
  25690. this._areMiscDirty = false;
  25691. this._areImageProcessingDirty = false;
  25692. };
  25693. MaterialDefines.prototype.markAsUnprocessed = function () {
  25694. this._isDirty = true;
  25695. };
  25696. MaterialDefines.prototype.markAllAsDirty = function () {
  25697. this._areTexturesDirty = true;
  25698. this._areAttributesDirty = true;
  25699. this._areLightsDirty = true;
  25700. this._areFresnelDirty = true;
  25701. this._areMiscDirty = true;
  25702. this._areImageProcessingDirty = true;
  25703. this._isDirty = true;
  25704. };
  25705. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  25706. this._areImageProcessingDirty = true;
  25707. this._isDirty = true;
  25708. };
  25709. MaterialDefines.prototype.markAsLightDirty = function () {
  25710. this._areLightsDirty = true;
  25711. this._isDirty = true;
  25712. };
  25713. MaterialDefines.prototype.markAsAttributesDirty = function () {
  25714. this._areAttributesDirty = true;
  25715. this._isDirty = true;
  25716. };
  25717. MaterialDefines.prototype.markAsTexturesDirty = function () {
  25718. this._areTexturesDirty = true;
  25719. this._isDirty = true;
  25720. };
  25721. MaterialDefines.prototype.markAsFresnelDirty = function () {
  25722. this._areFresnelDirty = true;
  25723. this._isDirty = true;
  25724. };
  25725. MaterialDefines.prototype.markAsMiscDirty = function () {
  25726. this._areMiscDirty = true;
  25727. this._isDirty = true;
  25728. };
  25729. MaterialDefines.prototype.rebuild = function () {
  25730. if (this._keys) {
  25731. delete this._keys;
  25732. }
  25733. this._keys = [];
  25734. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  25735. var key = _a[_i];
  25736. if (key[0] === "_") {
  25737. continue;
  25738. }
  25739. this._keys.push(key);
  25740. }
  25741. };
  25742. MaterialDefines.prototype.isEqual = function (other) {
  25743. if (this._keys.length !== other._keys.length) {
  25744. return false;
  25745. }
  25746. for (var index = 0; index < this._keys.length; index++) {
  25747. var prop = this._keys[index];
  25748. if (this[prop] !== other[prop]) {
  25749. return false;
  25750. }
  25751. }
  25752. return true;
  25753. };
  25754. MaterialDefines.prototype.cloneTo = function (other) {
  25755. if (this._keys.length !== other._keys.length) {
  25756. other._keys = this._keys.slice(0);
  25757. }
  25758. for (var index = 0; index < this._keys.length; index++) {
  25759. var prop = this._keys[index];
  25760. other[prop] = this[prop];
  25761. }
  25762. };
  25763. MaterialDefines.prototype.reset = function () {
  25764. for (var index = 0; index < this._keys.length; index++) {
  25765. var prop = this._keys[index];
  25766. if (typeof (this[prop]) === "number") {
  25767. this[prop] = 0;
  25768. }
  25769. else {
  25770. this[prop] = false;
  25771. }
  25772. }
  25773. };
  25774. MaterialDefines.prototype.toString = function () {
  25775. var result = "";
  25776. for (var index = 0; index < this._keys.length; index++) {
  25777. var prop = this._keys[index];
  25778. var value = this[prop];
  25779. if (typeof (value) === "number") {
  25780. result += "#define " + prop + " " + this[prop] + "\n";
  25781. }
  25782. else if (value) {
  25783. result += "#define " + prop + "\n";
  25784. }
  25785. }
  25786. return result;
  25787. };
  25788. return MaterialDefines;
  25789. }());
  25790. BABYLON.MaterialDefines = MaterialDefines;
  25791. var Material = (function () {
  25792. function Material(name, scene, doNotAdd) {
  25793. this.checkReadyOnEveryCall = false;
  25794. this.checkReadyOnlyOnce = false;
  25795. this.state = "";
  25796. this.alpha = 1.0;
  25797. this._backFaceCulling = true;
  25798. this.doNotSerialize = false;
  25799. this.storeEffectOnSubMeshes = false;
  25800. /**
  25801. * An event triggered when the material is disposed.
  25802. * @type {BABYLON.Observable}
  25803. */
  25804. this.onDisposeObservable = new BABYLON.Observable();
  25805. /**
  25806. * An event triggered when the material is bound.
  25807. * @type {BABYLON.Observable}
  25808. */
  25809. this.onBindObservable = new BABYLON.Observable();
  25810. /**
  25811. * An event triggered when the material is unbound.
  25812. * @type {BABYLON.Observable}
  25813. */
  25814. this.onUnBindObservable = new BABYLON.Observable();
  25815. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25816. this._needDepthPrePass = false;
  25817. this.disableDepthWrite = false;
  25818. this.forceDepthWrite = false;
  25819. this.separateCullingPass = false;
  25820. this._fogEnabled = true;
  25821. this.pointSize = 1.0;
  25822. this.zOffset = 0;
  25823. this._wasPreviouslyReady = false;
  25824. this._fillMode = Material.TriangleFillMode;
  25825. this.name = name;
  25826. this.id = name || BABYLON.Tools.RandomId();
  25827. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25828. if (this._scene.useRightHandedSystem) {
  25829. this.sideOrientation = Material.ClockWiseSideOrientation;
  25830. }
  25831. else {
  25832. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25833. }
  25834. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  25835. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  25836. if (!doNotAdd) {
  25837. this._scene.materials.push(this);
  25838. }
  25839. }
  25840. Object.defineProperty(Material, "TriangleFillMode", {
  25841. get: function () {
  25842. return Material._TriangleFillMode;
  25843. },
  25844. enumerable: true,
  25845. configurable: true
  25846. });
  25847. Object.defineProperty(Material, "WireFrameFillMode", {
  25848. get: function () {
  25849. return Material._WireFrameFillMode;
  25850. },
  25851. enumerable: true,
  25852. configurable: true
  25853. });
  25854. Object.defineProperty(Material, "PointFillMode", {
  25855. get: function () {
  25856. return Material._PointFillMode;
  25857. },
  25858. enumerable: true,
  25859. configurable: true
  25860. });
  25861. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25862. get: function () {
  25863. return Material._ClockWiseSideOrientation;
  25864. },
  25865. enumerable: true,
  25866. configurable: true
  25867. });
  25868. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25869. get: function () {
  25870. return Material._CounterClockWiseSideOrientation;
  25871. },
  25872. enumerable: true,
  25873. configurable: true
  25874. });
  25875. Object.defineProperty(Material, "TextureDirtyFlag", {
  25876. get: function () {
  25877. return Material._TextureDirtyFlag;
  25878. },
  25879. enumerable: true,
  25880. configurable: true
  25881. });
  25882. Object.defineProperty(Material, "LightDirtyFlag", {
  25883. get: function () {
  25884. return Material._LightDirtyFlag;
  25885. },
  25886. enumerable: true,
  25887. configurable: true
  25888. });
  25889. Object.defineProperty(Material, "FresnelDirtyFlag", {
  25890. get: function () {
  25891. return Material._FresnelDirtyFlag;
  25892. },
  25893. enumerable: true,
  25894. configurable: true
  25895. });
  25896. Object.defineProperty(Material, "AttributesDirtyFlag", {
  25897. get: function () {
  25898. return Material._AttributesDirtyFlag;
  25899. },
  25900. enumerable: true,
  25901. configurable: true
  25902. });
  25903. Object.defineProperty(Material, "MiscDirtyFlag", {
  25904. get: function () {
  25905. return Material._MiscDirtyFlag;
  25906. },
  25907. enumerable: true,
  25908. configurable: true
  25909. });
  25910. Object.defineProperty(Material.prototype, "backFaceCulling", {
  25911. get: function () {
  25912. return this._backFaceCulling;
  25913. },
  25914. set: function (value) {
  25915. if (this._backFaceCulling === value) {
  25916. return;
  25917. }
  25918. this._backFaceCulling = value;
  25919. this.markAsDirty(Material.TextureDirtyFlag);
  25920. },
  25921. enumerable: true,
  25922. configurable: true
  25923. });
  25924. Object.defineProperty(Material.prototype, "onDispose", {
  25925. set: function (callback) {
  25926. if (this._onDisposeObserver) {
  25927. this.onDisposeObservable.remove(this._onDisposeObserver);
  25928. }
  25929. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25930. },
  25931. enumerable: true,
  25932. configurable: true
  25933. });
  25934. Object.defineProperty(Material.prototype, "onBind", {
  25935. set: function (callback) {
  25936. if (this._onBindObserver) {
  25937. this.onBindObservable.remove(this._onBindObserver);
  25938. }
  25939. this._onBindObserver = this.onBindObservable.add(callback);
  25940. },
  25941. enumerable: true,
  25942. configurable: true
  25943. });
  25944. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  25945. get: function () {
  25946. return this._needDepthPrePass;
  25947. },
  25948. set: function (value) {
  25949. if (this._needDepthPrePass === value) {
  25950. return;
  25951. }
  25952. this._needDepthPrePass = value;
  25953. if (this._needDepthPrePass) {
  25954. this.checkReadyOnEveryCall = true;
  25955. }
  25956. },
  25957. enumerable: true,
  25958. configurable: true
  25959. });
  25960. Object.defineProperty(Material.prototype, "fogEnabled", {
  25961. get: function () {
  25962. return this._fogEnabled;
  25963. },
  25964. set: function (value) {
  25965. if (this._fogEnabled === value) {
  25966. return;
  25967. }
  25968. this._fogEnabled = value;
  25969. this.markAsDirty(Material.MiscDirtyFlag);
  25970. },
  25971. enumerable: true,
  25972. configurable: true
  25973. });
  25974. Object.defineProperty(Material.prototype, "wireframe", {
  25975. get: function () {
  25976. return this._fillMode === Material.WireFrameFillMode;
  25977. },
  25978. set: function (value) {
  25979. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25980. },
  25981. enumerable: true,
  25982. configurable: true
  25983. });
  25984. Object.defineProperty(Material.prototype, "pointsCloud", {
  25985. get: function () {
  25986. return this._fillMode === Material.PointFillMode;
  25987. },
  25988. set: function (value) {
  25989. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  25990. },
  25991. enumerable: true,
  25992. configurable: true
  25993. });
  25994. Object.defineProperty(Material.prototype, "fillMode", {
  25995. get: function () {
  25996. return this._fillMode;
  25997. },
  25998. set: function (value) {
  25999. if (this._fillMode === value) {
  26000. return;
  26001. }
  26002. this._fillMode = value;
  26003. this.markAsDirty(Material.MiscDirtyFlag);
  26004. },
  26005. enumerable: true,
  26006. configurable: true
  26007. });
  26008. /**
  26009. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26010. * subclasses should override adding information pertainent to themselves
  26011. */
  26012. Material.prototype.toString = function (fullDetails) {
  26013. var ret = "Name: " + this.name;
  26014. if (fullDetails) {
  26015. }
  26016. return ret;
  26017. };
  26018. /**
  26019. * Child classes can use it to update shaders
  26020. */
  26021. Material.prototype.getClassName = function () {
  26022. return "Material";
  26023. };
  26024. Object.defineProperty(Material.prototype, "isFrozen", {
  26025. get: function () {
  26026. return this.checkReadyOnlyOnce;
  26027. },
  26028. enumerable: true,
  26029. configurable: true
  26030. });
  26031. Material.prototype.freeze = function () {
  26032. this.checkReadyOnlyOnce = true;
  26033. };
  26034. Material.prototype.unfreeze = function () {
  26035. this.checkReadyOnlyOnce = false;
  26036. };
  26037. Material.prototype.isReady = function (mesh, useInstances) {
  26038. return true;
  26039. };
  26040. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  26041. return false;
  26042. };
  26043. Material.prototype.getEffect = function () {
  26044. return this._effect;
  26045. };
  26046. Material.prototype.getScene = function () {
  26047. return this._scene;
  26048. };
  26049. Material.prototype.needAlphaBlending = function () {
  26050. return (this.alpha < 1.0);
  26051. };
  26052. Material.prototype.needAlphaTesting = function () {
  26053. return false;
  26054. };
  26055. Material.prototype.getAlphaTestTexture = function () {
  26056. return null;
  26057. };
  26058. Material.prototype.markDirty = function () {
  26059. this._wasPreviouslyReady = false;
  26060. };
  26061. Material.prototype._preBind = function (effect, overrideOrientation) {
  26062. var engine = this._scene.getEngine();
  26063. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  26064. var reverse = orientation === Material.ClockWiseSideOrientation;
  26065. engine.enableEffect(effect ? effect : this._effect);
  26066. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  26067. return reverse;
  26068. };
  26069. Material.prototype.bind = function (world, mesh) {
  26070. };
  26071. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  26072. };
  26073. Material.prototype.bindOnlyWorldMatrix = function (world) {
  26074. };
  26075. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  26076. sceneUbo.bindToEffect(effect, "Scene");
  26077. };
  26078. Material.prototype.bindView = function (effect) {
  26079. if (!this._useUBO) {
  26080. effect.setMatrix("view", this.getScene().getViewMatrix());
  26081. }
  26082. else {
  26083. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  26084. }
  26085. };
  26086. Material.prototype.bindViewProjection = function (effect) {
  26087. if (!this._useUBO) {
  26088. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  26089. }
  26090. else {
  26091. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  26092. }
  26093. };
  26094. Material.prototype._afterBind = function (mesh) {
  26095. this._scene._cachedMaterial = this;
  26096. if (mesh) {
  26097. this._scene._cachedVisibility = mesh.visibility;
  26098. }
  26099. else {
  26100. this._scene._cachedVisibility = 1;
  26101. }
  26102. this.onBindObservable.notifyObservers(mesh);
  26103. if (this.disableDepthWrite) {
  26104. var engine = this._scene.getEngine();
  26105. this._cachedDepthWriteState = engine.getDepthWrite();
  26106. engine.setDepthWrite(false);
  26107. }
  26108. };
  26109. Material.prototype.unbind = function () {
  26110. this.onUnBindObservable.notifyObservers(this);
  26111. if (this.disableDepthWrite) {
  26112. var engine = this._scene.getEngine();
  26113. engine.setDepthWrite(this._cachedDepthWriteState);
  26114. }
  26115. };
  26116. Material.prototype.getActiveTextures = function () {
  26117. return [];
  26118. };
  26119. Material.prototype.hasTexture = function (texture) {
  26120. return false;
  26121. };
  26122. Material.prototype.clone = function (name) {
  26123. return null;
  26124. };
  26125. Material.prototype.getBindedMeshes = function () {
  26126. var result = new Array();
  26127. for (var index = 0; index < this._scene.meshes.length; index++) {
  26128. var mesh = this._scene.meshes[index];
  26129. if (mesh.material === this) {
  26130. result.push(mesh);
  26131. }
  26132. }
  26133. return result;
  26134. };
  26135. /**
  26136. * Force shader compilation including textures ready check
  26137. */
  26138. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  26139. var _this = this;
  26140. var subMesh = new BABYLON.BaseSubMesh();
  26141. var scene = this.getScene();
  26142. var engine = scene.getEngine();
  26143. var checkReady = function () {
  26144. if (!_this._scene || !_this._scene.getEngine()) {
  26145. return;
  26146. }
  26147. if (subMesh._materialDefines) {
  26148. subMesh._materialDefines._renderId = -1;
  26149. }
  26150. var alphaTestState = engine.getAlphaTesting();
  26151. var clipPlaneState = scene.clipPlane;
  26152. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  26153. if (options && options.clipPlane) {
  26154. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  26155. }
  26156. if (_this.storeEffectOnSubMeshes) {
  26157. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  26158. if (onCompiled) {
  26159. onCompiled(_this);
  26160. }
  26161. }
  26162. else {
  26163. setTimeout(checkReady, 16);
  26164. }
  26165. }
  26166. else {
  26167. if (_this.isReady(mesh)) {
  26168. if (onCompiled) {
  26169. onCompiled(_this);
  26170. }
  26171. }
  26172. else {
  26173. setTimeout(checkReady, 16);
  26174. }
  26175. }
  26176. engine.setAlphaTesting(alphaTestState);
  26177. if (options && options.clipPlane) {
  26178. scene.clipPlane = clipPlaneState;
  26179. }
  26180. };
  26181. checkReady();
  26182. };
  26183. Material.prototype.markAsDirty = function (flag) {
  26184. if (flag & Material.TextureDirtyFlag) {
  26185. this._markAllSubMeshesAsTexturesDirty();
  26186. }
  26187. if (flag & Material.LightDirtyFlag) {
  26188. this._markAllSubMeshesAsLightsDirty();
  26189. }
  26190. if (flag & Material.FresnelDirtyFlag) {
  26191. this._markAllSubMeshesAsFresnelDirty();
  26192. }
  26193. if (flag & Material.AttributesDirtyFlag) {
  26194. this._markAllSubMeshesAsAttributesDirty();
  26195. }
  26196. if (flag & Material.MiscDirtyFlag) {
  26197. this._markAllSubMeshesAsMiscDirty();
  26198. }
  26199. this.getScene().resetCachedMaterial();
  26200. };
  26201. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  26202. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  26203. var mesh = _a[_i];
  26204. if (!mesh.subMeshes) {
  26205. continue;
  26206. }
  26207. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  26208. var subMesh = _c[_b];
  26209. if (subMesh.getMaterial() !== this) {
  26210. continue;
  26211. }
  26212. if (!subMesh._materialDefines) {
  26213. continue;
  26214. }
  26215. func(subMesh._materialDefines);
  26216. }
  26217. }
  26218. };
  26219. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  26220. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  26221. };
  26222. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  26223. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  26224. };
  26225. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  26226. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  26227. };
  26228. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  26229. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  26230. };
  26231. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  26232. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  26233. };
  26234. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  26235. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  26236. };
  26237. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26238. // Animations
  26239. this.getScene().stopAnimation(this);
  26240. // Remove from scene
  26241. var index = this._scene.materials.indexOf(this);
  26242. if (index >= 0) {
  26243. this._scene.materials.splice(index, 1);
  26244. }
  26245. // Remove from meshes
  26246. for (index = 0; index < this._scene.meshes.length; index++) {
  26247. var mesh = this._scene.meshes[index];
  26248. if (mesh.material === this) {
  26249. mesh.material = null;
  26250. if (mesh.geometry) {
  26251. var geometry = mesh.geometry;
  26252. if (this.storeEffectOnSubMeshes) {
  26253. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  26254. var subMesh = _a[_i];
  26255. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  26256. }
  26257. }
  26258. else {
  26259. geometry._releaseVertexArrayObject(this._effect);
  26260. }
  26261. }
  26262. }
  26263. }
  26264. this._uniformBuffer.dispose();
  26265. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  26266. if (forceDisposeEffect && this._effect) {
  26267. if (this.storeEffectOnSubMeshes) {
  26268. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  26269. var subMesh = _c[_b];
  26270. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  26271. }
  26272. }
  26273. else {
  26274. this._scene.getEngine()._releaseEffect(this._effect);
  26275. }
  26276. this._effect = null;
  26277. }
  26278. // Callback
  26279. this.onDisposeObservable.notifyObservers(this);
  26280. this.onDisposeObservable.clear();
  26281. this.onBindObservable.clear();
  26282. this.onUnBindObservable.clear();
  26283. };
  26284. Material.prototype.serialize = function () {
  26285. return BABYLON.SerializationHelper.Serialize(this);
  26286. };
  26287. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  26288. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  26289. multiMaterial.id = parsedMultiMaterial.id;
  26290. if (BABYLON.Tags) {
  26291. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  26292. }
  26293. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  26294. var subMatId = parsedMultiMaterial.materials[matIndex];
  26295. if (subMatId) {
  26296. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  26297. }
  26298. else {
  26299. multiMaterial.subMaterials.push(null);
  26300. }
  26301. }
  26302. return multiMaterial;
  26303. };
  26304. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  26305. if (!parsedMaterial.customType) {
  26306. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  26307. }
  26308. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  26309. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  26310. if (!BABYLON.LegacyPBRMaterial) {
  26311. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  26312. return;
  26313. }
  26314. }
  26315. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  26316. return materialType.Parse(parsedMaterial, scene, rootUrl);
  26317. ;
  26318. };
  26319. Material._TriangleFillMode = 0;
  26320. Material._WireFrameFillMode = 1;
  26321. Material._PointFillMode = 2;
  26322. Material._ClockWiseSideOrientation = 0;
  26323. Material._CounterClockWiseSideOrientation = 1;
  26324. Material._TextureDirtyFlag = 1;
  26325. Material._LightDirtyFlag = 2;
  26326. Material._FresnelDirtyFlag = 4;
  26327. Material._AttributesDirtyFlag = 8;
  26328. Material._MiscDirtyFlag = 16;
  26329. __decorate([
  26330. BABYLON.serialize()
  26331. ], Material.prototype, "id", void 0);
  26332. __decorate([
  26333. BABYLON.serialize()
  26334. ], Material.prototype, "name", void 0);
  26335. __decorate([
  26336. BABYLON.serialize()
  26337. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  26338. __decorate([
  26339. BABYLON.serialize()
  26340. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  26341. __decorate([
  26342. BABYLON.serialize()
  26343. ], Material.prototype, "state", void 0);
  26344. __decorate([
  26345. BABYLON.serialize()
  26346. ], Material.prototype, "alpha", void 0);
  26347. __decorate([
  26348. BABYLON.serialize("backFaceCulling")
  26349. ], Material.prototype, "_backFaceCulling", void 0);
  26350. __decorate([
  26351. BABYLON.serialize()
  26352. ], Material.prototype, "sideOrientation", void 0);
  26353. __decorate([
  26354. BABYLON.serialize()
  26355. ], Material.prototype, "alphaMode", void 0);
  26356. __decorate([
  26357. BABYLON.serialize()
  26358. ], Material.prototype, "_needDepthPrePass", void 0);
  26359. __decorate([
  26360. BABYLON.serialize()
  26361. ], Material.prototype, "disableDepthWrite", void 0);
  26362. __decorate([
  26363. BABYLON.serialize()
  26364. ], Material.prototype, "forceDepthWrite", void 0);
  26365. __decorate([
  26366. BABYLON.serialize()
  26367. ], Material.prototype, "separateCullingPass", void 0);
  26368. __decorate([
  26369. BABYLON.serialize("fogEnabled")
  26370. ], Material.prototype, "_fogEnabled", void 0);
  26371. __decorate([
  26372. BABYLON.serialize()
  26373. ], Material.prototype, "pointSize", void 0);
  26374. __decorate([
  26375. BABYLON.serialize()
  26376. ], Material.prototype, "zOffset", void 0);
  26377. __decorate([
  26378. BABYLON.serialize()
  26379. ], Material.prototype, "wireframe", null);
  26380. __decorate([
  26381. BABYLON.serialize()
  26382. ], Material.prototype, "pointsCloud", null);
  26383. __decorate([
  26384. BABYLON.serialize()
  26385. ], Material.prototype, "fillMode", null);
  26386. return Material;
  26387. }());
  26388. BABYLON.Material = Material;
  26389. })(BABYLON || (BABYLON = {}));
  26390. //# sourceMappingURL=babylon.material.js.map
  26391. var BABYLON;
  26392. (function (BABYLON) {
  26393. var UniformBuffer = (function () {
  26394. /**
  26395. * Uniform buffer objects.
  26396. *
  26397. * Handles blocks of uniform on the GPU.
  26398. *
  26399. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  26400. *
  26401. * For more information, please refer to :
  26402. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  26403. */
  26404. function UniformBuffer(engine, data, dynamic) {
  26405. this._engine = engine;
  26406. this._noUBO = !engine.supportsUniformBuffers;
  26407. this._dynamic = dynamic;
  26408. this._data = data || [];
  26409. this._uniformLocations = {};
  26410. this._uniformSizes = {};
  26411. this._uniformLocationPointer = 0;
  26412. this._needSync = false;
  26413. if (this._noUBO) {
  26414. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  26415. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  26416. this.updateFloat = this._updateFloatForEffect;
  26417. this.updateFloat2 = this._updateFloat2ForEffect;
  26418. this.updateFloat3 = this._updateFloat3ForEffect;
  26419. this.updateFloat4 = this._updateFloat4ForEffect;
  26420. this.updateMatrix = this._updateMatrixForEffect;
  26421. this.updateVector3 = this._updateVector3ForEffect;
  26422. this.updateVector4 = this._updateVector4ForEffect;
  26423. this.updateColor3 = this._updateColor3ForEffect;
  26424. this.updateColor4 = this._updateColor4ForEffect;
  26425. }
  26426. else {
  26427. this._engine._uniformBuffers.push(this);
  26428. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  26429. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  26430. this.updateFloat = this._updateFloatForUniform;
  26431. this.updateFloat2 = this._updateFloat2ForUniform;
  26432. this.updateFloat3 = this._updateFloat3ForUniform;
  26433. this.updateFloat4 = this._updateFloat4ForUniform;
  26434. this.updateMatrix = this._updateMatrixForUniform;
  26435. this.updateVector3 = this._updateVector3ForUniform;
  26436. this.updateVector4 = this._updateVector4ForUniform;
  26437. this.updateColor3 = this._updateColor3ForUniform;
  26438. this.updateColor4 = this._updateColor4ForUniform;
  26439. }
  26440. }
  26441. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  26442. // Properties
  26443. /**
  26444. * Indicates if the buffer is using the WebGL2 UBO implementation,
  26445. * or just falling back on setUniformXXX calls.
  26446. */
  26447. get: function () {
  26448. return !this._noUBO;
  26449. },
  26450. enumerable: true,
  26451. configurable: true
  26452. });
  26453. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  26454. /**
  26455. * Indicates if the WebGL underlying uniform buffer is in sync
  26456. * with the javascript cache data.
  26457. */
  26458. get: function () {
  26459. return !this._needSync;
  26460. },
  26461. enumerable: true,
  26462. configurable: true
  26463. });
  26464. /**
  26465. * Indicates if the WebGL underlying uniform buffer is dynamic.
  26466. * Also, a dynamic UniformBuffer will disable cache verification and always
  26467. * update the underlying WebGL uniform buffer to the GPU.
  26468. */
  26469. UniformBuffer.prototype.isDynamic = function () {
  26470. return this._dynamic;
  26471. };
  26472. /**
  26473. * The data cache on JS side.
  26474. */
  26475. UniformBuffer.prototype.getData = function () {
  26476. return this._bufferData;
  26477. };
  26478. /**
  26479. * The underlying WebGL Uniform buffer.
  26480. */
  26481. UniformBuffer.prototype.getBuffer = function () {
  26482. return this._buffer;
  26483. };
  26484. /**
  26485. * std140 layout specifies how to align data within an UBO structure.
  26486. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  26487. * for specs.
  26488. */
  26489. UniformBuffer.prototype._fillAlignment = function (size) {
  26490. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  26491. // and 4x4 matrices
  26492. // TODO : change if other types are used
  26493. var alignment;
  26494. if (size <= 2) {
  26495. alignment = size;
  26496. }
  26497. else {
  26498. alignment = 4;
  26499. }
  26500. if ((this._uniformLocationPointer % alignment) !== 0) {
  26501. var oldPointer = this._uniformLocationPointer;
  26502. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  26503. var diff = this._uniformLocationPointer - oldPointer;
  26504. for (var i = 0; i < diff; i++) {
  26505. this._data.push(0);
  26506. }
  26507. }
  26508. };
  26509. /**
  26510. * Adds an uniform in the buffer.
  26511. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  26512. * for the layout to be correct !
  26513. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26514. * @param {number|number[]} size Data size, or data directly.
  26515. */
  26516. UniformBuffer.prototype.addUniform = function (name, size) {
  26517. if (this._noUBO) {
  26518. return;
  26519. }
  26520. if (this._uniformLocations[name] !== undefined) {
  26521. // Already existing uniform
  26522. return;
  26523. }
  26524. // This function must be called in the order of the shader layout !
  26525. // size can be the size of the uniform, or data directly
  26526. var data;
  26527. if (size instanceof Array) {
  26528. data = size;
  26529. size = data.length;
  26530. }
  26531. else {
  26532. size = size;
  26533. data = [];
  26534. // Fill with zeros
  26535. for (var i = 0; i < size; i++) {
  26536. data.push(0);
  26537. }
  26538. }
  26539. this._fillAlignment(size);
  26540. this._uniformSizes[name] = size;
  26541. this._uniformLocations[name] = this._uniformLocationPointer;
  26542. this._uniformLocationPointer += size;
  26543. for (var i = 0; i < size; i++) {
  26544. this._data.push(data[i]);
  26545. }
  26546. this._needSync = true;
  26547. };
  26548. /**
  26549. * Wrapper for addUniform.
  26550. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26551. * @param {Matrix} mat A 4x4 matrix.
  26552. */
  26553. UniformBuffer.prototype.addMatrix = function (name, mat) {
  26554. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  26555. };
  26556. /**
  26557. * Wrapper for addUniform.
  26558. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26559. * @param {number} x
  26560. * @param {number} y
  26561. */
  26562. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  26563. var temp = [x, y];
  26564. this.addUniform(name, temp);
  26565. };
  26566. /**
  26567. * Wrapper for addUniform.
  26568. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26569. * @param {number} x
  26570. * @param {number} y
  26571. * @param {number} z
  26572. */
  26573. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  26574. var temp = [x, y, z];
  26575. this.addUniform(name, temp);
  26576. };
  26577. /**
  26578. * Wrapper for addUniform.
  26579. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26580. * @param {Color3} color
  26581. */
  26582. UniformBuffer.prototype.addColor3 = function (name, color) {
  26583. var temp = new Array();
  26584. color.toArray(temp);
  26585. this.addUniform(name, temp);
  26586. };
  26587. /**
  26588. * Wrapper for addUniform.
  26589. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26590. * @param {Color3} color
  26591. * @param {number} alpha
  26592. */
  26593. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  26594. var temp = new Array();
  26595. color.toArray(temp);
  26596. temp.push(alpha);
  26597. this.addUniform(name, temp);
  26598. };
  26599. /**
  26600. * Wrapper for addUniform.
  26601. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26602. * @param {Vector3} vector
  26603. */
  26604. UniformBuffer.prototype.addVector3 = function (name, vector) {
  26605. var temp = new Array();
  26606. vector.toArray(temp);
  26607. this.addUniform(name, temp);
  26608. };
  26609. /**
  26610. * Wrapper for addUniform.
  26611. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26612. */
  26613. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  26614. this.addUniform(name, 12);
  26615. };
  26616. /**
  26617. * Wrapper for addUniform.
  26618. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  26619. */
  26620. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  26621. this.addUniform(name, 8);
  26622. };
  26623. /**
  26624. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  26625. */
  26626. UniformBuffer.prototype.create = function () {
  26627. if (this._noUBO) {
  26628. return;
  26629. }
  26630. if (this._buffer) {
  26631. return; // nothing to do
  26632. }
  26633. // See spec, alignment must be filled as a vec4
  26634. this._fillAlignment(4);
  26635. this._bufferData = new Float32Array(this._data);
  26636. this._rebuild();
  26637. this._needSync = true;
  26638. };
  26639. UniformBuffer.prototype._rebuild = function () {
  26640. if (this._noUBO) {
  26641. return;
  26642. }
  26643. if (this._dynamic) {
  26644. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  26645. }
  26646. else {
  26647. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  26648. }
  26649. };
  26650. /**
  26651. * Updates the WebGL Uniform Buffer on the GPU.
  26652. * If the `dynamic` flag is set to true, no cache comparison is done.
  26653. * Otherwise, the buffer will be updated only if the cache differs.
  26654. */
  26655. UniformBuffer.prototype.update = function () {
  26656. if (!this._buffer) {
  26657. this.create();
  26658. return;
  26659. }
  26660. if (!this._dynamic && !this._needSync) {
  26661. return;
  26662. }
  26663. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  26664. this._needSync = false;
  26665. };
  26666. /**
  26667. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  26668. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26669. * @param {number[]|Float32Array} data Flattened data
  26670. * @param {number} size Size of the data.
  26671. */
  26672. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  26673. var location = this._uniformLocations[uniformName];
  26674. if (location === undefined) {
  26675. if (this._buffer) {
  26676. // Cannot add an uniform if the buffer is already created
  26677. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  26678. return;
  26679. }
  26680. this.addUniform(uniformName, size);
  26681. location = this._uniformLocations[uniformName];
  26682. }
  26683. if (!this._buffer) {
  26684. this.create();
  26685. }
  26686. if (!this._dynamic) {
  26687. // Cache for static uniform buffers
  26688. var changed = false;
  26689. for (var i = 0; i < size; i++) {
  26690. if (this._bufferData[location + i] !== data[i]) {
  26691. changed = true;
  26692. this._bufferData[location + i] = data[i];
  26693. }
  26694. }
  26695. this._needSync = this._needSync || changed;
  26696. }
  26697. else {
  26698. // No cache for dynamic
  26699. for (var i = 0; i < size; i++) {
  26700. this._bufferData[location + i] = data[i];
  26701. }
  26702. }
  26703. };
  26704. // Update methods
  26705. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  26706. // To match std140, matrix must be realigned
  26707. for (var i = 0; i < 3; i++) {
  26708. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  26709. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  26710. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  26711. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26712. }
  26713. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  26714. };
  26715. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  26716. this._currentEffect.setMatrix3x3(name, matrix);
  26717. };
  26718. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  26719. this._currentEffect.setMatrix2x2(name, matrix);
  26720. };
  26721. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  26722. // To match std140, matrix must be realigned
  26723. for (var i = 0; i < 2; i++) {
  26724. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  26725. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  26726. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  26727. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26728. }
  26729. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  26730. };
  26731. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  26732. this._currentEffect.setFloat(name, x);
  26733. };
  26734. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  26735. UniformBuffer._tempBuffer[0] = x;
  26736. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  26737. };
  26738. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  26739. if (suffix === void 0) { suffix = ""; }
  26740. this._currentEffect.setFloat2(name + suffix, x, y);
  26741. };
  26742. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  26743. if (suffix === void 0) { suffix = ""; }
  26744. UniformBuffer._tempBuffer[0] = x;
  26745. UniformBuffer._tempBuffer[1] = y;
  26746. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  26747. };
  26748. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  26749. if (suffix === void 0) { suffix = ""; }
  26750. this._currentEffect.setFloat3(name + suffix, x, y, z);
  26751. };
  26752. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  26753. if (suffix === void 0) { suffix = ""; }
  26754. UniformBuffer._tempBuffer[0] = x;
  26755. UniformBuffer._tempBuffer[1] = y;
  26756. UniformBuffer._tempBuffer[2] = z;
  26757. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26758. };
  26759. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  26760. if (suffix === void 0) { suffix = ""; }
  26761. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  26762. };
  26763. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  26764. if (suffix === void 0) { suffix = ""; }
  26765. UniformBuffer._tempBuffer[0] = x;
  26766. UniformBuffer._tempBuffer[1] = y;
  26767. UniformBuffer._tempBuffer[2] = z;
  26768. UniformBuffer._tempBuffer[3] = w;
  26769. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26770. };
  26771. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  26772. this._currentEffect.setMatrix(name, mat);
  26773. };
  26774. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  26775. this.updateUniform(name, mat.toArray(), 16);
  26776. };
  26777. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  26778. this._currentEffect.setVector3(name, vector);
  26779. };
  26780. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  26781. vector.toArray(UniformBuffer._tempBuffer);
  26782. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26783. };
  26784. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  26785. this._currentEffect.setVector4(name, vector);
  26786. };
  26787. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  26788. vector.toArray(UniformBuffer._tempBuffer);
  26789. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26790. };
  26791. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  26792. if (suffix === void 0) { suffix = ""; }
  26793. this._currentEffect.setColor3(name + suffix, color);
  26794. };
  26795. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  26796. if (suffix === void 0) { suffix = ""; }
  26797. color.toArray(UniformBuffer._tempBuffer);
  26798. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26799. };
  26800. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  26801. if (suffix === void 0) { suffix = ""; }
  26802. this._currentEffect.setColor4(name + suffix, color, alpha);
  26803. };
  26804. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  26805. if (suffix === void 0) { suffix = ""; }
  26806. color.toArray(UniformBuffer._tempBuffer);
  26807. UniformBuffer._tempBuffer[3] = alpha;
  26808. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26809. };
  26810. /**
  26811. * Sets a sampler uniform on the effect.
  26812. * @param {string} name Name of the sampler.
  26813. * @param {Texture} texture
  26814. */
  26815. UniformBuffer.prototype.setTexture = function (name, texture) {
  26816. this._currentEffect.setTexture(name, texture);
  26817. };
  26818. /**
  26819. * Directly updates the value of the uniform in the cache AND on the GPU.
  26820. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26821. * @param {number[]|Float32Array} data Flattened data
  26822. */
  26823. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  26824. this.updateUniform(uniformName, data, data.length);
  26825. this.update();
  26826. };
  26827. /**
  26828. * Binds this uniform buffer to an effect.
  26829. * @param {Effect} effect
  26830. * @param {string} name Name of the uniform block in the shader.
  26831. */
  26832. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  26833. this._currentEffect = effect;
  26834. if (this._noUBO) {
  26835. return;
  26836. }
  26837. effect.bindUniformBuffer(this._buffer, name);
  26838. };
  26839. /**
  26840. * Disposes the uniform buffer.
  26841. */
  26842. UniformBuffer.prototype.dispose = function () {
  26843. if (this._noUBO) {
  26844. return;
  26845. }
  26846. var index = this._engine._uniformBuffers.indexOf(this);
  26847. if (index !== -1) {
  26848. this._engine._uniformBuffers.splice(index, 1);
  26849. }
  26850. if (!this._buffer) {
  26851. return;
  26852. }
  26853. if (this._engine._releaseBuffer(this._buffer)) {
  26854. this._buffer = null;
  26855. }
  26856. };
  26857. // Pool for avoiding memory leaks
  26858. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  26859. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  26860. return UniformBuffer;
  26861. }());
  26862. BABYLON.UniformBuffer = UniformBuffer;
  26863. })(BABYLON || (BABYLON = {}));
  26864. //# sourceMappingURL=babylon.uniformBuffer.js.map
  26865. var BABYLON;
  26866. (function (BABYLON) {
  26867. var PushMaterial = (function (_super) {
  26868. __extends(PushMaterial, _super);
  26869. function PushMaterial(name, scene) {
  26870. var _this = _super.call(this, name, scene) || this;
  26871. _this.storeEffectOnSubMeshes = true;
  26872. return _this;
  26873. }
  26874. PushMaterial.prototype.getEffect = function () {
  26875. return this._activeEffect;
  26876. };
  26877. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  26878. if (!mesh) {
  26879. return false;
  26880. }
  26881. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26882. return true;
  26883. }
  26884. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  26885. };
  26886. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26887. this._activeEffect.setMatrix("world", world);
  26888. };
  26889. PushMaterial.prototype.bind = function (world, mesh) {
  26890. if (!mesh) {
  26891. return;
  26892. }
  26893. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  26894. };
  26895. PushMaterial.prototype._afterBind = function (mesh, effect) {
  26896. _super.prototype._afterBind.call(this, mesh);
  26897. this.getScene()._cachedEffect = effect;
  26898. };
  26899. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  26900. if (visibility === void 0) { visibility = 1; }
  26901. return scene.isCachedMaterialInvalid(this, effect, visibility);
  26902. };
  26903. return PushMaterial;
  26904. }(BABYLON.Material));
  26905. BABYLON.PushMaterial = PushMaterial;
  26906. })(BABYLON || (BABYLON = {}));
  26907. //# sourceMappingURL=babylon.pushMaterial.js.map
  26908. var BABYLON;
  26909. (function (BABYLON) {
  26910. var VertexData = (function () {
  26911. function VertexData() {
  26912. }
  26913. VertexData.prototype.set = function (data, kind) {
  26914. switch (kind) {
  26915. case BABYLON.VertexBuffer.PositionKind:
  26916. this.positions = data;
  26917. break;
  26918. case BABYLON.VertexBuffer.NormalKind:
  26919. this.normals = data;
  26920. break;
  26921. case BABYLON.VertexBuffer.TangentKind:
  26922. this.tangents = data;
  26923. break;
  26924. case BABYLON.VertexBuffer.UVKind:
  26925. this.uvs = data;
  26926. break;
  26927. case BABYLON.VertexBuffer.UV2Kind:
  26928. this.uvs2 = data;
  26929. break;
  26930. case BABYLON.VertexBuffer.UV3Kind:
  26931. this.uvs3 = data;
  26932. break;
  26933. case BABYLON.VertexBuffer.UV4Kind:
  26934. this.uvs4 = data;
  26935. break;
  26936. case BABYLON.VertexBuffer.UV5Kind:
  26937. this.uvs5 = data;
  26938. break;
  26939. case BABYLON.VertexBuffer.UV6Kind:
  26940. this.uvs6 = data;
  26941. break;
  26942. case BABYLON.VertexBuffer.ColorKind:
  26943. this.colors = data;
  26944. break;
  26945. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26946. this.matricesIndices = data;
  26947. break;
  26948. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26949. this.matricesWeights = data;
  26950. break;
  26951. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  26952. this.matricesIndicesExtra = data;
  26953. break;
  26954. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  26955. this.matricesWeightsExtra = data;
  26956. break;
  26957. }
  26958. };
  26959. /**
  26960. * Associates the vertexData to the passed Mesh.
  26961. * Sets it as updatable or not (default `false`).
  26962. * Returns the VertexData.
  26963. */
  26964. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26965. this._applyTo(mesh, updatable);
  26966. return this;
  26967. };
  26968. /**
  26969. * Associates the vertexData to the passed Geometry.
  26970. * Sets it as updatable or not (default `false`).
  26971. * Returns the VertexData.
  26972. */
  26973. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26974. this._applyTo(geometry, updatable);
  26975. return this;
  26976. };
  26977. /**
  26978. * Updates the associated mesh.
  26979. * Returns the VertexData.
  26980. */
  26981. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  26982. this._update(mesh);
  26983. return this;
  26984. };
  26985. /**
  26986. * Updates the associated geometry.
  26987. * Returns the VertexData.
  26988. */
  26989. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  26990. this._update(geometry);
  26991. return this;
  26992. };
  26993. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  26994. if (this.positions) {
  26995. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  26996. }
  26997. if (this.normals) {
  26998. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  26999. }
  27000. if (this.tangents) {
  27001. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  27002. }
  27003. if (this.uvs) {
  27004. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  27005. }
  27006. if (this.uvs2) {
  27007. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  27008. }
  27009. if (this.uvs3) {
  27010. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  27011. }
  27012. if (this.uvs4) {
  27013. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  27014. }
  27015. if (this.uvs5) {
  27016. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  27017. }
  27018. if (this.uvs6) {
  27019. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  27020. }
  27021. if (this.colors) {
  27022. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  27023. }
  27024. if (this.matricesIndices) {
  27025. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  27026. }
  27027. if (this.matricesWeights) {
  27028. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  27029. }
  27030. if (this.matricesIndicesExtra) {
  27031. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  27032. }
  27033. if (this.matricesWeightsExtra) {
  27034. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  27035. }
  27036. if (this.indices) {
  27037. meshOrGeometry.setIndices(this.indices);
  27038. }
  27039. return this;
  27040. };
  27041. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  27042. if (this.positions) {
  27043. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  27044. }
  27045. if (this.normals) {
  27046. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  27047. }
  27048. if (this.tangents) {
  27049. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  27050. }
  27051. if (this.uvs) {
  27052. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  27053. }
  27054. if (this.uvs2) {
  27055. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  27056. }
  27057. if (this.uvs3) {
  27058. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  27059. }
  27060. if (this.uvs4) {
  27061. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  27062. }
  27063. if (this.uvs5) {
  27064. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  27065. }
  27066. if (this.uvs6) {
  27067. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  27068. }
  27069. if (this.colors) {
  27070. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  27071. }
  27072. if (this.matricesIndices) {
  27073. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  27074. }
  27075. if (this.matricesWeights) {
  27076. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  27077. }
  27078. if (this.matricesIndicesExtra) {
  27079. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  27080. }
  27081. if (this.matricesWeightsExtra) {
  27082. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  27083. }
  27084. if (this.indices) {
  27085. meshOrGeometry.setIndices(this.indices);
  27086. }
  27087. return this;
  27088. };
  27089. /**
  27090. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  27091. * Returns the VertexData.
  27092. */
  27093. VertexData.prototype.transform = function (matrix) {
  27094. var transformed = BABYLON.Vector3.Zero();
  27095. var index;
  27096. if (this.positions) {
  27097. var position = BABYLON.Vector3.Zero();
  27098. for (index = 0; index < this.positions.length; index += 3) {
  27099. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  27100. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  27101. this.positions[index] = transformed.x;
  27102. this.positions[index + 1] = transformed.y;
  27103. this.positions[index + 2] = transformed.z;
  27104. }
  27105. }
  27106. if (this.normals) {
  27107. var normal = BABYLON.Vector3.Zero();
  27108. for (index = 0; index < this.normals.length; index += 3) {
  27109. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  27110. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  27111. this.normals[index] = transformed.x;
  27112. this.normals[index + 1] = transformed.y;
  27113. this.normals[index + 2] = transformed.z;
  27114. }
  27115. }
  27116. if (this.tangents) {
  27117. var tangent = BABYLON.Vector4.Zero();
  27118. var tangentTransformed = BABYLON.Vector4.Zero();
  27119. for (index = 0; index < this.tangents.length; index += 4) {
  27120. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  27121. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  27122. this.tangents[index] = tangentTransformed.x;
  27123. this.tangents[index + 1] = tangentTransformed.y;
  27124. this.tangents[index + 2] = tangentTransformed.z;
  27125. this.tangents[index + 3] = tangentTransformed.w;
  27126. }
  27127. }
  27128. return this;
  27129. };
  27130. /**
  27131. * Merges the passed VertexData into the current one.
  27132. * Returns the modified VertexData.
  27133. */
  27134. VertexData.prototype.merge = function (other) {
  27135. if (other.indices) {
  27136. if (!this.indices) {
  27137. this.indices = [];
  27138. }
  27139. var offset = this.positions ? this.positions.length / 3 : 0;
  27140. for (var index = 0; index < other.indices.length; index++) {
  27141. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  27142. this.indices.push(other.indices[index] + offset);
  27143. }
  27144. }
  27145. this.positions = this._mergeElement(this.positions, other.positions);
  27146. var count = this.positions.length / 3;
  27147. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  27148. this.tangents = this._mergeElement(this.tangents, other.tangents, count * 4);
  27149. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  27150. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  27151. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  27152. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  27153. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  27154. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  27155. this.colors = this._mergeElement(this.colors, other.colors, count * 4);
  27156. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  27157. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  27158. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  27159. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  27160. return this;
  27161. };
  27162. VertexData.prototype._mergeElement = function (source, other, length) {
  27163. if (length === void 0) { length = 0; }
  27164. if (!other && !source) {
  27165. return null;
  27166. }
  27167. if (!other) {
  27168. return this._mergeElement(source, new Float32Array(source.length), length);
  27169. }
  27170. if (!source) {
  27171. if (length === other.length) {
  27172. return other;
  27173. }
  27174. return this._mergeElement(new Float32Array(length - other.length), other, length);
  27175. }
  27176. var len = other.length + source.length;
  27177. var isSrcTypedArray = source instanceof Float32Array;
  27178. var isOthTypedArray = other instanceof Float32Array;
  27179. // use non-loop method when the source is Float32Array
  27180. if (isSrcTypedArray) {
  27181. var ret32 = new Float32Array(len);
  27182. ret32.set(source);
  27183. ret32.set(other, source.length);
  27184. return ret32;
  27185. // source is number[], when other is also use concat
  27186. }
  27187. else if (!isOthTypedArray) {
  27188. return source.concat(other);
  27189. // source is a number[], but other is a Float32Array, loop required
  27190. }
  27191. else {
  27192. var ret = source.slice(0); // copy source to a separate array
  27193. for (var i = 0, len = other.length; i < len; i++) {
  27194. ret.push(other[i]);
  27195. }
  27196. return ret;
  27197. }
  27198. };
  27199. /**
  27200. * Serializes the VertexData.
  27201. * Returns a serialized object.
  27202. */
  27203. VertexData.prototype.serialize = function () {
  27204. var serializationObject = this.serialize();
  27205. if (this.positions) {
  27206. serializationObject.positions = this.positions;
  27207. }
  27208. if (this.normals) {
  27209. serializationObject.normals = this.normals;
  27210. }
  27211. if (this.tangents) {
  27212. serializationObject.tangents = this.tangents;
  27213. }
  27214. if (this.uvs) {
  27215. serializationObject.uvs = this.uvs;
  27216. }
  27217. if (this.uvs2) {
  27218. serializationObject.uvs2 = this.uvs2;
  27219. }
  27220. if (this.uvs3) {
  27221. serializationObject.uvs3 = this.uvs3;
  27222. }
  27223. if (this.uvs4) {
  27224. serializationObject.uvs4 = this.uvs4;
  27225. }
  27226. if (this.uvs5) {
  27227. serializationObject.uvs5 = this.uvs5;
  27228. }
  27229. if (this.uvs6) {
  27230. serializationObject.uvs6 = this.uvs6;
  27231. }
  27232. if (this.colors) {
  27233. serializationObject.colors = this.colors;
  27234. }
  27235. if (this.matricesIndices) {
  27236. serializationObject.matricesIndices = this.matricesIndices;
  27237. serializationObject.matricesIndices._isExpanded = true;
  27238. }
  27239. if (this.matricesWeights) {
  27240. serializationObject.matricesWeights = this.matricesWeights;
  27241. }
  27242. if (this.matricesIndicesExtra) {
  27243. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  27244. serializationObject.matricesIndicesExtra._isExpanded = true;
  27245. }
  27246. if (this.matricesWeightsExtra) {
  27247. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  27248. }
  27249. serializationObject.indices = this.indices;
  27250. return serializationObject;
  27251. };
  27252. // Statics
  27253. /**
  27254. * Returns the object VertexData associated to the passed mesh.
  27255. */
  27256. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  27257. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  27258. };
  27259. /**
  27260. * Returns the object VertexData associated to the passed geometry.
  27261. */
  27262. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  27263. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  27264. };
  27265. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  27266. var result = new VertexData();
  27267. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27268. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  27269. }
  27270. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27271. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  27272. }
  27273. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  27274. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  27275. }
  27276. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27277. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  27278. }
  27279. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27280. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  27281. }
  27282. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27283. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  27284. }
  27285. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27286. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  27287. }
  27288. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27289. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  27290. }
  27291. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27292. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  27293. }
  27294. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27295. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  27296. }
  27297. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27298. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  27299. }
  27300. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27301. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  27302. }
  27303. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  27304. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  27305. }
  27306. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  27307. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  27308. }
  27309. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  27310. return result;
  27311. };
  27312. /**
  27313. * Creates the vertexData of the Ribbon.
  27314. */
  27315. VertexData.CreateRibbon = function (options) {
  27316. var pathArray = options.pathArray;
  27317. var closeArray = options.closeArray || false;
  27318. var closePath = options.closePath || false;
  27319. var invertUV = options.invertUV || false;
  27320. var defaultOffset = Math.floor(pathArray[0].length / 2);
  27321. var offset = options.offset || defaultOffset;
  27322. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  27323. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27324. var customUV = options.uvs;
  27325. var customColors = options.colors;
  27326. var positions = [];
  27327. var indices = [];
  27328. var normals = [];
  27329. var uvs = [];
  27330. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  27331. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  27332. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  27333. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  27334. var minlg; // minimal length among all paths from pathArray
  27335. var lg = []; // array of path lengths : nb of vertex per path
  27336. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  27337. var p; // path iterator
  27338. var i; // point iterator
  27339. var j; // point iterator
  27340. // if single path in pathArray
  27341. if (pathArray.length < 2) {
  27342. var ar1 = [];
  27343. var ar2 = [];
  27344. for (i = 0; i < pathArray[0].length - offset; i++) {
  27345. ar1.push(pathArray[0][i]);
  27346. ar2.push(pathArray[0][i + offset]);
  27347. }
  27348. pathArray = [ar1, ar2];
  27349. }
  27350. // positions and horizontal distances (u)
  27351. var idc = 0;
  27352. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  27353. var path;
  27354. var l;
  27355. minlg = pathArray[0].length;
  27356. var vectlg;
  27357. var dist;
  27358. for (p = 0; p < pathArray.length; p++) {
  27359. uTotalDistance[p] = 0;
  27360. us[p] = [0];
  27361. path = pathArray[p];
  27362. l = path.length;
  27363. minlg = (minlg < l) ? minlg : l;
  27364. j = 0;
  27365. while (j < l) {
  27366. positions.push(path[j].x, path[j].y, path[j].z);
  27367. if (j > 0) {
  27368. vectlg = path[j].subtract(path[j - 1]).length();
  27369. dist = vectlg + uTotalDistance[p];
  27370. us[p].push(dist);
  27371. uTotalDistance[p] = dist;
  27372. }
  27373. j++;
  27374. }
  27375. if (closePath) {
  27376. j--;
  27377. positions.push(path[0].x, path[0].y, path[0].z);
  27378. vectlg = path[j].subtract(path[0]).length();
  27379. dist = vectlg + uTotalDistance[p];
  27380. us[p].push(dist);
  27381. uTotalDistance[p] = dist;
  27382. }
  27383. lg[p] = l + closePathCorr;
  27384. idx[p] = idc;
  27385. idc += (l + closePathCorr);
  27386. }
  27387. // vertical distances (v)
  27388. var path1;
  27389. var path2;
  27390. var vertex1;
  27391. var vertex2;
  27392. for (i = 0; i < minlg + closePathCorr; i++) {
  27393. vTotalDistance[i] = 0;
  27394. vs[i] = [0];
  27395. for (p = 0; p < pathArray.length - 1; p++) {
  27396. path1 = pathArray[p];
  27397. path2 = pathArray[p + 1];
  27398. if (i === minlg) {
  27399. vertex1 = path1[0];
  27400. vertex2 = path2[0];
  27401. }
  27402. else {
  27403. vertex1 = path1[i];
  27404. vertex2 = path2[i];
  27405. }
  27406. vectlg = vertex2.subtract(vertex1).length();
  27407. dist = vectlg + vTotalDistance[i];
  27408. vs[i].push(dist);
  27409. vTotalDistance[i] = dist;
  27410. }
  27411. if (closeArray) {
  27412. path1 = pathArray[p];
  27413. path2 = pathArray[0];
  27414. if (i === minlg) {
  27415. vertex2 = path2[0];
  27416. }
  27417. vectlg = vertex2.subtract(vertex1).length();
  27418. dist = vectlg + vTotalDistance[i];
  27419. vTotalDistance[i] = dist;
  27420. }
  27421. }
  27422. // uvs
  27423. var u;
  27424. var v;
  27425. if (customUV) {
  27426. for (p = 0; p < customUV.length; p++) {
  27427. uvs.push(customUV[p].x, customUV[p].y);
  27428. }
  27429. }
  27430. else {
  27431. for (p = 0; p < pathArray.length; p++) {
  27432. for (i = 0; i < minlg + closePathCorr; i++) {
  27433. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  27434. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  27435. if (invertUV) {
  27436. uvs.push(v, u);
  27437. }
  27438. else {
  27439. uvs.push(u, v);
  27440. }
  27441. }
  27442. }
  27443. }
  27444. // indices
  27445. p = 0; // path index
  27446. var pi = 0; // positions array index
  27447. var l1 = lg[p] - 1; // path1 length
  27448. var l2 = lg[p + 1] - 1; // path2 length
  27449. var min = (l1 < l2) ? l1 : l2; // current path stop index
  27450. var shft = idx[1] - idx[0]; // shift
  27451. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  27452. while (pi <= min && p < path1nb) {
  27453. // 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
  27454. indices.push(pi, pi + shft, pi + 1);
  27455. indices.push(pi + shft + 1, pi + 1, pi + shft);
  27456. pi += 1;
  27457. if (pi === min) {
  27458. p++;
  27459. if (p === lg.length - 1) {
  27460. shft = idx[0] - idx[p];
  27461. l1 = lg[p] - 1;
  27462. l2 = lg[0] - 1;
  27463. }
  27464. else {
  27465. shft = idx[p + 1] - idx[p];
  27466. l1 = lg[p] - 1;
  27467. l2 = lg[p + 1] - 1;
  27468. }
  27469. pi = idx[p];
  27470. min = (l1 < l2) ? l1 + pi : l2 + pi;
  27471. }
  27472. }
  27473. // normals
  27474. VertexData.ComputeNormals(positions, indices, normals);
  27475. if (closePath) {
  27476. var indexFirst = 0;
  27477. var indexLast = 0;
  27478. for (p = 0; p < pathArray.length; p++) {
  27479. indexFirst = idx[p] * 3;
  27480. if (p + 1 < pathArray.length) {
  27481. indexLast = (idx[p + 1] - 1) * 3;
  27482. }
  27483. else {
  27484. indexLast = normals.length - 3;
  27485. }
  27486. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  27487. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  27488. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  27489. normals[indexLast] = normals[indexFirst];
  27490. normals[indexLast + 1] = normals[indexFirst + 1];
  27491. normals[indexLast + 2] = normals[indexFirst + 2];
  27492. }
  27493. }
  27494. // sides
  27495. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27496. // Colors
  27497. if (customColors) {
  27498. var colors = new Float32Array(customColors.length * 4);
  27499. for (var c = 0; c < customColors.length; c++) {
  27500. colors[c * 4] = customColors[c].r;
  27501. colors[c * 4 + 1] = customColors[c].g;
  27502. colors[c * 4 + 2] = customColors[c].b;
  27503. colors[c * 4 + 3] = customColors[c].a;
  27504. }
  27505. }
  27506. // Result
  27507. var vertexData = new VertexData();
  27508. var positions32 = new Float32Array(positions);
  27509. var normals32 = new Float32Array(normals);
  27510. var uvs32 = new Float32Array(uvs);
  27511. vertexData.indices = indices;
  27512. vertexData.positions = positions32;
  27513. vertexData.normals = normals32;
  27514. vertexData.uvs = uvs32;
  27515. if (customColors) {
  27516. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  27517. }
  27518. if (closePath) {
  27519. vertexData._idx = idx;
  27520. }
  27521. return vertexData;
  27522. };
  27523. /**
  27524. * Creates the VertexData of the Box.
  27525. */
  27526. VertexData.CreateBox = function (options) {
  27527. var normalsSource = [
  27528. new BABYLON.Vector3(0, 0, 1),
  27529. new BABYLON.Vector3(0, 0, -1),
  27530. new BABYLON.Vector3(1, 0, 0),
  27531. new BABYLON.Vector3(-1, 0, 0),
  27532. new BABYLON.Vector3(0, 1, 0),
  27533. new BABYLON.Vector3(0, -1, 0)
  27534. ];
  27535. var indices = [];
  27536. var positions = [];
  27537. var normals = [];
  27538. var uvs = [];
  27539. var width = options.width || options.size || 1;
  27540. var height = options.height || options.size || 1;
  27541. var depth = options.depth || options.size || 1;
  27542. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27543. var faceUV = options.faceUV || new Array(6);
  27544. var faceColors = options.faceColors;
  27545. var colors = [];
  27546. // default face colors and UV if undefined
  27547. for (var f = 0; f < 6; f++) {
  27548. if (faceUV[f] === undefined) {
  27549. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27550. }
  27551. if (faceColors && faceColors[f] === undefined) {
  27552. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27553. }
  27554. }
  27555. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  27556. // Create each face in turn.
  27557. for (var index = 0; index < normalsSource.length; index++) {
  27558. var normal = normalsSource[index];
  27559. // Get two vectors perpendicular to the face normal and to each other.
  27560. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  27561. var side2 = BABYLON.Vector3.Cross(normal, side1);
  27562. // Six indices (two triangles) per face.
  27563. var verticesLength = positions.length / 3;
  27564. indices.push(verticesLength);
  27565. indices.push(verticesLength + 1);
  27566. indices.push(verticesLength + 2);
  27567. indices.push(verticesLength);
  27568. indices.push(verticesLength + 2);
  27569. indices.push(verticesLength + 3);
  27570. // Four vertices per face.
  27571. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  27572. positions.push(vertex.x, vertex.y, vertex.z);
  27573. normals.push(normal.x, normal.y, normal.z);
  27574. uvs.push(faceUV[index].z, faceUV[index].w);
  27575. if (faceColors) {
  27576. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27577. }
  27578. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  27579. positions.push(vertex.x, vertex.y, vertex.z);
  27580. normals.push(normal.x, normal.y, normal.z);
  27581. uvs.push(faceUV[index].x, faceUV[index].w);
  27582. if (faceColors) {
  27583. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27584. }
  27585. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  27586. positions.push(vertex.x, vertex.y, vertex.z);
  27587. normals.push(normal.x, normal.y, normal.z);
  27588. uvs.push(faceUV[index].x, faceUV[index].y);
  27589. if (faceColors) {
  27590. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27591. }
  27592. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  27593. positions.push(vertex.x, vertex.y, vertex.z);
  27594. normals.push(normal.x, normal.y, normal.z);
  27595. uvs.push(faceUV[index].z, faceUV[index].y);
  27596. if (faceColors) {
  27597. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27598. }
  27599. }
  27600. // sides
  27601. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27602. // Result
  27603. var vertexData = new VertexData();
  27604. vertexData.indices = indices;
  27605. vertexData.positions = positions;
  27606. vertexData.normals = normals;
  27607. vertexData.uvs = uvs;
  27608. if (faceColors) {
  27609. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27610. vertexData.colors = totalColors;
  27611. }
  27612. return vertexData;
  27613. };
  27614. /**
  27615. * Creates the VertexData of the Sphere.
  27616. */
  27617. VertexData.CreateSphere = function (options) {
  27618. var segments = options.segments || 32;
  27619. var diameterX = options.diameterX || options.diameter || 1;
  27620. var diameterY = options.diameterY || options.diameter || 1;
  27621. var diameterZ = options.diameterZ || options.diameter || 1;
  27622. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27623. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  27624. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27625. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  27626. var totalZRotationSteps = 2 + segments;
  27627. var totalYRotationSteps = 2 * totalZRotationSteps;
  27628. var indices = [];
  27629. var positions = [];
  27630. var normals = [];
  27631. var uvs = [];
  27632. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  27633. var normalizedZ = zRotationStep / totalZRotationSteps;
  27634. var angleZ = normalizedZ * Math.PI * slice;
  27635. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  27636. var normalizedY = yRotationStep / totalYRotationSteps;
  27637. var angleY = normalizedY * Math.PI * 2 * arc;
  27638. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  27639. var rotationY = BABYLON.Matrix.RotationY(angleY);
  27640. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  27641. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  27642. var vertex = complete.multiply(radius);
  27643. var normal = complete.divide(radius).normalize();
  27644. positions.push(vertex.x, vertex.y, vertex.z);
  27645. normals.push(normal.x, normal.y, normal.z);
  27646. uvs.push(normalizedY, normalizedZ);
  27647. }
  27648. if (zRotationStep > 0) {
  27649. var verticesCount = positions.length / 3;
  27650. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  27651. indices.push((firstIndex));
  27652. indices.push((firstIndex + 1));
  27653. indices.push(firstIndex + totalYRotationSteps + 1);
  27654. indices.push((firstIndex + totalYRotationSteps + 1));
  27655. indices.push((firstIndex + 1));
  27656. indices.push((firstIndex + totalYRotationSteps + 2));
  27657. }
  27658. }
  27659. }
  27660. // Sides
  27661. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27662. // Result
  27663. var vertexData = new VertexData();
  27664. vertexData.indices = indices;
  27665. vertexData.positions = positions;
  27666. vertexData.normals = normals;
  27667. vertexData.uvs = uvs;
  27668. return vertexData;
  27669. };
  27670. /**
  27671. * Creates the VertexData of the Cylinder or Cone.
  27672. */
  27673. VertexData.CreateCylinder = function (options) {
  27674. var height = options.height || 2;
  27675. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  27676. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  27677. var tessellation = options.tessellation || 24;
  27678. var subdivisions = options.subdivisions || 1;
  27679. var hasRings = options.hasRings;
  27680. var enclose = options.enclose;
  27681. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27682. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27683. var faceUV = options.faceUV || new Array(3);
  27684. var faceColors = options.faceColors;
  27685. // default face colors and UV if undefined
  27686. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  27687. var ringNb = (hasRings) ? subdivisions : 1;
  27688. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  27689. var f;
  27690. for (f = 0; f < surfaceNb; f++) {
  27691. if (faceColors && faceColors[f] === undefined) {
  27692. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27693. }
  27694. }
  27695. for (f = 0; f < surfaceNb; f++) {
  27696. if (faceUV && faceUV[f] === undefined) {
  27697. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27698. }
  27699. }
  27700. var indices = new Array();
  27701. var positions = new Array();
  27702. var normals = new Array();
  27703. var uvs = new Array();
  27704. var colors = new Array();
  27705. var angle_step = Math.PI * 2 * arc / tessellation;
  27706. var angle;
  27707. var h;
  27708. var radius;
  27709. var tan = (diameterBottom - diameterTop) / 2 / height;
  27710. var ringVertex = BABYLON.Vector3.Zero();
  27711. var ringNormal = BABYLON.Vector3.Zero();
  27712. var ringFirstVertex = BABYLON.Vector3.Zero();
  27713. var ringFirstNormal = BABYLON.Vector3.Zero();
  27714. var quadNormal = BABYLON.Vector3.Zero();
  27715. var Y = BABYLON.Axis.Y;
  27716. // positions, normals, uvs
  27717. var i;
  27718. var j;
  27719. var r;
  27720. var ringIdx = 1;
  27721. var s = 1; // surface index
  27722. var cs = 0;
  27723. var v = 0;
  27724. for (i = 0; i <= subdivisions; i++) {
  27725. h = i / subdivisions;
  27726. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  27727. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  27728. for (r = 0; r < ringIdx; r++) {
  27729. if (hasRings) {
  27730. s += r;
  27731. }
  27732. if (enclose) {
  27733. s += 2 * r;
  27734. }
  27735. for (j = 0; j <= tessellation; j++) {
  27736. angle = j * angle_step;
  27737. // position
  27738. ringVertex.x = Math.cos(-angle) * radius;
  27739. ringVertex.y = -height / 2 + h * height;
  27740. ringVertex.z = Math.sin(-angle) * radius;
  27741. // normal
  27742. if (diameterTop === 0 && i === subdivisions) {
  27743. // if no top cap, reuse former normals
  27744. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  27745. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  27746. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  27747. }
  27748. else {
  27749. ringNormal.x = ringVertex.x;
  27750. ringNormal.z = ringVertex.z;
  27751. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  27752. ringNormal.normalize();
  27753. }
  27754. // keep first ring vertex values for enclose
  27755. if (j === 0) {
  27756. ringFirstVertex.copyFrom(ringVertex);
  27757. ringFirstNormal.copyFrom(ringNormal);
  27758. }
  27759. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27760. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  27761. if (hasRings) {
  27762. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  27763. }
  27764. else {
  27765. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  27766. }
  27767. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  27768. if (faceColors) {
  27769. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  27770. }
  27771. }
  27772. // if enclose, add four vertices and their dedicated normals
  27773. if (arc !== 1 && enclose) {
  27774. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27775. positions.push(0, ringVertex.y, 0);
  27776. positions.push(0, ringVertex.y, 0);
  27777. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  27778. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  27779. quadNormal.normalize();
  27780. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27781. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  27782. quadNormal.normalize();
  27783. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27784. if (hasRings) {
  27785. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  27786. }
  27787. else {
  27788. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  27789. }
  27790. uvs.push(faceUV[s + 1].x, v);
  27791. uvs.push(faceUV[s + 1].z, v);
  27792. if (hasRings) {
  27793. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  27794. }
  27795. else {
  27796. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  27797. }
  27798. uvs.push(faceUV[s + 2].x, v);
  27799. uvs.push(faceUV[s + 2].z, v);
  27800. if (faceColors) {
  27801. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27802. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27803. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27804. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27805. }
  27806. }
  27807. if (cs !== s) {
  27808. cs = s;
  27809. }
  27810. }
  27811. }
  27812. // indices
  27813. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  27814. var s;
  27815. i = 0;
  27816. for (s = 0; s < subdivisions; s++) {
  27817. for (j = 0; j < tessellation; j++) {
  27818. var i0 = i * (e + 1) + j;
  27819. var i1 = (i + 1) * (e + 1) + j;
  27820. var i2 = i * (e + 1) + (j + 1);
  27821. var i3 = (i + 1) * (e + 1) + (j + 1);
  27822. indices.push(i0, i1, i2);
  27823. indices.push(i3, i2, i1);
  27824. }
  27825. if (arc !== 1 && enclose) {
  27826. indices.push(i0 + 2, i1 + 2, i2 + 2);
  27827. indices.push(i3 + 2, i2 + 2, i1 + 2);
  27828. indices.push(i0 + 4, i1 + 4, i2 + 4);
  27829. indices.push(i3 + 4, i2 + 4, i1 + 4);
  27830. }
  27831. i = (hasRings) ? (i + 2) : (i + 1);
  27832. }
  27833. // Caps
  27834. var createCylinderCap = function (isTop) {
  27835. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  27836. if (radius === 0) {
  27837. return;
  27838. }
  27839. // Cap positions, normals & uvs
  27840. var angle;
  27841. var circleVector;
  27842. var i;
  27843. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  27844. var c;
  27845. if (faceColors) {
  27846. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  27847. }
  27848. // cap center
  27849. var vbase = positions.length / 3;
  27850. var offset = isTop ? height / 2 : -height / 2;
  27851. var center = new BABYLON.Vector3(0, offset, 0);
  27852. positions.push(center.x, center.y, center.z);
  27853. normals.push(0, isTop ? 1 : -1, 0);
  27854. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  27855. if (faceColors) {
  27856. colors.push(c.r, c.g, c.b, c.a);
  27857. }
  27858. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  27859. for (i = 0; i <= tessellation; i++) {
  27860. angle = Math.PI * 2 * i * arc / tessellation;
  27861. var cos = Math.cos(-angle);
  27862. var sin = Math.sin(-angle);
  27863. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  27864. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  27865. positions.push(circleVector.x, circleVector.y, circleVector.z);
  27866. normals.push(0, isTop ? 1 : -1, 0);
  27867. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  27868. if (faceColors) {
  27869. colors.push(c.r, c.g, c.b, c.a);
  27870. }
  27871. }
  27872. // Cap indices
  27873. for (i = 0; i < tessellation; i++) {
  27874. if (!isTop) {
  27875. indices.push(vbase);
  27876. indices.push(vbase + (i + 1));
  27877. indices.push(vbase + (i + 2));
  27878. }
  27879. else {
  27880. indices.push(vbase);
  27881. indices.push(vbase + (i + 2));
  27882. indices.push(vbase + (i + 1));
  27883. }
  27884. }
  27885. };
  27886. // add caps to geometry
  27887. createCylinderCap(false);
  27888. createCylinderCap(true);
  27889. // Sides
  27890. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27891. var vertexData = new VertexData();
  27892. vertexData.indices = indices;
  27893. vertexData.positions = positions;
  27894. vertexData.normals = normals;
  27895. vertexData.uvs = uvs;
  27896. if (faceColors) {
  27897. vertexData.colors = colors;
  27898. }
  27899. return vertexData;
  27900. };
  27901. /**
  27902. * Creates the VertexData of the Torus.
  27903. */
  27904. VertexData.CreateTorus = function (options) {
  27905. var indices = [];
  27906. var positions = [];
  27907. var normals = [];
  27908. var uvs = [];
  27909. var diameter = options.diameter || 1;
  27910. var thickness = options.thickness || 0.5;
  27911. var tessellation = options.tessellation || 16;
  27912. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27913. var stride = tessellation + 1;
  27914. for (var i = 0; i <= tessellation; i++) {
  27915. var u = i / tessellation;
  27916. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  27917. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  27918. for (var j = 0; j <= tessellation; j++) {
  27919. var v = 1 - j / tessellation;
  27920. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  27921. var dx = Math.cos(innerAngle);
  27922. var dy = Math.sin(innerAngle);
  27923. // Create a vertex.
  27924. var normal = new BABYLON.Vector3(dx, dy, 0);
  27925. var position = normal.scale(thickness / 2);
  27926. var textureCoordinate = new BABYLON.Vector2(u, v);
  27927. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  27928. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  27929. positions.push(position.x, position.y, position.z);
  27930. normals.push(normal.x, normal.y, normal.z);
  27931. uvs.push(textureCoordinate.x, textureCoordinate.y);
  27932. // And create indices for two triangles.
  27933. var nextI = (i + 1) % stride;
  27934. var nextJ = (j + 1) % stride;
  27935. indices.push(i * stride + j);
  27936. indices.push(i * stride + nextJ);
  27937. indices.push(nextI * stride + j);
  27938. indices.push(i * stride + nextJ);
  27939. indices.push(nextI * stride + nextJ);
  27940. indices.push(nextI * stride + j);
  27941. }
  27942. }
  27943. // Sides
  27944. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27945. // Result
  27946. var vertexData = new VertexData();
  27947. vertexData.indices = indices;
  27948. vertexData.positions = positions;
  27949. vertexData.normals = normals;
  27950. vertexData.uvs = uvs;
  27951. return vertexData;
  27952. };
  27953. /**
  27954. * Creates the VertexData of the LineSystem.
  27955. */
  27956. VertexData.CreateLineSystem = function (options) {
  27957. var indices = [];
  27958. var positions = [];
  27959. var lines = options.lines;
  27960. var idx = 0;
  27961. for (var l = 0; l < lines.length; l++) {
  27962. var points = lines[l];
  27963. for (var index = 0; index < points.length; index++) {
  27964. positions.push(points[index].x, points[index].y, points[index].z);
  27965. if (index > 0) {
  27966. indices.push(idx - 1);
  27967. indices.push(idx);
  27968. }
  27969. idx++;
  27970. }
  27971. }
  27972. var vertexData = new VertexData();
  27973. vertexData.indices = indices;
  27974. vertexData.positions = positions;
  27975. return vertexData;
  27976. };
  27977. /**
  27978. * Create the VertexData of the DashedLines.
  27979. */
  27980. VertexData.CreateDashedLines = function (options) {
  27981. var dashSize = options.dashSize || 3;
  27982. var gapSize = options.gapSize || 1;
  27983. var dashNb = options.dashNb || 200;
  27984. var points = options.points;
  27985. var positions = new Array();
  27986. var indices = new Array();
  27987. var curvect = BABYLON.Vector3.Zero();
  27988. var lg = 0;
  27989. var nb = 0;
  27990. var shft = 0;
  27991. var dashshft = 0;
  27992. var curshft = 0;
  27993. var idx = 0;
  27994. var i = 0;
  27995. for (i = 0; i < points.length - 1; i++) {
  27996. points[i + 1].subtractToRef(points[i], curvect);
  27997. lg += curvect.length();
  27998. }
  27999. shft = lg / dashNb;
  28000. dashshft = dashSize * shft / (dashSize + gapSize);
  28001. for (i = 0; i < points.length - 1; i++) {
  28002. points[i + 1].subtractToRef(points[i], curvect);
  28003. nb = Math.floor(curvect.length() / shft);
  28004. curvect.normalize();
  28005. for (var j = 0; j < nb; j++) {
  28006. curshft = shft * j;
  28007. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  28008. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  28009. indices.push(idx, idx + 1);
  28010. idx += 2;
  28011. }
  28012. }
  28013. // Result
  28014. var vertexData = new VertexData();
  28015. vertexData.positions = positions;
  28016. vertexData.indices = indices;
  28017. return vertexData;
  28018. };
  28019. /**
  28020. * Creates the VertexData of the Ground.
  28021. */
  28022. VertexData.CreateGround = function (options) {
  28023. var indices = [];
  28024. var positions = [];
  28025. var normals = [];
  28026. var uvs = [];
  28027. var row, col;
  28028. var width = options.width || 1;
  28029. var height = options.height || 1;
  28030. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  28031. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  28032. for (row = 0; row <= subdivisionsY; row++) {
  28033. for (col = 0; col <= subdivisionsX; col++) {
  28034. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  28035. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28036. positions.push(position.x, position.y, position.z);
  28037. normals.push(normal.x, normal.y, normal.z);
  28038. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  28039. }
  28040. }
  28041. for (row = 0; row < subdivisionsY; row++) {
  28042. for (col = 0; col < subdivisionsX; col++) {
  28043. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  28044. indices.push(col + 1 + row * (subdivisionsX + 1));
  28045. indices.push(col + row * (subdivisionsX + 1));
  28046. indices.push(col + (row + 1) * (subdivisionsX + 1));
  28047. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  28048. indices.push(col + row * (subdivisionsX + 1));
  28049. }
  28050. }
  28051. // Result
  28052. var vertexData = new VertexData();
  28053. vertexData.indices = indices;
  28054. vertexData.positions = positions;
  28055. vertexData.normals = normals;
  28056. vertexData.uvs = uvs;
  28057. return vertexData;
  28058. };
  28059. /**
  28060. * Creates the VertexData of the TiledGround.
  28061. */
  28062. VertexData.CreateTiledGround = function (options) {
  28063. var xmin = options.xmin || -1.0;
  28064. var zmin = options.zmin || -1.0;
  28065. var xmax = options.xmax || 1.0;
  28066. var zmax = options.zmax || 1.0;
  28067. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  28068. var precision = options.precision || { w: 1, h: 1 };
  28069. var indices = new Array();
  28070. var positions = new Array();
  28071. var normals = new Array();
  28072. var uvs = new Array();
  28073. var row, col, tileRow, tileCol;
  28074. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  28075. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  28076. precision.w = (precision.w < 1) ? 1 : precision.w;
  28077. precision.h = (precision.h < 1) ? 1 : precision.h;
  28078. var tileSize = {
  28079. 'w': (xmax - xmin) / subdivisions.w,
  28080. 'h': (zmax - zmin) / subdivisions.h
  28081. };
  28082. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  28083. // Indices
  28084. var base = positions.length / 3;
  28085. var rowLength = precision.w + 1;
  28086. for (row = 0; row < precision.h; row++) {
  28087. for (col = 0; col < precision.w; col++) {
  28088. var square = [
  28089. base + col + row * rowLength,
  28090. base + (col + 1) + row * rowLength,
  28091. base + (col + 1) + (row + 1) * rowLength,
  28092. base + col + (row + 1) * rowLength
  28093. ];
  28094. indices.push(square[1]);
  28095. indices.push(square[2]);
  28096. indices.push(square[3]);
  28097. indices.push(square[0]);
  28098. indices.push(square[1]);
  28099. indices.push(square[3]);
  28100. }
  28101. }
  28102. // Position, normals and uvs
  28103. var position = BABYLON.Vector3.Zero();
  28104. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28105. for (row = 0; row <= precision.h; row++) {
  28106. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  28107. for (col = 0; col <= precision.w; col++) {
  28108. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  28109. position.y = 0;
  28110. positions.push(position.x, position.y, position.z);
  28111. normals.push(normal.x, normal.y, normal.z);
  28112. uvs.push(col / precision.w, row / precision.h);
  28113. }
  28114. }
  28115. }
  28116. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  28117. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  28118. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  28119. }
  28120. }
  28121. // Result
  28122. var vertexData = new VertexData();
  28123. vertexData.indices = indices;
  28124. vertexData.positions = positions;
  28125. vertexData.normals = normals;
  28126. vertexData.uvs = uvs;
  28127. return vertexData;
  28128. };
  28129. /**
  28130. * Creates the VertexData of the Ground designed from a heightmap.
  28131. */
  28132. VertexData.CreateGroundFromHeightMap = function (options) {
  28133. var indices = [];
  28134. var positions = [];
  28135. var normals = [];
  28136. var uvs = [];
  28137. var row, col;
  28138. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  28139. // Vertices
  28140. for (row = 0; row <= options.subdivisions; row++) {
  28141. for (col = 0; col <= options.subdivisions; col++) {
  28142. 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));
  28143. // Compute height
  28144. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  28145. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  28146. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  28147. var r = options.buffer[pos] / 255.0;
  28148. var g = options.buffer[pos + 1] / 255.0;
  28149. var b = options.buffer[pos + 2] / 255.0;
  28150. var gradient = r * filter.r + g * filter.g + b * filter.b;
  28151. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  28152. // Add vertex
  28153. positions.push(position.x, position.y, position.z);
  28154. normals.push(0, 0, 0);
  28155. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  28156. }
  28157. }
  28158. // Indices
  28159. for (row = 0; row < options.subdivisions; row++) {
  28160. for (col = 0; col < options.subdivisions; col++) {
  28161. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28162. indices.push(col + 1 + row * (options.subdivisions + 1));
  28163. indices.push(col + row * (options.subdivisions + 1));
  28164. indices.push(col + (row + 1) * (options.subdivisions + 1));
  28165. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28166. indices.push(col + row * (options.subdivisions + 1));
  28167. }
  28168. }
  28169. // Normals
  28170. VertexData.ComputeNormals(positions, indices, normals);
  28171. // Result
  28172. var vertexData = new VertexData();
  28173. vertexData.indices = indices;
  28174. vertexData.positions = positions;
  28175. vertexData.normals = normals;
  28176. vertexData.uvs = uvs;
  28177. return vertexData;
  28178. };
  28179. /**
  28180. * Creates the VertexData of the Plane.
  28181. */
  28182. VertexData.CreatePlane = function (options) {
  28183. var indices = [];
  28184. var positions = [];
  28185. var normals = [];
  28186. var uvs = [];
  28187. var width = options.width || options.size || 1;
  28188. var height = options.height || options.size || 1;
  28189. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28190. // Vertices
  28191. var halfWidth = width / 2.0;
  28192. var halfHeight = height / 2.0;
  28193. positions.push(-halfWidth, -halfHeight, 0);
  28194. normals.push(0, 0, -1.0);
  28195. uvs.push(0.0, 0.0);
  28196. positions.push(halfWidth, -halfHeight, 0);
  28197. normals.push(0, 0, -1.0);
  28198. uvs.push(1.0, 0.0);
  28199. positions.push(halfWidth, halfHeight, 0);
  28200. normals.push(0, 0, -1.0);
  28201. uvs.push(1.0, 1.0);
  28202. positions.push(-halfWidth, halfHeight, 0);
  28203. normals.push(0, 0, -1.0);
  28204. uvs.push(0.0, 1.0);
  28205. // Indices
  28206. indices.push(0);
  28207. indices.push(1);
  28208. indices.push(2);
  28209. indices.push(0);
  28210. indices.push(2);
  28211. indices.push(3);
  28212. // Sides
  28213. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28214. // Result
  28215. var vertexData = new VertexData();
  28216. vertexData.indices = indices;
  28217. vertexData.positions = positions;
  28218. vertexData.normals = normals;
  28219. vertexData.uvs = uvs;
  28220. return vertexData;
  28221. };
  28222. /**
  28223. * Creates the VertexData of the Disc or regular Polygon.
  28224. */
  28225. VertexData.CreateDisc = function (options) {
  28226. var positions = new Array();
  28227. var indices = new Array();
  28228. var normals = new Array();
  28229. var uvs = new Array();
  28230. var radius = options.radius || 0.5;
  28231. var tessellation = options.tessellation || 64;
  28232. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28233. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28234. // positions and uvs
  28235. positions.push(0, 0, 0); // disc center first
  28236. uvs.push(0.5, 0.5);
  28237. var theta = Math.PI * 2 * arc;
  28238. var step = theta / tessellation;
  28239. for (var a = 0; a < theta; a += step) {
  28240. var x = Math.cos(a);
  28241. var y = Math.sin(a);
  28242. var u = (x + 1) / 2;
  28243. var v = (1 - y) / 2;
  28244. positions.push(radius * x, radius * y, 0);
  28245. uvs.push(u, v);
  28246. }
  28247. if (arc === 1) {
  28248. positions.push(positions[3], positions[4], positions[5]); // close the circle
  28249. uvs.push(uvs[2], uvs[3]);
  28250. }
  28251. //indices
  28252. var vertexNb = positions.length / 3;
  28253. for (var i = 1; i < vertexNb - 1; i++) {
  28254. indices.push(i + 1, 0, i);
  28255. }
  28256. // result
  28257. VertexData.ComputeNormals(positions, indices, normals);
  28258. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28259. var vertexData = new VertexData();
  28260. vertexData.indices = indices;
  28261. vertexData.positions = positions;
  28262. vertexData.normals = normals;
  28263. vertexData.uvs = uvs;
  28264. return vertexData;
  28265. };
  28266. /**
  28267. * Re-creates the VertexData of the Polygon for sideOrientation.
  28268. */
  28269. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  28270. var faceUV = fUV || new Array(3);
  28271. var faceColors = fColors;
  28272. var colors = [];
  28273. // default face colors and UV if undefined
  28274. for (var f = 0; f < 3; f++) {
  28275. if (faceUV[f] === undefined) {
  28276. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28277. }
  28278. if (faceColors && faceColors[f] === undefined) {
  28279. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28280. }
  28281. }
  28282. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28283. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28284. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28285. var indices = polygon.getIndices();
  28286. // set face colours and textures
  28287. var idx = 0;
  28288. var face = 0;
  28289. for (var index = 0; index < normals.length; index += 3) {
  28290. //Edge Face no. 1
  28291. if (Math.abs(normals[index + 1]) < 0.001) {
  28292. face = 1;
  28293. }
  28294. //Top Face no. 0
  28295. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  28296. face = 0;
  28297. }
  28298. //Bottom Face no. 2
  28299. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  28300. face = 2;
  28301. }
  28302. idx = index / 3;
  28303. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  28304. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  28305. if (faceColors) {
  28306. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  28307. }
  28308. }
  28309. // sides
  28310. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  28311. // Result
  28312. var vertexData = new VertexData();
  28313. vertexData.indices = indices;
  28314. vertexData.positions = positions;
  28315. vertexData.normals = normals;
  28316. vertexData.uvs = uvs;
  28317. if (faceColors) {
  28318. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28319. vertexData.colors = totalColors;
  28320. }
  28321. return vertexData;
  28322. };
  28323. /**
  28324. * Creates the VertexData of the IcoSphere.
  28325. */
  28326. VertexData.CreateIcoSphere = function (options) {
  28327. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28328. var radius = options.radius || 1;
  28329. var flat = (options.flat === undefined) ? true : options.flat;
  28330. var subdivisions = options.subdivisions || 4;
  28331. var radiusX = options.radiusX || radius;
  28332. var radiusY = options.radiusY || radius;
  28333. var radiusZ = options.radiusZ || radius;
  28334. var t = (1 + Math.sqrt(5)) / 2;
  28335. // 12 vertex x,y,z
  28336. var ico_vertices = [
  28337. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  28338. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  28339. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  28340. ];
  28341. // index of 3 vertex makes a face of icopshere
  28342. var ico_indices = [
  28343. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  28344. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  28345. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  28346. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  28347. ];
  28348. // vertex for uv have aliased position, not for UV
  28349. var vertices_unalias_id = [
  28350. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  28351. // vertex alias
  28352. 0,
  28353. 2,
  28354. 3,
  28355. 3,
  28356. 3,
  28357. 4,
  28358. 7,
  28359. 8,
  28360. 9,
  28361. 9,
  28362. 10,
  28363. 11 // 23: B + 12
  28364. ];
  28365. // uv as integer step (not pixels !)
  28366. var ico_vertexuv = [
  28367. 5, 1, 3, 1, 6, 4, 0, 0,
  28368. 5, 3, 4, 2, 2, 2, 4, 0,
  28369. 2, 0, 1, 1, 6, 0, 6, 2,
  28370. // vertex alias (for same vertex on different faces)
  28371. 0, 4,
  28372. 3, 3,
  28373. 4, 4,
  28374. 3, 1,
  28375. 4, 2,
  28376. 4, 4,
  28377. 0, 2,
  28378. 1, 1,
  28379. 2, 2,
  28380. 3, 3,
  28381. 1, 3,
  28382. 2, 4 // 23: B + 12
  28383. ];
  28384. // Vertices[0, 1, ...9, A, B] : position on UV plane
  28385. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  28386. // First island of uv mapping
  28387. // v = 4h 3+ 2
  28388. // v = 3h 9+ 4
  28389. // v = 2h 9+ 5 B
  28390. // v = 1h 9 1 0
  28391. // v = 0h 3 8 7 A
  28392. // u = 0 1 2 3 4 5 6 *a
  28393. // Second island of uv mapping
  28394. // v = 4h 0+ B+ 4+
  28395. // v = 3h A+ 2+
  28396. // v = 2h 7+ 6 3+
  28397. // v = 1h 8+ 3+
  28398. // v = 0h
  28399. // u = 0 1 2 3 4 5 6 *a
  28400. // Face layout on texture UV mapping
  28401. // ============
  28402. // \ 4 /\ 16 / ======
  28403. // \ / \ / /\ 11 /
  28404. // \/ 7 \/ / \ /
  28405. // ======= / 10 \/
  28406. // /\ 17 /\ =======
  28407. // / \ / \ \ 15 /\
  28408. // / 8 \/ 12 \ \ / \
  28409. // ============ \/ 6 \
  28410. // \ 18 /\ ============
  28411. // \ / \ \ 5 /\ 0 /
  28412. // \/ 13 \ \ / \ /
  28413. // ======= \/ 1 \/
  28414. // =============
  28415. // /\ 19 /\ 2 /\
  28416. // / \ / \ / \
  28417. // / 14 \/ 9 \/ 3 \
  28418. // ===================
  28419. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  28420. var ustep = 138 / 1024;
  28421. var vstep = 239 / 1024;
  28422. var uoffset = 60 / 1024;
  28423. var voffset = 26 / 1024;
  28424. // Second island should have margin, not to touch the first island
  28425. // avoid any borderline artefact in pixel rounding
  28426. var island_u_offset = -40 / 1024;
  28427. var island_v_offset = +20 / 1024;
  28428. // face is either island 0 or 1 :
  28429. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  28430. var island = [
  28431. 0, 0, 0, 0, 1,
  28432. 0, 0, 1, 1, 0,
  28433. 0, 0, 1, 1, 0,
  28434. 0, 1, 1, 1, 0 // 15 - 19
  28435. ];
  28436. var indices = new Array();
  28437. var positions = new Array();
  28438. var normals = new Array();
  28439. var uvs = new Array();
  28440. var current_indice = 0;
  28441. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  28442. var face_vertex_pos = new Array(3);
  28443. var face_vertex_uv = new Array(3);
  28444. var v012;
  28445. for (v012 = 0; v012 < 3; v012++) {
  28446. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  28447. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  28448. }
  28449. // create all with normals
  28450. for (var face = 0; face < 20; face++) {
  28451. // 3 vertex per face
  28452. for (v012 = 0; v012 < 3; v012++) {
  28453. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  28454. var v_id = ico_indices[3 * face + v012];
  28455. // vertex have 3D position (x,y,z)
  28456. 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]);
  28457. // Normalize to get normal, then scale to radius
  28458. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  28459. // uv Coordinates from vertex ID
  28460. 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);
  28461. }
  28462. // Subdivide the face (interpolate pos, norm, uv)
  28463. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  28464. // - norm is linear interpolation of vertex corner normal
  28465. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  28466. // - uv is linear interpolation
  28467. //
  28468. // Topology is as below for sub-divide by 2
  28469. // vertex shown as v0,v1,v2
  28470. // interp index is i1 to progress in range [v0,v1[
  28471. // interp index is i2 to progress in range [v0,v2[
  28472. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  28473. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28474. //
  28475. //
  28476. // i2 v2
  28477. // ^ ^
  28478. // / / \
  28479. // / / \
  28480. // / / \
  28481. // / / (0,1) \
  28482. // / #---------\
  28483. // / / \ (0,0)'/ \
  28484. // / / \ / \
  28485. // / / \ / \
  28486. // / / (0,0) \ / (1,0) \
  28487. // / #---------#---------\
  28488. // v0 v1
  28489. //
  28490. // --------------------> i1
  28491. //
  28492. // interp of (i1,i2):
  28493. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  28494. // along i1 : lerp(x0,x1, i1/(S-i2))
  28495. //
  28496. // centroid of triangle is needed to get help normal computation
  28497. // (c1,c2) are used for centroid location
  28498. var interp_vertex = function (i1, i2, c1, c2) {
  28499. // vertex is interpolated from
  28500. // - face_vertex_pos[0..2]
  28501. // - face_vertex_uv[0..2]
  28502. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  28503. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  28504. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  28505. pos_interp.normalize();
  28506. var vertex_normal;
  28507. if (flat) {
  28508. // in flat mode, recalculate normal as face centroid normal
  28509. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  28510. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  28511. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  28512. }
  28513. else {
  28514. // in smooth mode, recalculate normal from each single vertex position
  28515. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  28516. }
  28517. // Vertex normal need correction due to X,Y,Z radius scaling
  28518. vertex_normal.x /= radiusX;
  28519. vertex_normal.y /= radiusY;
  28520. vertex_normal.z /= radiusZ;
  28521. vertex_normal.normalize();
  28522. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  28523. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  28524. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  28525. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  28526. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  28527. uvs.push(uv_interp.x, uv_interp.y);
  28528. // push each vertex has member of a face
  28529. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  28530. indices.push(current_indice);
  28531. current_indice++;
  28532. };
  28533. for (var i2 = 0; i2 < subdivisions; i2++) {
  28534. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  28535. // face : (i1,i2) for /\ :
  28536. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  28537. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28538. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28539. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28540. if (i1 + i2 + 1 < subdivisions) {
  28541. // face : (i1,i2)' for \/ :
  28542. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28543. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28544. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28545. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28546. }
  28547. }
  28548. }
  28549. }
  28550. // Sides
  28551. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28552. // Result
  28553. var vertexData = new VertexData();
  28554. vertexData.indices = indices;
  28555. vertexData.positions = positions;
  28556. vertexData.normals = normals;
  28557. vertexData.uvs = uvs;
  28558. return vertexData;
  28559. };
  28560. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  28561. /**
  28562. * Creates the VertexData of the Polyhedron.
  28563. */
  28564. VertexData.CreatePolyhedron = function (options) {
  28565. // provided polyhedron types :
  28566. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  28567. // 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)
  28568. var polyhedra = [];
  28569. 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]] };
  28570. 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]] };
  28571. polyhedra[2] = {
  28572. 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]],
  28573. 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]]
  28574. };
  28575. polyhedra[3] = {
  28576. 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]],
  28577. 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]]
  28578. };
  28579. polyhedra[4] = {
  28580. 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]],
  28581. 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]]
  28582. };
  28583. 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]] };
  28584. 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]] };
  28585. 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]] };
  28586. 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]] };
  28587. 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]] };
  28588. 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]] };
  28589. 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]] };
  28590. 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]] };
  28591. 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]] };
  28592. polyhedra[14] = {
  28593. 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]],
  28594. 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]]
  28595. };
  28596. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  28597. var size = options.size;
  28598. var sizeX = options.sizeX || size || 1;
  28599. var sizeY = options.sizeY || size || 1;
  28600. var sizeZ = options.sizeZ || size || 1;
  28601. var data = options.custom || polyhedra[type];
  28602. var nbfaces = data.face.length;
  28603. var faceUV = options.faceUV || new Array(nbfaces);
  28604. var faceColors = options.faceColors;
  28605. var flat = (options.flat === undefined) ? true : options.flat;
  28606. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28607. var positions = new Array();
  28608. var indices = new Array();
  28609. var normals = new Array();
  28610. var uvs = new Array();
  28611. var colors = new Array();
  28612. var index = 0;
  28613. var faceIdx = 0; // face cursor in the array "indexes"
  28614. var indexes = new Array();
  28615. var i = 0;
  28616. var f = 0;
  28617. var u, v, ang, x, y, tmp;
  28618. // default face colors and UV if undefined
  28619. if (flat) {
  28620. for (f = 0; f < nbfaces; f++) {
  28621. if (faceColors && faceColors[f] === undefined) {
  28622. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28623. }
  28624. if (faceUV && faceUV[f] === undefined) {
  28625. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28626. }
  28627. }
  28628. }
  28629. if (!flat) {
  28630. for (i = 0; i < data.vertex.length; i++) {
  28631. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  28632. uvs.push(0, 0);
  28633. }
  28634. for (f = 0; f < nbfaces; f++) {
  28635. for (i = 0; i < data.face[f].length - 2; i++) {
  28636. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  28637. }
  28638. }
  28639. }
  28640. else {
  28641. for (f = 0; f < nbfaces; f++) {
  28642. var fl = data.face[f].length; // number of vertices of the current face
  28643. ang = 2 * Math.PI / fl;
  28644. x = 0.5 * Math.tan(ang / 2);
  28645. y = 0.5;
  28646. // positions, uvs, colors
  28647. for (i = 0; i < fl; i++) {
  28648. // positions
  28649. 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);
  28650. indexes.push(index);
  28651. index++;
  28652. // uvs
  28653. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  28654. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  28655. uvs.push(u, v);
  28656. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  28657. y = x * Math.sin(ang) + y * Math.cos(ang);
  28658. x = tmp;
  28659. // colors
  28660. if (faceColors) {
  28661. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  28662. }
  28663. }
  28664. // indices from indexes
  28665. for (i = 0; i < fl - 2; i++) {
  28666. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  28667. }
  28668. faceIdx += fl;
  28669. }
  28670. }
  28671. VertexData.ComputeNormals(positions, indices, normals);
  28672. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28673. var vertexData = new VertexData();
  28674. vertexData.positions = positions;
  28675. vertexData.indices = indices;
  28676. vertexData.normals = normals;
  28677. vertexData.uvs = uvs;
  28678. if (faceColors && flat) {
  28679. vertexData.colors = colors;
  28680. }
  28681. return vertexData;
  28682. };
  28683. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  28684. /**
  28685. * Creates the VertexData of the Torus Knot.
  28686. */
  28687. VertexData.CreateTorusKnot = function (options) {
  28688. var indices = new Array();
  28689. var positions = new Array();
  28690. var normals = new Array();
  28691. var uvs = new Array();
  28692. var radius = options.radius || 2;
  28693. var tube = options.tube || 0.5;
  28694. var radialSegments = options.radialSegments || 32;
  28695. var tubularSegments = options.tubularSegments || 32;
  28696. var p = options.p || 2;
  28697. var q = options.q || 3;
  28698. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28699. // Helper
  28700. var getPos = function (angle) {
  28701. var cu = Math.cos(angle);
  28702. var su = Math.sin(angle);
  28703. var quOverP = q / p * angle;
  28704. var cs = Math.cos(quOverP);
  28705. var tx = radius * (2 + cs) * 0.5 * cu;
  28706. var ty = radius * (2 + cs) * su * 0.5;
  28707. var tz = radius * Math.sin(quOverP) * 0.5;
  28708. return new BABYLON.Vector3(tx, ty, tz);
  28709. };
  28710. // Vertices
  28711. var i;
  28712. var j;
  28713. for (i = 0; i <= radialSegments; i++) {
  28714. var modI = i % radialSegments;
  28715. var u = modI / radialSegments * 2 * p * Math.PI;
  28716. var p1 = getPos(u);
  28717. var p2 = getPos(u + 0.01);
  28718. var tang = p2.subtract(p1);
  28719. var n = p2.add(p1);
  28720. var bitan = BABYLON.Vector3.Cross(tang, n);
  28721. n = BABYLON.Vector3.Cross(bitan, tang);
  28722. bitan.normalize();
  28723. n.normalize();
  28724. for (j = 0; j < tubularSegments; j++) {
  28725. var modJ = j % tubularSegments;
  28726. var v = modJ / tubularSegments * 2 * Math.PI;
  28727. var cx = -tube * Math.cos(v);
  28728. var cy = tube * Math.sin(v);
  28729. positions.push(p1.x + cx * n.x + cy * bitan.x);
  28730. positions.push(p1.y + cx * n.y + cy * bitan.y);
  28731. positions.push(p1.z + cx * n.z + cy * bitan.z);
  28732. uvs.push(i / radialSegments);
  28733. uvs.push(j / tubularSegments);
  28734. }
  28735. }
  28736. for (i = 0; i < radialSegments; i++) {
  28737. for (j = 0; j < tubularSegments; j++) {
  28738. var jNext = (j + 1) % tubularSegments;
  28739. var a = i * tubularSegments + j;
  28740. var b = (i + 1) * tubularSegments + j;
  28741. var c = (i + 1) * tubularSegments + jNext;
  28742. var d = i * tubularSegments + jNext;
  28743. indices.push(d);
  28744. indices.push(b);
  28745. indices.push(a);
  28746. indices.push(d);
  28747. indices.push(c);
  28748. indices.push(b);
  28749. }
  28750. }
  28751. // Normals
  28752. VertexData.ComputeNormals(positions, indices, normals);
  28753. // Sides
  28754. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28755. // Result
  28756. var vertexData = new VertexData();
  28757. vertexData.indices = indices;
  28758. vertexData.positions = positions;
  28759. vertexData.normals = normals;
  28760. vertexData.uvs = uvs;
  28761. return vertexData;
  28762. };
  28763. // Tools
  28764. /**
  28765. * @param {any} - positions (number[] or Float32Array)
  28766. * @param {any} - indices (number[] or Uint16Array)
  28767. * @param {any} - normals (number[] or Float32Array)
  28768. * options (optional) :
  28769. * facetPositions : optional array of facet positions (vector3)
  28770. * facetNormals : optional array of facet normals (vector3)
  28771. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  28772. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  28773. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  28774. * bbSize : optional bounding box size data, required for facetPartitioning computation
  28775. * bInfo : optional bounding info, required for facetPartitioning computation
  28776. */
  28777. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  28778. // temporary scalar variables
  28779. var index = 0; // facet index
  28780. var p1p2x = 0.0; // p1p2 vector x coordinate
  28781. var p1p2y = 0.0; // p1p2 vector y coordinate
  28782. var p1p2z = 0.0; // p1p2 vector z coordinate
  28783. var p3p2x = 0.0; // p3p2 vector x coordinate
  28784. var p3p2y = 0.0; // p3p2 vector y coordinate
  28785. var p3p2z = 0.0; // p3p2 vector z coordinate
  28786. var faceNormalx = 0.0; // facet normal x coordinate
  28787. var faceNormaly = 0.0; // facet normal y coordinate
  28788. var faceNormalz = 0.0; // facet normal z coordinate
  28789. var length = 0.0; // facet normal length before normalization
  28790. var v1x = 0; // vector1 x index in the positions array
  28791. var v1y = 0; // vector1 y index in the positions array
  28792. var v1z = 0; // vector1 z index in the positions array
  28793. var v2x = 0; // vector2 x index in the positions array
  28794. var v2y = 0; // vector2 y index in the positions array
  28795. var v2z = 0; // vector2 z index in the positions array
  28796. var v3x = 0; // vector3 x index in the positions array
  28797. var v3y = 0; // vector3 y index in the positions array
  28798. var v3z = 0; // vector3 z index in the positions array
  28799. var computeFacetNormals = false;
  28800. var computeFacetPositions = false;
  28801. var computeFacetPartitioning = false;
  28802. var faceNormalSign = 1;
  28803. if (options) {
  28804. computeFacetNormals = (options.facetNormals) ? true : false;
  28805. computeFacetPositions = (options.facetPositions) ? true : false;
  28806. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  28807. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  28808. }
  28809. // facetPartitioning reinit if needed
  28810. if (computeFacetPartitioning) {
  28811. var ox = 0; // X partitioning index for facet position
  28812. var oy = 0; // Y partinioning index for facet position
  28813. var oz = 0; // Z partinioning index for facet position
  28814. var b1x = 0; // X partitioning index for facet v1 vertex
  28815. var b1y = 0; // Y partitioning index for facet v1 vertex
  28816. var b1z = 0; // z partitioning index for facet v1 vertex
  28817. var b2x = 0; // X partitioning index for facet v2 vertex
  28818. var b2y = 0; // Y partitioning index for facet v2 vertex
  28819. var b2z = 0; // Z partitioning index for facet v2 vertex
  28820. var b3x = 0; // X partitioning index for facet v3 vertex
  28821. var b3y = 0; // Y partitioning index for facet v3 vertex
  28822. var b3z = 0; // Z partitioning index for facet v3 vertex
  28823. var block_idx_o = 0; // facet barycenter block index
  28824. var block_idx_v1 = 0; // v1 vertex block index
  28825. var block_idx_v2 = 0; // v2 vertex block index
  28826. var block_idx_v3 = 0; // v3 vertex block index
  28827. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  28828. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  28829. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  28830. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  28831. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  28832. var subSq = options.subDiv.max * options.subDiv.max;
  28833. options.facetPartitioning.length = 0;
  28834. }
  28835. // reset the normals
  28836. for (index = 0; index < positions.length; index++) {
  28837. normals[index] = 0.0;
  28838. }
  28839. // Loop : 1 indice triplet = 1 facet
  28840. var nbFaces = indices.length / 3;
  28841. for (index = 0; index < nbFaces; index++) {
  28842. // get the indexes of the coordinates of each vertex of the facet
  28843. v1x = indices[index * 3] * 3;
  28844. v1y = v1x + 1;
  28845. v1z = v1x + 2;
  28846. v2x = indices[index * 3 + 1] * 3;
  28847. v2y = v2x + 1;
  28848. v2z = v2x + 2;
  28849. v3x = indices[index * 3 + 2] * 3;
  28850. v3y = v3x + 1;
  28851. v3z = v3x + 2;
  28852. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  28853. p1p2y = positions[v1y] - positions[v2y];
  28854. p1p2z = positions[v1z] - positions[v2z];
  28855. p3p2x = positions[v3x] - positions[v2x];
  28856. p3p2y = positions[v3y] - positions[v2y];
  28857. p3p2z = positions[v3z] - positions[v2z];
  28858. // compute the face normal with the cross product
  28859. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  28860. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  28861. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  28862. // normalize this normal and store it in the array facetData
  28863. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28864. length = (length === 0) ? 1.0 : length;
  28865. faceNormalx /= length;
  28866. faceNormaly /= length;
  28867. faceNormalz /= length;
  28868. if (computeFacetNormals) {
  28869. options.facetNormals[index].x = faceNormalx;
  28870. options.facetNormals[index].y = faceNormaly;
  28871. options.facetNormals[index].z = faceNormalz;
  28872. }
  28873. if (computeFacetPositions) {
  28874. // compute and the facet barycenter coordinates in the array facetPositions
  28875. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  28876. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  28877. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  28878. }
  28879. if (computeFacetPartitioning) {
  28880. // store the facet indexes in arrays in the main facetPartitioning array :
  28881. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  28882. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28883. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28884. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28885. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28886. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28887. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28888. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28889. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28890. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28891. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28892. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28893. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28894. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  28895. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  28896. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  28897. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  28898. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  28899. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  28900. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  28901. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  28902. // push each facet index in each block containing the vertex
  28903. options.facetPartitioning[block_idx_v1].push(index);
  28904. if (block_idx_v2 != block_idx_v1) {
  28905. options.facetPartitioning[block_idx_v2].push(index);
  28906. }
  28907. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  28908. options.facetPartitioning[block_idx_v3].push(index);
  28909. }
  28910. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  28911. options.facetPartitioning[block_idx_o].push(index);
  28912. }
  28913. }
  28914. // compute the normals anyway
  28915. normals[v1x] += faceNormalx; // accumulate all the normals per face
  28916. normals[v1y] += faceNormaly;
  28917. normals[v1z] += faceNormalz;
  28918. normals[v2x] += faceNormalx;
  28919. normals[v2y] += faceNormaly;
  28920. normals[v2z] += faceNormalz;
  28921. normals[v3x] += faceNormalx;
  28922. normals[v3y] += faceNormaly;
  28923. normals[v3z] += faceNormalz;
  28924. }
  28925. // last normalization of each normal
  28926. for (index = 0; index < normals.length / 3; index++) {
  28927. faceNormalx = normals[index * 3];
  28928. faceNormaly = normals[index * 3 + 1];
  28929. faceNormalz = normals[index * 3 + 2];
  28930. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28931. length = (length === 0) ? 1.0 : length;
  28932. faceNormalx /= length;
  28933. faceNormaly /= length;
  28934. faceNormalz /= length;
  28935. normals[index * 3] = faceNormalx;
  28936. normals[index * 3 + 1] = faceNormaly;
  28937. normals[index * 3 + 2] = faceNormalz;
  28938. }
  28939. };
  28940. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  28941. var li = indices.length;
  28942. var ln = normals.length;
  28943. var i;
  28944. var n;
  28945. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28946. switch (sideOrientation) {
  28947. case BABYLON.Mesh.FRONTSIDE:
  28948. // nothing changed
  28949. break;
  28950. case BABYLON.Mesh.BACKSIDE:
  28951. var tmp;
  28952. // indices
  28953. for (i = 0; i < li; i += 3) {
  28954. tmp = indices[i];
  28955. indices[i] = indices[i + 2];
  28956. indices[i + 2] = tmp;
  28957. }
  28958. // normals
  28959. for (n = 0; n < ln; n++) {
  28960. normals[n] = -normals[n];
  28961. }
  28962. break;
  28963. case BABYLON.Mesh.DOUBLESIDE:
  28964. // positions
  28965. var lp = positions.length;
  28966. var l = lp / 3;
  28967. for (var p = 0; p < lp; p++) {
  28968. positions[lp + p] = positions[p];
  28969. }
  28970. // indices
  28971. for (i = 0; i < li; i += 3) {
  28972. indices[i + li] = indices[i + 2] + l;
  28973. indices[i + 1 + li] = indices[i + 1] + l;
  28974. indices[i + 2 + li] = indices[i] + l;
  28975. }
  28976. // normals
  28977. for (n = 0; n < ln; n++) {
  28978. normals[ln + n] = -normals[n];
  28979. }
  28980. // uvs
  28981. var lu = uvs.length;
  28982. var u = 0;
  28983. for (u = 0; u < lu; u++) {
  28984. uvs[u + lu] = uvs[u];
  28985. }
  28986. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28987. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28988. u = 0;
  28989. for (i = 0; i < lu / 2; i++) {
  28990. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  28991. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  28992. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  28993. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  28994. u += 2;
  28995. }
  28996. break;
  28997. }
  28998. };
  28999. /**
  29000. * Creates a new VertexData from the imported parameters.
  29001. */
  29002. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  29003. var vertexData = new VertexData();
  29004. // positions
  29005. var positions = parsedVertexData.positions;
  29006. if (positions) {
  29007. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  29008. }
  29009. // normals
  29010. var normals = parsedVertexData.normals;
  29011. if (normals) {
  29012. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  29013. }
  29014. // tangents
  29015. var tangents = parsedVertexData.tangents;
  29016. if (tangents) {
  29017. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  29018. }
  29019. // uvs
  29020. var uvs = parsedVertexData.uvs;
  29021. if (uvs) {
  29022. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  29023. }
  29024. // uv2s
  29025. var uv2s = parsedVertexData.uv2s;
  29026. if (uv2s) {
  29027. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  29028. }
  29029. // uv3s
  29030. var uv3s = parsedVertexData.uv3s;
  29031. if (uv3s) {
  29032. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  29033. }
  29034. // uv4s
  29035. var uv4s = parsedVertexData.uv4s;
  29036. if (uv4s) {
  29037. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  29038. }
  29039. // uv5s
  29040. var uv5s = parsedVertexData.uv5s;
  29041. if (uv5s) {
  29042. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  29043. }
  29044. // uv6s
  29045. var uv6s = parsedVertexData.uv6s;
  29046. if (uv6s) {
  29047. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  29048. }
  29049. // colors
  29050. var colors = parsedVertexData.colors;
  29051. if (colors) {
  29052. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  29053. }
  29054. // matricesIndices
  29055. var matricesIndices = parsedVertexData.matricesIndices;
  29056. if (matricesIndices) {
  29057. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  29058. }
  29059. // matricesWeights
  29060. var matricesWeights = parsedVertexData.matricesWeights;
  29061. if (matricesWeights) {
  29062. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  29063. }
  29064. // indices
  29065. var indices = parsedVertexData.indices;
  29066. if (indices) {
  29067. vertexData.indices = indices;
  29068. }
  29069. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  29070. };
  29071. return VertexData;
  29072. }());
  29073. BABYLON.VertexData = VertexData;
  29074. })(BABYLON || (BABYLON = {}));
  29075. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  29076. var BABYLON;
  29077. (function (BABYLON) {
  29078. var Geometry = (function () {
  29079. function Geometry(id, scene, vertexData, updatable, mesh) {
  29080. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29081. this._totalVertices = 0;
  29082. this._isDisposed = false;
  29083. this.id = id;
  29084. this._engine = scene.getEngine();
  29085. this._meshes = [];
  29086. this._scene = scene;
  29087. //Init vertex buffer cache
  29088. this._vertexBuffers = {};
  29089. this._indices = [];
  29090. this._updatable = updatable;
  29091. // vertexData
  29092. if (vertexData) {
  29093. this.setAllVerticesData(vertexData, updatable);
  29094. }
  29095. else {
  29096. this._totalVertices = 0;
  29097. this._indices = [];
  29098. }
  29099. if (this._engine.getCaps().vertexArrayObject) {
  29100. this._vertexArrayObjects = {};
  29101. }
  29102. // applyToMesh
  29103. if (mesh) {
  29104. if (mesh.getClassName() === "LinesMesh") {
  29105. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  29106. this.updateExtend();
  29107. }
  29108. this.applyToMesh(mesh);
  29109. mesh.computeWorldMatrix(true);
  29110. }
  29111. }
  29112. Object.defineProperty(Geometry.prototype, "boundingBias", {
  29113. /**
  29114. * 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
  29115. * @returns The Bias Vector
  29116. */
  29117. get: function () {
  29118. return this._boundingBias;
  29119. },
  29120. set: function (value) {
  29121. if (this._boundingBias && this._boundingBias.equals(value)) {
  29122. return;
  29123. }
  29124. this._boundingBias = value.clone();
  29125. this.updateBoundingInfo(true, null);
  29126. },
  29127. enumerable: true,
  29128. configurable: true
  29129. });
  29130. Object.defineProperty(Geometry.prototype, "extend", {
  29131. get: function () {
  29132. return this._extend;
  29133. },
  29134. enumerable: true,
  29135. configurable: true
  29136. });
  29137. Geometry.prototype.getScene = function () {
  29138. return this._scene;
  29139. };
  29140. Geometry.prototype.getEngine = function () {
  29141. return this._engine;
  29142. };
  29143. Geometry.prototype.isReady = function () {
  29144. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  29145. };
  29146. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  29147. get: function () {
  29148. for (var index = 0; index < this._meshes.length; index++) {
  29149. if (!this._meshes[index].doNotSerialize) {
  29150. return false;
  29151. }
  29152. }
  29153. return true;
  29154. },
  29155. enumerable: true,
  29156. configurable: true
  29157. });
  29158. Geometry.prototype._rebuild = function () {
  29159. if (this._vertexArrayObjects) {
  29160. this._vertexArrayObjects = {};
  29161. }
  29162. // Index buffer
  29163. if (this._meshes.length !== 0 && this._indices) {
  29164. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29165. }
  29166. // Vertex buffers
  29167. for (var key in this._vertexBuffers) {
  29168. var vertexBuffer = this._vertexBuffers[key];
  29169. vertexBuffer._rebuild();
  29170. }
  29171. };
  29172. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  29173. vertexData.applyToGeometry(this, updatable);
  29174. this.notifyUpdate();
  29175. };
  29176. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  29177. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  29178. this.setVerticesBuffer(buffer);
  29179. };
  29180. Geometry.prototype.removeVerticesData = function (kind) {
  29181. if (this._vertexBuffers[kind]) {
  29182. this._vertexBuffers[kind].dispose();
  29183. delete this._vertexBuffers[kind];
  29184. }
  29185. };
  29186. Geometry.prototype.setVerticesBuffer = function (buffer) {
  29187. var kind = buffer.getKind();
  29188. if (this._vertexBuffers[kind]) {
  29189. this._vertexBuffers[kind].dispose();
  29190. }
  29191. this._vertexBuffers[kind] = buffer;
  29192. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29193. var data = buffer.getData();
  29194. var stride = buffer.getStrideSize();
  29195. this._totalVertices = data.length / stride;
  29196. this.updateExtend(data, stride);
  29197. this._resetPointsArrayCache();
  29198. var meshes = this._meshes;
  29199. var numOfMeshes = meshes.length;
  29200. for (var index = 0; index < numOfMeshes; index++) {
  29201. var mesh = meshes[index];
  29202. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29203. mesh._createGlobalSubMesh(false);
  29204. mesh.computeWorldMatrix(true);
  29205. }
  29206. }
  29207. this.notifyUpdate(kind);
  29208. if (this._vertexArrayObjects) {
  29209. this._disposeVertexArrayObjects();
  29210. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  29211. }
  29212. };
  29213. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  29214. var vertexBuffer = this.getVertexBuffer(kind);
  29215. if (!vertexBuffer) {
  29216. return;
  29217. }
  29218. vertexBuffer.updateDirectly(data, offset);
  29219. this.notifyUpdate(kind);
  29220. };
  29221. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  29222. var vertexBuffer = this.getVertexBuffer(kind);
  29223. if (!vertexBuffer) {
  29224. return;
  29225. }
  29226. vertexBuffer.update(data);
  29227. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29228. var stride = vertexBuffer.getStrideSize();
  29229. this._totalVertices = data.length / stride;
  29230. this.updateBoundingInfo(updateExtends, data);
  29231. }
  29232. this.notifyUpdate(kind);
  29233. };
  29234. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  29235. if (updateExtends) {
  29236. this.updateExtend(data);
  29237. }
  29238. var meshes = this._meshes;
  29239. var numOfMeshes = meshes.length;
  29240. this._resetPointsArrayCache();
  29241. for (var index = 0; index < numOfMeshes; index++) {
  29242. var mesh = meshes[index];
  29243. if (updateExtends) {
  29244. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29245. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  29246. var subMesh = mesh.subMeshes[subIndex];
  29247. subMesh.refreshBoundingInfo();
  29248. }
  29249. }
  29250. }
  29251. };
  29252. Geometry.prototype._bind = function (effect, indexToBind) {
  29253. if (indexToBind === void 0) { indexToBind = undefined; }
  29254. if (indexToBind === undefined) {
  29255. indexToBind = this._indexBuffer;
  29256. }
  29257. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  29258. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  29259. return;
  29260. }
  29261. // Using VAO
  29262. if (!this._vertexArrayObjects[effect.key]) {
  29263. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  29264. }
  29265. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  29266. };
  29267. Geometry.prototype.getTotalVertices = function () {
  29268. if (!this.isReady()) {
  29269. return 0;
  29270. }
  29271. return this._totalVertices;
  29272. };
  29273. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  29274. var vertexBuffer = this.getVertexBuffer(kind);
  29275. if (!vertexBuffer) {
  29276. return null;
  29277. }
  29278. var orig = vertexBuffer.getData();
  29279. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  29280. return orig;
  29281. }
  29282. else {
  29283. var len = orig.length;
  29284. var copy = [];
  29285. for (var i = 0; i < len; i++) {
  29286. copy.push(orig[i]);
  29287. }
  29288. return copy;
  29289. }
  29290. };
  29291. Geometry.prototype.getVertexBuffer = function (kind) {
  29292. if (!this.isReady()) {
  29293. return null;
  29294. }
  29295. return this._vertexBuffers[kind];
  29296. };
  29297. Geometry.prototype.getVertexBuffers = function () {
  29298. if (!this.isReady()) {
  29299. return null;
  29300. }
  29301. return this._vertexBuffers;
  29302. };
  29303. Geometry.prototype.isVerticesDataPresent = function (kind) {
  29304. if (!this._vertexBuffers) {
  29305. if (this._delayInfo) {
  29306. return this._delayInfo.indexOf(kind) !== -1;
  29307. }
  29308. return false;
  29309. }
  29310. return this._vertexBuffers[kind] !== undefined;
  29311. };
  29312. Geometry.prototype.getVerticesDataKinds = function () {
  29313. var result = [];
  29314. var kind;
  29315. if (!this._vertexBuffers && this._delayInfo) {
  29316. for (kind in this._delayInfo) {
  29317. result.push(kind);
  29318. }
  29319. }
  29320. else {
  29321. for (kind in this._vertexBuffers) {
  29322. result.push(kind);
  29323. }
  29324. }
  29325. return result;
  29326. };
  29327. Geometry.prototype.setIndices = function (indices, totalVertices) {
  29328. if (this._indexBuffer) {
  29329. this._engine._releaseBuffer(this._indexBuffer);
  29330. }
  29331. this._disposeVertexArrayObjects();
  29332. this._indices = indices;
  29333. if (this._meshes.length !== 0 && this._indices) {
  29334. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29335. }
  29336. if (totalVertices !== undefined) {
  29337. this._totalVertices = totalVertices;
  29338. }
  29339. var meshes = this._meshes;
  29340. var numOfMeshes = meshes.length;
  29341. for (var index = 0; index < numOfMeshes; index++) {
  29342. meshes[index]._createGlobalSubMesh(true);
  29343. }
  29344. this.notifyUpdate();
  29345. };
  29346. Geometry.prototype.getTotalIndices = function () {
  29347. if (!this.isReady()) {
  29348. return 0;
  29349. }
  29350. return this._indices.length;
  29351. };
  29352. Geometry.prototype.getIndices = function (copyWhenShared) {
  29353. if (!this.isReady()) {
  29354. return null;
  29355. }
  29356. var orig = this._indices;
  29357. if (!copyWhenShared || this._meshes.length === 1) {
  29358. return orig;
  29359. }
  29360. else {
  29361. var len = orig.length;
  29362. var copy = [];
  29363. for (var i = 0; i < len; i++) {
  29364. copy.push(orig[i]);
  29365. }
  29366. return copy;
  29367. }
  29368. };
  29369. Geometry.prototype.getIndexBuffer = function () {
  29370. if (!this.isReady()) {
  29371. return null;
  29372. }
  29373. return this._indexBuffer;
  29374. };
  29375. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  29376. if (!effect || !this._vertexArrayObjects) {
  29377. return;
  29378. }
  29379. if (this._vertexArrayObjects[effect.key]) {
  29380. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  29381. delete this._vertexArrayObjects[effect.key];
  29382. }
  29383. };
  29384. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  29385. var meshes = this._meshes;
  29386. var index = meshes.indexOf(mesh);
  29387. if (index === -1) {
  29388. return;
  29389. }
  29390. meshes.splice(index, 1);
  29391. mesh._geometry = null;
  29392. if (meshes.length === 0 && shouldDispose) {
  29393. this.dispose();
  29394. }
  29395. };
  29396. Geometry.prototype.applyToMesh = function (mesh) {
  29397. if (mesh._geometry === this) {
  29398. return;
  29399. }
  29400. var previousGeometry = mesh._geometry;
  29401. if (previousGeometry) {
  29402. previousGeometry.releaseForMesh(mesh);
  29403. }
  29404. var meshes = this._meshes;
  29405. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  29406. mesh._geometry = this;
  29407. this._scene.pushGeometry(this);
  29408. meshes.push(mesh);
  29409. if (this.isReady()) {
  29410. this._applyToMesh(mesh);
  29411. }
  29412. else {
  29413. mesh._boundingInfo = this._boundingInfo;
  29414. }
  29415. };
  29416. Geometry.prototype.updateExtend = function (data, stride) {
  29417. if (data === void 0) { data = null; }
  29418. if (!data) {
  29419. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  29420. }
  29421. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  29422. };
  29423. Geometry.prototype._applyToMesh = function (mesh) {
  29424. var numOfMeshes = this._meshes.length;
  29425. // vertexBuffers
  29426. for (var kind in this._vertexBuffers) {
  29427. if (numOfMeshes === 1) {
  29428. this._vertexBuffers[kind].create();
  29429. }
  29430. var buffer = this._vertexBuffers[kind].getBuffer();
  29431. if (buffer)
  29432. buffer.references = numOfMeshes;
  29433. if (kind === BABYLON.VertexBuffer.PositionKind) {
  29434. if (!this._extend) {
  29435. this.updateExtend(this._vertexBuffers[kind].getData());
  29436. }
  29437. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29438. mesh._createGlobalSubMesh(false);
  29439. //bounding info was just created again, world matrix should be applied again.
  29440. mesh._updateBoundingInfo();
  29441. }
  29442. }
  29443. // indexBuffer
  29444. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  29445. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  29446. }
  29447. if (this._indexBuffer) {
  29448. this._indexBuffer.references = numOfMeshes;
  29449. }
  29450. };
  29451. Geometry.prototype.notifyUpdate = function (kind) {
  29452. if (this.onGeometryUpdated) {
  29453. this.onGeometryUpdated(this, kind);
  29454. }
  29455. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  29456. var mesh = _a[_i];
  29457. mesh._markSubMeshesAsAttributesDirty();
  29458. }
  29459. };
  29460. Geometry.prototype.load = function (scene, onLoaded) {
  29461. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29462. return;
  29463. }
  29464. if (this.isReady()) {
  29465. if (onLoaded) {
  29466. onLoaded();
  29467. }
  29468. return;
  29469. }
  29470. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29471. this._queueLoad(scene, onLoaded);
  29472. };
  29473. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  29474. var _this = this;
  29475. scene._addPendingData(this);
  29476. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29477. _this._delayLoadingFunction(JSON.parse(data), _this);
  29478. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29479. _this._delayInfo = [];
  29480. scene._removePendingData(_this);
  29481. var meshes = _this._meshes;
  29482. var numOfMeshes = meshes.length;
  29483. for (var index = 0; index < numOfMeshes; index++) {
  29484. _this._applyToMesh(meshes[index]);
  29485. }
  29486. if (onLoaded) {
  29487. onLoaded();
  29488. }
  29489. }, function () { }, scene.database);
  29490. };
  29491. /**
  29492. * Invert the geometry to move from a right handed system to a left handed one.
  29493. */
  29494. Geometry.prototype.toLeftHanded = function () {
  29495. // Flip faces
  29496. var tIndices = this.getIndices(false);
  29497. if (tIndices != null && tIndices.length > 0) {
  29498. for (var i = 0; i < tIndices.length; i += 3) {
  29499. var tTemp = tIndices[i + 0];
  29500. tIndices[i + 0] = tIndices[i + 2];
  29501. tIndices[i + 2] = tTemp;
  29502. }
  29503. this.setIndices(tIndices);
  29504. }
  29505. // Negate position.z
  29506. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  29507. if (tPositions != null && tPositions.length > 0) {
  29508. for (var i = 0; i < tPositions.length; i += 3) {
  29509. tPositions[i + 2] = -tPositions[i + 2];
  29510. }
  29511. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  29512. }
  29513. // Negate normal.z
  29514. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  29515. if (tNormals != null && tNormals.length > 0) {
  29516. for (var i = 0; i < tNormals.length; i += 3) {
  29517. tNormals[i + 2] = -tNormals[i + 2];
  29518. }
  29519. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  29520. }
  29521. };
  29522. // Cache
  29523. Geometry.prototype._resetPointsArrayCache = function () {
  29524. this._positions = null;
  29525. };
  29526. Geometry.prototype._generatePointsArray = function () {
  29527. if (this._positions)
  29528. return true;
  29529. this._positions = [];
  29530. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29531. if (!data) {
  29532. return false;
  29533. }
  29534. for (var index = 0; index < data.length; index += 3) {
  29535. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  29536. }
  29537. return true;
  29538. };
  29539. Geometry.prototype.isDisposed = function () {
  29540. return this._isDisposed;
  29541. };
  29542. Geometry.prototype._disposeVertexArrayObjects = function () {
  29543. if (this._vertexArrayObjects) {
  29544. for (var kind in this._vertexArrayObjects) {
  29545. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  29546. }
  29547. this._vertexArrayObjects = {};
  29548. }
  29549. };
  29550. Geometry.prototype.dispose = function () {
  29551. var meshes = this._meshes;
  29552. var numOfMeshes = meshes.length;
  29553. var index;
  29554. for (index = 0; index < numOfMeshes; index++) {
  29555. this.releaseForMesh(meshes[index]);
  29556. }
  29557. this._meshes = [];
  29558. this._disposeVertexArrayObjects();
  29559. for (var kind in this._vertexBuffers) {
  29560. this._vertexBuffers[kind].dispose();
  29561. }
  29562. this._vertexBuffers = {};
  29563. this._totalVertices = 0;
  29564. if (this._indexBuffer) {
  29565. this._engine._releaseBuffer(this._indexBuffer);
  29566. }
  29567. this._indexBuffer = null;
  29568. this._indices = [];
  29569. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29570. this.delayLoadingFile = null;
  29571. this._delayLoadingFunction = null;
  29572. this._delayInfo = [];
  29573. this._boundingInfo = null;
  29574. this._scene.removeGeometry(this);
  29575. this._isDisposed = true;
  29576. };
  29577. Geometry.prototype.copy = function (id) {
  29578. var vertexData = new BABYLON.VertexData();
  29579. vertexData.indices = [];
  29580. var indices = this.getIndices();
  29581. for (var index = 0; index < indices.length; index++) {
  29582. vertexData.indices.push(indices[index]);
  29583. }
  29584. var updatable = false;
  29585. var stopChecking = false;
  29586. var kind;
  29587. for (kind in this._vertexBuffers) {
  29588. // using slice() to make a copy of the array and not just reference it
  29589. var data = this.getVerticesData(kind);
  29590. if (data instanceof Float32Array) {
  29591. vertexData.set(new Float32Array(data), kind);
  29592. }
  29593. else {
  29594. vertexData.set(data.slice(0), kind);
  29595. }
  29596. if (!stopChecking) {
  29597. updatable = this.getVertexBuffer(kind).isUpdatable();
  29598. stopChecking = !updatable;
  29599. }
  29600. }
  29601. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  29602. geometry.delayLoadState = this.delayLoadState;
  29603. geometry.delayLoadingFile = this.delayLoadingFile;
  29604. geometry._delayLoadingFunction = this._delayLoadingFunction;
  29605. for (kind in this._delayInfo) {
  29606. geometry._delayInfo = geometry._delayInfo || [];
  29607. geometry._delayInfo.push(kind);
  29608. }
  29609. // Bounding info
  29610. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  29611. return geometry;
  29612. };
  29613. Geometry.prototype.serialize = function () {
  29614. var serializationObject = {};
  29615. serializationObject.id = this.id;
  29616. serializationObject.updatable = this._updatable;
  29617. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29618. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29619. }
  29620. return serializationObject;
  29621. };
  29622. Geometry.prototype.toNumberArray = function (origin) {
  29623. if (Array.isArray(origin)) {
  29624. return origin;
  29625. }
  29626. else {
  29627. return Array.prototype.slice.call(origin);
  29628. }
  29629. };
  29630. Geometry.prototype.serializeVerticeData = function () {
  29631. var serializationObject = this.serialize();
  29632. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29633. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  29634. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  29635. serializationObject.positions._updatable = true;
  29636. }
  29637. }
  29638. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29639. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  29640. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  29641. serializationObject.normals._updatable = true;
  29642. }
  29643. }
  29644. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29645. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  29646. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  29647. serializationObject.uvs._updatable = true;
  29648. }
  29649. }
  29650. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29651. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  29652. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  29653. serializationObject.uv2s._updatable = true;
  29654. }
  29655. }
  29656. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29657. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  29658. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  29659. serializationObject.uv3s._updatable = true;
  29660. }
  29661. }
  29662. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29663. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  29664. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  29665. serializationObject.uv4s._updatable = true;
  29666. }
  29667. }
  29668. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29669. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  29670. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  29671. serializationObject.uv5s._updatable = true;
  29672. }
  29673. }
  29674. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29675. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  29676. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  29677. serializationObject.uv6s._updatable = true;
  29678. }
  29679. }
  29680. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29681. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  29682. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  29683. serializationObject.colors._updatable = true;
  29684. }
  29685. }
  29686. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29687. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  29688. serializationObject.matricesIndices._isExpanded = true;
  29689. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  29690. serializationObject.matricesIndices._updatable = true;
  29691. }
  29692. }
  29693. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29694. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  29695. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  29696. serializationObject.matricesWeights._updatable = true;
  29697. }
  29698. }
  29699. serializationObject.indices = this.toNumberArray(this.getIndices());
  29700. return serializationObject;
  29701. };
  29702. // Statics
  29703. Geometry.ExtractFromMesh = function (mesh, id) {
  29704. var geometry = mesh._geometry;
  29705. if (!geometry) {
  29706. return null;
  29707. }
  29708. return geometry.copy(id);
  29709. };
  29710. /**
  29711. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  29712. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  29713. * Be aware Math.random() could cause collisions, but:
  29714. * "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"
  29715. */
  29716. Geometry.RandomId = function () {
  29717. return BABYLON.Tools.RandomId();
  29718. };
  29719. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  29720. var scene = mesh.getScene();
  29721. // Geometry
  29722. var geometryId = parsedGeometry.geometryId;
  29723. if (geometryId) {
  29724. var geometry = scene.getGeometryByID(geometryId);
  29725. if (geometry) {
  29726. geometry.applyToMesh(mesh);
  29727. }
  29728. }
  29729. else if (parsedGeometry instanceof ArrayBuffer) {
  29730. var binaryInfo = mesh._binaryInfo;
  29731. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  29732. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  29733. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  29734. }
  29735. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  29736. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  29737. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  29738. }
  29739. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  29740. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  29741. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  29742. }
  29743. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  29744. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  29745. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  29746. }
  29747. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  29748. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  29749. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  29750. }
  29751. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  29752. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  29753. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  29754. }
  29755. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  29756. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  29757. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  29758. }
  29759. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  29760. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  29761. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  29762. }
  29763. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  29764. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  29765. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  29766. }
  29767. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  29768. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  29769. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  29770. }
  29771. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  29772. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  29773. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  29774. }
  29775. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  29776. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  29777. mesh.setIndices(indicesData);
  29778. }
  29779. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  29780. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  29781. mesh.subMeshes = [];
  29782. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  29783. var materialIndex = subMeshesData[(i * 5) + 0];
  29784. var verticesStart = subMeshesData[(i * 5) + 1];
  29785. var verticesCount = subMeshesData[(i * 5) + 2];
  29786. var indexStart = subMeshesData[(i * 5) + 3];
  29787. var indexCount = subMeshesData[(i * 5) + 4];
  29788. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  29789. }
  29790. }
  29791. }
  29792. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  29793. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  29794. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  29795. if (parsedGeometry.uvs) {
  29796. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  29797. }
  29798. if (parsedGeometry.uvs2) {
  29799. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  29800. }
  29801. if (parsedGeometry.uvs3) {
  29802. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  29803. }
  29804. if (parsedGeometry.uvs4) {
  29805. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  29806. }
  29807. if (parsedGeometry.uvs5) {
  29808. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  29809. }
  29810. if (parsedGeometry.uvs6) {
  29811. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  29812. }
  29813. if (parsedGeometry.colors) {
  29814. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  29815. }
  29816. if (parsedGeometry.matricesIndices) {
  29817. if (!parsedGeometry.matricesIndices._isExpanded) {
  29818. var floatIndices = [];
  29819. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  29820. var matricesIndex = parsedGeometry.matricesIndices[i];
  29821. floatIndices.push(matricesIndex & 0x000000FF);
  29822. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29823. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29824. floatIndices.push(matricesIndex >> 24);
  29825. }
  29826. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  29827. }
  29828. else {
  29829. delete parsedGeometry.matricesIndices._isExpanded;
  29830. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  29831. }
  29832. }
  29833. if (parsedGeometry.matricesIndicesExtra) {
  29834. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  29835. var floatIndices = [];
  29836. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  29837. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  29838. floatIndices.push(matricesIndex & 0x000000FF);
  29839. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29840. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29841. floatIndices.push(matricesIndex >> 24);
  29842. }
  29843. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  29844. }
  29845. else {
  29846. delete parsedGeometry.matricesIndices._isExpanded;
  29847. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  29848. }
  29849. }
  29850. if (parsedGeometry.matricesWeights) {
  29851. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  29852. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  29853. }
  29854. if (parsedGeometry.matricesWeightsExtra) {
  29855. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  29856. }
  29857. mesh.setIndices(parsedGeometry.indices);
  29858. }
  29859. // SubMeshes
  29860. if (parsedGeometry.subMeshes) {
  29861. mesh.subMeshes = [];
  29862. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  29863. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  29864. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  29865. }
  29866. }
  29867. // Flat shading
  29868. if (mesh._shouldGenerateFlatShading) {
  29869. mesh.convertToFlatShadedMesh();
  29870. delete mesh._shouldGenerateFlatShading;
  29871. }
  29872. // Update
  29873. mesh.computeWorldMatrix(true);
  29874. // Octree
  29875. if (scene['_selectionOctree']) {
  29876. scene['_selectionOctree'].addMesh(mesh);
  29877. }
  29878. };
  29879. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  29880. var epsilon = 1e-3;
  29881. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  29882. return;
  29883. }
  29884. var noInfluenceBoneIndex = 0.0;
  29885. if (parsedGeometry.skeletonId > -1) {
  29886. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  29887. noInfluenceBoneIndex = skeleton.bones.length;
  29888. }
  29889. else {
  29890. return;
  29891. }
  29892. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29893. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  29894. var matricesWeights = parsedGeometry.matricesWeights;
  29895. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  29896. var influencers = parsedGeometry.numBoneInfluencer;
  29897. var size = matricesWeights.length;
  29898. for (var i = 0; i < size; i += 4) {
  29899. var weight = 0.0;
  29900. var firstZeroWeight = -1;
  29901. for (var j = 0; j < 4; j++) {
  29902. var w = matricesWeights[i + j];
  29903. weight += w;
  29904. if (w < epsilon && firstZeroWeight < 0) {
  29905. firstZeroWeight = j;
  29906. }
  29907. }
  29908. if (matricesWeightsExtra) {
  29909. for (var j = 0; j < 4; j++) {
  29910. var w = matricesWeightsExtra[i + j];
  29911. weight += w;
  29912. if (w < epsilon && firstZeroWeight < 0) {
  29913. firstZeroWeight = j + 4;
  29914. }
  29915. }
  29916. }
  29917. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  29918. firstZeroWeight = influencers - 1;
  29919. }
  29920. if (weight > epsilon) {
  29921. var mweight = 1.0 / weight;
  29922. for (var j = 0; j < 4; j++) {
  29923. matricesWeights[i + j] *= mweight;
  29924. }
  29925. if (matricesWeightsExtra) {
  29926. for (var j = 0; j < 4; j++) {
  29927. matricesWeightsExtra[i + j] *= mweight;
  29928. }
  29929. }
  29930. }
  29931. else {
  29932. if (firstZeroWeight >= 4) {
  29933. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  29934. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  29935. }
  29936. else {
  29937. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  29938. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  29939. }
  29940. }
  29941. }
  29942. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  29943. if (parsedGeometry.matricesWeightsExtra) {
  29944. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  29945. }
  29946. };
  29947. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  29948. if (scene.getGeometryByID(parsedVertexData.id)) {
  29949. return null; // null since geometry could be something else than a box...
  29950. }
  29951. var geometry = new Geometry(parsedVertexData.id, scene, null, parsedVertexData.updatable);
  29952. if (BABYLON.Tags) {
  29953. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  29954. }
  29955. if (parsedVertexData.delayLoadingFile) {
  29956. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29957. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  29958. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  29959. geometry._delayInfo = [];
  29960. if (parsedVertexData.hasUVs) {
  29961. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29962. }
  29963. if (parsedVertexData.hasUVs2) {
  29964. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29965. }
  29966. if (parsedVertexData.hasUVs3) {
  29967. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29968. }
  29969. if (parsedVertexData.hasUVs4) {
  29970. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29971. }
  29972. if (parsedVertexData.hasUVs5) {
  29973. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29974. }
  29975. if (parsedVertexData.hasUVs6) {
  29976. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29977. }
  29978. if (parsedVertexData.hasColors) {
  29979. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29980. }
  29981. if (parsedVertexData.hasMatricesIndices) {
  29982. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29983. }
  29984. if (parsedVertexData.hasMatricesWeights) {
  29985. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29986. }
  29987. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  29988. }
  29989. else {
  29990. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  29991. }
  29992. scene.pushGeometry(geometry, true);
  29993. return geometry;
  29994. };
  29995. return Geometry;
  29996. }());
  29997. BABYLON.Geometry = Geometry;
  29998. /////// Primitives //////////////////////////////////////////////
  29999. (function (Geometry) {
  30000. var Primitives;
  30001. (function (Primitives) {
  30002. /// Abstract class
  30003. var _Primitive = (function (_super) {
  30004. __extends(_Primitive, _super);
  30005. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  30006. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  30007. _this._canBeRegenerated = _canBeRegenerated;
  30008. _this._beingRegenerated = true;
  30009. _this.regenerate();
  30010. _this._beingRegenerated = false;
  30011. return _this;
  30012. }
  30013. _Primitive.prototype.canBeRegenerated = function () {
  30014. return this._canBeRegenerated;
  30015. };
  30016. _Primitive.prototype.regenerate = function () {
  30017. if (!this._canBeRegenerated) {
  30018. return;
  30019. }
  30020. this._beingRegenerated = true;
  30021. this.setAllVerticesData(this._regenerateVertexData(), false);
  30022. this._beingRegenerated = false;
  30023. };
  30024. _Primitive.prototype.asNewGeometry = function (id) {
  30025. return _super.prototype.copy.call(this, id);
  30026. };
  30027. // overrides
  30028. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  30029. if (!this._beingRegenerated) {
  30030. return;
  30031. }
  30032. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  30033. };
  30034. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  30035. if (!this._beingRegenerated) {
  30036. return;
  30037. }
  30038. _super.prototype.setVerticesData.call(this, kind, data, false);
  30039. };
  30040. // to override
  30041. // protected
  30042. _Primitive.prototype._regenerateVertexData = function () {
  30043. throw new Error("Abstract method");
  30044. };
  30045. _Primitive.prototype.copy = function (id) {
  30046. throw new Error("Must be overriden in sub-classes.");
  30047. };
  30048. _Primitive.prototype.serialize = function () {
  30049. var serializationObject = _super.prototype.serialize.call(this);
  30050. serializationObject.canBeRegenerated = this.canBeRegenerated();
  30051. return serializationObject;
  30052. };
  30053. return _Primitive;
  30054. }(Geometry));
  30055. Primitives._Primitive = _Primitive;
  30056. var Ribbon = (function (_super) {
  30057. __extends(Ribbon, _super);
  30058. // Members
  30059. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  30060. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30061. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30062. _this.pathArray = pathArray;
  30063. _this.closeArray = closeArray;
  30064. _this.closePath = closePath;
  30065. _this.offset = offset;
  30066. _this.side = side;
  30067. return _this;
  30068. }
  30069. Ribbon.prototype._regenerateVertexData = function () {
  30070. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  30071. };
  30072. Ribbon.prototype.copy = function (id) {
  30073. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  30074. };
  30075. return Ribbon;
  30076. }(_Primitive));
  30077. Primitives.Ribbon = Ribbon;
  30078. var Box = (function (_super) {
  30079. __extends(Box, _super);
  30080. // Members
  30081. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  30082. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30083. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30084. _this.size = size;
  30085. _this.side = side;
  30086. return _this;
  30087. }
  30088. Box.prototype._regenerateVertexData = function () {
  30089. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  30090. };
  30091. Box.prototype.copy = function (id) {
  30092. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  30093. };
  30094. Box.prototype.serialize = function () {
  30095. var serializationObject = _super.prototype.serialize.call(this);
  30096. serializationObject.size = this.size;
  30097. return serializationObject;
  30098. };
  30099. Box.Parse = function (parsedBox, scene) {
  30100. if (scene.getGeometryByID(parsedBox.id)) {
  30101. return null; // null since geometry could be something else than a box...
  30102. }
  30103. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  30104. if (BABYLON.Tags) {
  30105. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  30106. }
  30107. scene.pushGeometry(box, true);
  30108. return box;
  30109. };
  30110. return Box;
  30111. }(_Primitive));
  30112. Primitives.Box = Box;
  30113. var Sphere = (function (_super) {
  30114. __extends(Sphere, _super);
  30115. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  30116. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30117. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30118. _this.segments = segments;
  30119. _this.diameter = diameter;
  30120. _this.side = side;
  30121. return _this;
  30122. }
  30123. Sphere.prototype._regenerateVertexData = function () {
  30124. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  30125. };
  30126. Sphere.prototype.copy = function (id) {
  30127. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  30128. };
  30129. Sphere.prototype.serialize = function () {
  30130. var serializationObject = _super.prototype.serialize.call(this);
  30131. serializationObject.segments = this.segments;
  30132. serializationObject.diameter = this.diameter;
  30133. return serializationObject;
  30134. };
  30135. Sphere.Parse = function (parsedSphere, scene) {
  30136. if (scene.getGeometryByID(parsedSphere.id)) {
  30137. return null; // null since geometry could be something else than a sphere...
  30138. }
  30139. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  30140. if (BABYLON.Tags) {
  30141. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  30142. }
  30143. scene.pushGeometry(sphere, true);
  30144. return sphere;
  30145. };
  30146. return Sphere;
  30147. }(_Primitive));
  30148. Primitives.Sphere = Sphere;
  30149. var Disc = (function (_super) {
  30150. __extends(Disc, _super);
  30151. // Members
  30152. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  30153. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30154. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30155. _this.radius = radius;
  30156. _this.tessellation = tessellation;
  30157. _this.side = side;
  30158. return _this;
  30159. }
  30160. Disc.prototype._regenerateVertexData = function () {
  30161. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  30162. };
  30163. Disc.prototype.copy = function (id) {
  30164. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  30165. };
  30166. return Disc;
  30167. }(_Primitive));
  30168. Primitives.Disc = Disc;
  30169. var Cylinder = (function (_super) {
  30170. __extends(Cylinder, _super);
  30171. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  30172. if (subdivisions === void 0) { subdivisions = 1; }
  30173. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30174. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30175. _this.height = height;
  30176. _this.diameterTop = diameterTop;
  30177. _this.diameterBottom = diameterBottom;
  30178. _this.tessellation = tessellation;
  30179. _this.subdivisions = subdivisions;
  30180. _this.side = side;
  30181. return _this;
  30182. }
  30183. Cylinder.prototype._regenerateVertexData = function () {
  30184. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  30185. };
  30186. Cylinder.prototype.copy = function (id) {
  30187. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  30188. };
  30189. Cylinder.prototype.serialize = function () {
  30190. var serializationObject = _super.prototype.serialize.call(this);
  30191. serializationObject.height = this.height;
  30192. serializationObject.diameterTop = this.diameterTop;
  30193. serializationObject.diameterBottom = this.diameterBottom;
  30194. serializationObject.tessellation = this.tessellation;
  30195. return serializationObject;
  30196. };
  30197. Cylinder.Parse = function (parsedCylinder, scene) {
  30198. if (scene.getGeometryByID(parsedCylinder.id)) {
  30199. return null; // null since geometry could be something else than a cylinder...
  30200. }
  30201. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  30202. if (BABYLON.Tags) {
  30203. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  30204. }
  30205. scene.pushGeometry(cylinder, true);
  30206. return cylinder;
  30207. };
  30208. return Cylinder;
  30209. }(_Primitive));
  30210. Primitives.Cylinder = Cylinder;
  30211. var Torus = (function (_super) {
  30212. __extends(Torus, _super);
  30213. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  30214. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30215. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30216. _this.diameter = diameter;
  30217. _this.thickness = thickness;
  30218. _this.tessellation = tessellation;
  30219. _this.side = side;
  30220. return _this;
  30221. }
  30222. Torus.prototype._regenerateVertexData = function () {
  30223. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  30224. };
  30225. Torus.prototype.copy = function (id) {
  30226. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  30227. };
  30228. Torus.prototype.serialize = function () {
  30229. var serializationObject = _super.prototype.serialize.call(this);
  30230. serializationObject.diameter = this.diameter;
  30231. serializationObject.thickness = this.thickness;
  30232. serializationObject.tessellation = this.tessellation;
  30233. return serializationObject;
  30234. };
  30235. Torus.Parse = function (parsedTorus, scene) {
  30236. if (scene.getGeometryByID(parsedTorus.id)) {
  30237. return null; // null since geometry could be something else than a torus...
  30238. }
  30239. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  30240. if (BABYLON.Tags) {
  30241. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  30242. }
  30243. scene.pushGeometry(torus, true);
  30244. return torus;
  30245. };
  30246. return Torus;
  30247. }(_Primitive));
  30248. Primitives.Torus = Torus;
  30249. var Ground = (function (_super) {
  30250. __extends(Ground, _super);
  30251. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  30252. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30253. _this.width = width;
  30254. _this.height = height;
  30255. _this.subdivisions = subdivisions;
  30256. return _this;
  30257. }
  30258. Ground.prototype._regenerateVertexData = function () {
  30259. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  30260. };
  30261. Ground.prototype.copy = function (id) {
  30262. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  30263. };
  30264. Ground.prototype.serialize = function () {
  30265. var serializationObject = _super.prototype.serialize.call(this);
  30266. serializationObject.width = this.width;
  30267. serializationObject.height = this.height;
  30268. serializationObject.subdivisions = this.subdivisions;
  30269. return serializationObject;
  30270. };
  30271. Ground.Parse = function (parsedGround, scene) {
  30272. if (scene.getGeometryByID(parsedGround.id)) {
  30273. return null; // null since geometry could be something else than a ground...
  30274. }
  30275. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  30276. if (BABYLON.Tags) {
  30277. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  30278. }
  30279. scene.pushGeometry(ground, true);
  30280. return ground;
  30281. };
  30282. return Ground;
  30283. }(_Primitive));
  30284. Primitives.Ground = Ground;
  30285. var TiledGround = (function (_super) {
  30286. __extends(TiledGround, _super);
  30287. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  30288. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30289. _this.xmin = xmin;
  30290. _this.zmin = zmin;
  30291. _this.xmax = xmax;
  30292. _this.zmax = zmax;
  30293. _this.subdivisions = subdivisions;
  30294. _this.precision = precision;
  30295. return _this;
  30296. }
  30297. TiledGround.prototype._regenerateVertexData = function () {
  30298. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  30299. };
  30300. TiledGround.prototype.copy = function (id) {
  30301. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  30302. };
  30303. return TiledGround;
  30304. }(_Primitive));
  30305. Primitives.TiledGround = TiledGround;
  30306. var Plane = (function (_super) {
  30307. __extends(Plane, _super);
  30308. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  30309. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30310. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30311. _this.size = size;
  30312. _this.side = side;
  30313. return _this;
  30314. }
  30315. Plane.prototype._regenerateVertexData = function () {
  30316. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  30317. };
  30318. Plane.prototype.copy = function (id) {
  30319. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  30320. };
  30321. Plane.prototype.serialize = function () {
  30322. var serializationObject = _super.prototype.serialize.call(this);
  30323. serializationObject.size = this.size;
  30324. return serializationObject;
  30325. };
  30326. Plane.Parse = function (parsedPlane, scene) {
  30327. if (scene.getGeometryByID(parsedPlane.id)) {
  30328. return null; // null since geometry could be something else than a ground...
  30329. }
  30330. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  30331. if (BABYLON.Tags) {
  30332. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  30333. }
  30334. scene.pushGeometry(plane, true);
  30335. return plane;
  30336. };
  30337. return Plane;
  30338. }(_Primitive));
  30339. Primitives.Plane = Plane;
  30340. var TorusKnot = (function (_super) {
  30341. __extends(TorusKnot, _super);
  30342. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  30343. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  30344. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  30345. _this.radius = radius;
  30346. _this.tube = tube;
  30347. _this.radialSegments = radialSegments;
  30348. _this.tubularSegments = tubularSegments;
  30349. _this.p = p;
  30350. _this.q = q;
  30351. _this.side = side;
  30352. return _this;
  30353. }
  30354. TorusKnot.prototype._regenerateVertexData = function () {
  30355. 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 });
  30356. };
  30357. TorusKnot.prototype.copy = function (id) {
  30358. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  30359. };
  30360. TorusKnot.prototype.serialize = function () {
  30361. var serializationObject = _super.prototype.serialize.call(this);
  30362. serializationObject.radius = this.radius;
  30363. serializationObject.tube = this.tube;
  30364. serializationObject.radialSegments = this.radialSegments;
  30365. serializationObject.tubularSegments = this.tubularSegments;
  30366. serializationObject.p = this.p;
  30367. serializationObject.q = this.q;
  30368. return serializationObject;
  30369. };
  30370. ;
  30371. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  30372. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  30373. return null; // null since geometry could be something else than a ground...
  30374. }
  30375. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  30376. if (BABYLON.Tags) {
  30377. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  30378. }
  30379. scene.pushGeometry(torusKnot, true);
  30380. return torusKnot;
  30381. };
  30382. return TorusKnot;
  30383. }(_Primitive));
  30384. Primitives.TorusKnot = TorusKnot;
  30385. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  30386. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  30387. })(BABYLON || (BABYLON = {}));
  30388. //# sourceMappingURL=babylon.geometry.js.map
  30389. var BABYLON;
  30390. (function (BABYLON) {
  30391. var PostProcessManager = (function () {
  30392. function PostProcessManager(scene) {
  30393. this._vertexBuffers = {};
  30394. this._scene = scene;
  30395. }
  30396. PostProcessManager.prototype._prepareBuffers = function () {
  30397. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  30398. return;
  30399. }
  30400. // VBO
  30401. var vertices = [];
  30402. vertices.push(1, 1);
  30403. vertices.push(-1, 1);
  30404. vertices.push(-1, -1);
  30405. vertices.push(1, -1);
  30406. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  30407. this._buildIndexBuffer();
  30408. };
  30409. PostProcessManager.prototype._buildIndexBuffer = function () {
  30410. // Indices
  30411. var indices = [];
  30412. indices.push(0);
  30413. indices.push(1);
  30414. indices.push(2);
  30415. indices.push(0);
  30416. indices.push(2);
  30417. indices.push(3);
  30418. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  30419. };
  30420. PostProcessManager.prototype._rebuild = function () {
  30421. if (!this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  30422. return;
  30423. }
  30424. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  30425. this._buildIndexBuffer();
  30426. };
  30427. // Methods
  30428. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  30429. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  30430. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30431. return false;
  30432. }
  30433. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  30434. return true;
  30435. };
  30436. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  30437. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  30438. var engine = this._scene.getEngine();
  30439. for (var index = 0; index < postProcesses.length; index++) {
  30440. if (index < postProcesses.length - 1) {
  30441. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30442. }
  30443. else {
  30444. if (targetTexture) {
  30445. engine.bindFramebuffer(targetTexture, 0, null, null, forceFullscreenViewport);
  30446. }
  30447. else {
  30448. engine.restoreDefaultFramebuffer();
  30449. }
  30450. }
  30451. var pp = postProcesses[index];
  30452. var effect = pp.apply();
  30453. if (effect) {
  30454. pp.onBeforeRenderObservable.notifyObservers(effect);
  30455. // VBOs
  30456. this._prepareBuffers();
  30457. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30458. // Draw order
  30459. engine.draw(true, 0, 6);
  30460. pp.onAfterRenderObservable.notifyObservers(effect);
  30461. }
  30462. }
  30463. // Restore depth buffer
  30464. engine.setDepthBuffer(true);
  30465. engine.setDepthWrite(true);
  30466. };
  30467. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  30468. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  30469. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  30470. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30471. return;
  30472. }
  30473. var engine = this._scene.getEngine();
  30474. for (var index = 0, len = postProcesses.length; index < len; index++) {
  30475. if (index < len - 1) {
  30476. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30477. }
  30478. else {
  30479. if (targetTexture) {
  30480. engine.bindFramebuffer(targetTexture, faceIndex, null, null, forceFullscreenViewport);
  30481. }
  30482. else {
  30483. engine.restoreDefaultFramebuffer();
  30484. }
  30485. }
  30486. if (doNotPresent) {
  30487. break;
  30488. }
  30489. var pp = postProcesses[index];
  30490. var effect = pp.apply();
  30491. if (effect) {
  30492. pp.onBeforeRenderObservable.notifyObservers(effect);
  30493. // VBOs
  30494. this._prepareBuffers();
  30495. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30496. // Draw order
  30497. engine.draw(true, 0, 6);
  30498. pp.onAfterRenderObservable.notifyObservers(effect);
  30499. }
  30500. }
  30501. // Restore states
  30502. engine.setDepthBuffer(true);
  30503. engine.setDepthWrite(true);
  30504. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  30505. };
  30506. PostProcessManager.prototype.dispose = function () {
  30507. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  30508. if (buffer) {
  30509. buffer.dispose();
  30510. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  30511. }
  30512. if (this._indexBuffer) {
  30513. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  30514. this._indexBuffer = null;
  30515. }
  30516. };
  30517. return PostProcessManager;
  30518. }());
  30519. BABYLON.PostProcessManager = PostProcessManager;
  30520. })(BABYLON || (BABYLON = {}));
  30521. //# sourceMappingURL=babylon.postProcessManager.js.map
  30522. var BABYLON;
  30523. (function (BABYLON) {
  30524. /**
  30525. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  30526. */
  30527. var PerformanceMonitor = (function () {
  30528. /**
  30529. * constructor
  30530. * @param frameSampleSize The number of samples required to saturate the sliding window
  30531. */
  30532. function PerformanceMonitor(frameSampleSize) {
  30533. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  30534. this._enabled = true;
  30535. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  30536. }
  30537. /**
  30538. * Samples current frame
  30539. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  30540. */
  30541. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  30542. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  30543. if (!this._enabled)
  30544. return;
  30545. if (this._lastFrameTimeMs != null) {
  30546. var dt = timeMs - this._lastFrameTimeMs;
  30547. this._rollingFrameTime.add(dt);
  30548. }
  30549. this._lastFrameTimeMs = timeMs;
  30550. };
  30551. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  30552. /**
  30553. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  30554. * @return Average frame time in milliseconds
  30555. */
  30556. get: function () {
  30557. return this._rollingFrameTime.average;
  30558. },
  30559. enumerable: true,
  30560. configurable: true
  30561. });
  30562. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  30563. /**
  30564. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  30565. * @return Frame time variance in milliseconds squared
  30566. */
  30567. get: function () {
  30568. return this._rollingFrameTime.variance;
  30569. },
  30570. enumerable: true,
  30571. configurable: true
  30572. });
  30573. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  30574. /**
  30575. * Returns the frame time of the most recent frame
  30576. * @return Frame time in milliseconds
  30577. */
  30578. get: function () {
  30579. return this._rollingFrameTime.history(0);
  30580. },
  30581. enumerable: true,
  30582. configurable: true
  30583. });
  30584. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  30585. /**
  30586. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  30587. * @return Framerate in frames per second
  30588. */
  30589. get: function () {
  30590. return 1000.0 / this._rollingFrameTime.average;
  30591. },
  30592. enumerable: true,
  30593. configurable: true
  30594. });
  30595. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  30596. /**
  30597. * Returns the average framerate in frames per second using the most recent frame time
  30598. * @return Framerate in frames per second
  30599. */
  30600. get: function () {
  30601. return 1000.0 / this._rollingFrameTime.history(0);
  30602. },
  30603. enumerable: true,
  30604. configurable: true
  30605. });
  30606. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  30607. /**
  30608. * Returns true if enough samples have been taken to completely fill the sliding window
  30609. * @return true if saturated
  30610. */
  30611. get: function () {
  30612. return this._rollingFrameTime.isSaturated();
  30613. },
  30614. enumerable: true,
  30615. configurable: true
  30616. });
  30617. /**
  30618. * Enables contributions to the sliding window sample set
  30619. */
  30620. PerformanceMonitor.prototype.enable = function () {
  30621. this._enabled = true;
  30622. };
  30623. /**
  30624. * Disables contributions to the sliding window sample set
  30625. * Samples will not be interpolated over the disabled period
  30626. */
  30627. PerformanceMonitor.prototype.disable = function () {
  30628. this._enabled = false;
  30629. //clear last sample to avoid interpolating over the disabled period when next enabled
  30630. this._lastFrameTimeMs = null;
  30631. this._lastChangeTimeMs = null;
  30632. };
  30633. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  30634. /**
  30635. * Returns true if sampling is enabled
  30636. * @return true if enabled
  30637. */
  30638. get: function () {
  30639. return this._enabled;
  30640. },
  30641. enumerable: true,
  30642. configurable: true
  30643. });
  30644. /**
  30645. * Resets performance monitor
  30646. */
  30647. PerformanceMonitor.prototype.reset = function () {
  30648. //clear last sample to avoid interpolating over the disabled period when next enabled
  30649. this._lastFrameTimeMs = null;
  30650. this._lastChangeTimeMs = null;
  30651. //wipe record
  30652. this._rollingFrameTime.reset();
  30653. };
  30654. return PerformanceMonitor;
  30655. }());
  30656. BABYLON.PerformanceMonitor = PerformanceMonitor;
  30657. /**
  30658. * RollingAverage
  30659. *
  30660. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  30661. */
  30662. var RollingAverage = (function () {
  30663. /**
  30664. * constructor
  30665. * @param length The number of samples required to saturate the sliding window
  30666. */
  30667. function RollingAverage(length) {
  30668. this._samples = new Array(length);
  30669. this.reset();
  30670. }
  30671. /**
  30672. * Adds a sample to the sample set
  30673. * @param v The sample value
  30674. */
  30675. RollingAverage.prototype.add = function (v) {
  30676. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  30677. var delta;
  30678. //we need to check if we've already wrapped round
  30679. if (this.isSaturated()) {
  30680. //remove bottom of stack from mean
  30681. var bottomValue = this._samples[this._pos];
  30682. delta = bottomValue - this.average;
  30683. this.average -= delta / (this._sampleCount - 1);
  30684. this._m2 -= delta * (bottomValue - this.average);
  30685. }
  30686. else {
  30687. this._sampleCount++;
  30688. }
  30689. //add new value to mean
  30690. delta = v - this.average;
  30691. this.average += delta / (this._sampleCount);
  30692. this._m2 += delta * (v - this.average);
  30693. //set the new variance
  30694. this.variance = this._m2 / (this._sampleCount - 1);
  30695. this._samples[this._pos] = v;
  30696. this._pos++;
  30697. this._pos %= this._samples.length; //positive wrap around
  30698. };
  30699. /**
  30700. * Returns previously added values or null if outside of history or outside the sliding window domain
  30701. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  30702. * @return Value previously recorded with add() or null if outside of range
  30703. */
  30704. RollingAverage.prototype.history = function (i) {
  30705. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  30706. return null;
  30707. }
  30708. var i0 = this._wrapPosition(this._pos - 1.0);
  30709. return this._samples[this._wrapPosition(i0 - i)];
  30710. };
  30711. /**
  30712. * Returns true if enough samples have been taken to completely fill the sliding window
  30713. * @return true if sample-set saturated
  30714. */
  30715. RollingAverage.prototype.isSaturated = function () {
  30716. return this._sampleCount >= this._samples.length;
  30717. };
  30718. /**
  30719. * Resets the rolling average (equivalent to 0 samples taken so far)
  30720. */
  30721. RollingAverage.prototype.reset = function () {
  30722. this.average = 0;
  30723. this.variance = 0;
  30724. this._sampleCount = 0;
  30725. this._pos = 0;
  30726. this._m2 = 0;
  30727. };
  30728. /**
  30729. * Wraps a value around the sample range boundaries
  30730. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  30731. * @return Wrapped position in sample range
  30732. */
  30733. RollingAverage.prototype._wrapPosition = function (i) {
  30734. var max = this._samples.length;
  30735. return ((i % max) + max) % max;
  30736. };
  30737. return RollingAverage;
  30738. }());
  30739. BABYLON.RollingAverage = RollingAverage;
  30740. })(BABYLON || (BABYLON = {}));
  30741. //# sourceMappingURL=babylon.performanceMonitor.js.map
  30742. var BABYLON;
  30743. (function (BABYLON) {
  30744. /**
  30745. * This groups together the common properties used for image processing either in direct forward pass
  30746. * or through post processing effect depending on the use of the image processing pipeline in your scene
  30747. * or not.
  30748. */
  30749. var ImageProcessingConfiguration = (function () {
  30750. function ImageProcessingConfiguration() {
  30751. /**
  30752. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  30753. */
  30754. this.colorCurves = new BABYLON.ColorCurves();
  30755. this._colorCurvesEnabled = false;
  30756. this._colorGradingEnabled = false;
  30757. this._colorGradingWithGreenDepth = false;
  30758. this._colorGradingBGR = false;
  30759. this._exposure = 1.0;
  30760. this._toneMappingEnabled = false;
  30761. this._contrast = 1.0;
  30762. /**
  30763. * Vignette stretch size.
  30764. */
  30765. this.vignetteStretch = 0;
  30766. /**
  30767. * Vignette centre X Offset.
  30768. */
  30769. this.vignetteCentreX = 0;
  30770. /**
  30771. * Vignette centre Y Offset.
  30772. */
  30773. this.vignetteCentreY = 0;
  30774. /**
  30775. * Vignette weight or intensity of the vignette effect.
  30776. */
  30777. this.vignetteWeight = 1.5;
  30778. /**
  30779. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  30780. * if vignetteEnabled is set to true.
  30781. */
  30782. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  30783. /**
  30784. * Camera field of view used by the Vignette effect.
  30785. */
  30786. this.vignetteCameraFov = 0.5;
  30787. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  30788. this._vignetteEnabled = false;
  30789. this._applyByPostProcess = false;
  30790. /**
  30791. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  30792. * @type {BABYLON.Observable}
  30793. */
  30794. this.onUpdateParameters = new BABYLON.Observable();
  30795. }
  30796. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  30797. /**
  30798. * Gets wether the color curves effect is enabled.
  30799. */
  30800. get: function () {
  30801. return this._colorCurvesEnabled;
  30802. },
  30803. /**
  30804. * Sets wether the color curves effect is enabled.
  30805. */
  30806. set: function (value) {
  30807. if (this._colorCurvesEnabled === value) {
  30808. return;
  30809. }
  30810. this._colorCurvesEnabled = value;
  30811. this._updateParameters();
  30812. },
  30813. enumerable: true,
  30814. configurable: true
  30815. });
  30816. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  30817. /**
  30818. * Gets wether the color grading effect is enabled.
  30819. */
  30820. get: function () {
  30821. return this._colorGradingEnabled;
  30822. },
  30823. /**
  30824. * Sets wether the color grading effect is enabled.
  30825. */
  30826. set: function (value) {
  30827. if (this._colorGradingEnabled === value) {
  30828. return;
  30829. }
  30830. this._colorGradingEnabled = value;
  30831. this._updateParameters();
  30832. },
  30833. enumerable: true,
  30834. configurable: true
  30835. });
  30836. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  30837. /**
  30838. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  30839. */
  30840. get: function () {
  30841. return this._colorGradingWithGreenDepth;
  30842. },
  30843. /**
  30844. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  30845. */
  30846. set: function (value) {
  30847. if (this._colorGradingWithGreenDepth === value) {
  30848. return;
  30849. }
  30850. this._colorGradingWithGreenDepth = value;
  30851. this._updateParameters();
  30852. },
  30853. enumerable: true,
  30854. configurable: true
  30855. });
  30856. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  30857. /**
  30858. * Gets wether the color grading texture contains BGR values.
  30859. */
  30860. get: function () {
  30861. return this._colorGradingBGR;
  30862. },
  30863. /**
  30864. * Sets wether the color grading texture contains BGR values.
  30865. */
  30866. set: function (value) {
  30867. if (this._colorGradingBGR === value) {
  30868. return;
  30869. }
  30870. this._colorGradingBGR = value;
  30871. this._updateParameters();
  30872. },
  30873. enumerable: true,
  30874. configurable: true
  30875. });
  30876. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  30877. /**
  30878. * Gets the Exposure used in the effect.
  30879. */
  30880. get: function () {
  30881. return this._exposure;
  30882. },
  30883. /**
  30884. * Sets the Exposure used in the effect.
  30885. */
  30886. set: function (value) {
  30887. if (this._exposure === value) {
  30888. return;
  30889. }
  30890. this._exposure = value;
  30891. this._updateParameters();
  30892. },
  30893. enumerable: true,
  30894. configurable: true
  30895. });
  30896. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  30897. /**
  30898. * Gets wether the tone mapping effect is enabled.
  30899. */
  30900. get: function () {
  30901. return this._toneMappingEnabled;
  30902. },
  30903. /**
  30904. * Sets wether the tone mapping effect is enabled.
  30905. */
  30906. set: function (value) {
  30907. if (this._toneMappingEnabled === value) {
  30908. return;
  30909. }
  30910. this._toneMappingEnabled = value;
  30911. this._updateParameters();
  30912. },
  30913. enumerable: true,
  30914. configurable: true
  30915. });
  30916. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  30917. /**
  30918. * Gets the contrast used in the effect.
  30919. */
  30920. get: function () {
  30921. return this._contrast;
  30922. },
  30923. /**
  30924. * Sets the contrast used in the effect.
  30925. */
  30926. set: function (value) {
  30927. if (this._contrast === value) {
  30928. return;
  30929. }
  30930. this._contrast = value;
  30931. this._updateParameters();
  30932. },
  30933. enumerable: true,
  30934. configurable: true
  30935. });
  30936. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  30937. /**
  30938. * Gets the vignette blend mode allowing different kind of effect.
  30939. */
  30940. get: function () {
  30941. return this._vignetteBlendMode;
  30942. },
  30943. /**
  30944. * Sets the vignette blend mode allowing different kind of effect.
  30945. */
  30946. set: function (value) {
  30947. if (this._vignetteBlendMode === value) {
  30948. return;
  30949. }
  30950. this._vignetteBlendMode = value;
  30951. this._updateParameters();
  30952. },
  30953. enumerable: true,
  30954. configurable: true
  30955. });
  30956. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  30957. /**
  30958. * Gets wether the vignette effect is enabled.
  30959. */
  30960. get: function () {
  30961. return this._vignetteEnabled;
  30962. },
  30963. /**
  30964. * Sets wether the vignette effect is enabled.
  30965. */
  30966. set: function (value) {
  30967. if (this._vignetteEnabled === value) {
  30968. return;
  30969. }
  30970. this._vignetteEnabled = value;
  30971. this._updateParameters();
  30972. },
  30973. enumerable: true,
  30974. configurable: true
  30975. });
  30976. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  30977. /**
  30978. * Gets wether the image processing is applied through a post process or not.
  30979. */
  30980. get: function () {
  30981. return this._applyByPostProcess;
  30982. },
  30983. /**
  30984. * Sets wether the image processing is applied through a post process or not.
  30985. */
  30986. set: function (value) {
  30987. if (this._applyByPostProcess === value) {
  30988. return;
  30989. }
  30990. this._applyByPostProcess = value;
  30991. this._updateParameters();
  30992. },
  30993. enumerable: true,
  30994. configurable: true
  30995. });
  30996. /**
  30997. * Method called each time the image processing information changes requires to recompile the effect.
  30998. */
  30999. ImageProcessingConfiguration.prototype._updateParameters = function () {
  31000. this.onUpdateParameters.notifyObservers(this);
  31001. };
  31002. ImageProcessingConfiguration.prototype.getClassName = function () {
  31003. return "ImageProcessingConfiguration";
  31004. };
  31005. /**
  31006. * Prepare the list of uniforms associated with the Image Processing effects.
  31007. * @param uniformsList The list of uniforms used in the effect
  31008. * @param defines the list of defines currently in use
  31009. */
  31010. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  31011. if (defines.EXPOSURE) {
  31012. uniforms.push("exposureLinear");
  31013. }
  31014. if (defines.CONTRAST) {
  31015. uniforms.push("contrast");
  31016. }
  31017. if (defines.COLORGRADING) {
  31018. uniforms.push("colorTransformSettings");
  31019. }
  31020. if (defines.VIGNETTE) {
  31021. uniforms.push("vInverseScreenSize");
  31022. uniforms.push("vignetteSettings1");
  31023. uniforms.push("vignetteSettings2");
  31024. }
  31025. if (defines.COLORCURVES) {
  31026. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  31027. }
  31028. };
  31029. /**
  31030. * Prepare the list of samplers associated with the Image Processing effects.
  31031. * @param uniformsList The list of uniforms used in the effect
  31032. * @param defines the list of defines currently in use
  31033. */
  31034. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  31035. if (defines.COLORGRADING) {
  31036. samplersList.push("txColorTransform");
  31037. }
  31038. };
  31039. /**
  31040. * Prepare the list of defines associated to the shader.
  31041. * @param defines the list of defines to complete
  31042. */
  31043. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  31044. if (forPostProcess === void 0) { forPostProcess = false; }
  31045. if (forPostProcess !== this.applyByPostProcess) {
  31046. defines.VIGNETTE = false;
  31047. defines.TONEMAPPING = false;
  31048. defines.CONTRAST = false;
  31049. defines.EXPOSURE = false;
  31050. defines.COLORCURVES = false;
  31051. defines.COLORGRADING = false;
  31052. defines.IMAGEPROCESSING = false;
  31053. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  31054. return;
  31055. }
  31056. defines.VIGNETTE = this.vignetteEnabled;
  31057. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  31058. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  31059. defines.TONEMAPPING = this.toneMappingEnabled;
  31060. defines.CONTRAST = (this.contrast !== 1.0);
  31061. defines.EXPOSURE = (this.exposure !== 1.0);
  31062. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  31063. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  31064. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  31065. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  31066. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  31067. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  31068. };
  31069. /**
  31070. * Returns true if all the image processing information are ready.
  31071. */
  31072. ImageProcessingConfiguration.prototype.isReady = function () {
  31073. // Color Grading texure can not be none blocking.
  31074. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  31075. };
  31076. /**
  31077. * Binds the image processing to the shader.
  31078. * @param effect The effect to bind to
  31079. */
  31080. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  31081. if (aspectRatio === void 0) { aspectRatio = 1; }
  31082. // Color Curves
  31083. if (this._colorCurvesEnabled) {
  31084. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  31085. }
  31086. // Vignette
  31087. if (this._vignetteEnabled) {
  31088. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  31089. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  31090. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  31091. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  31092. var vignetteScaleX = vignetteScaleY * aspectRatio;
  31093. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  31094. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  31095. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  31096. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  31097. var vignettePower = -2.0 * this.vignetteWeight;
  31098. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  31099. }
  31100. // Exposure
  31101. effect.setFloat("exposureLinear", this.exposure);
  31102. // Contrast
  31103. effect.setFloat("contrast", this.contrast);
  31104. // Color transform settings
  31105. if (this.colorGradingTexture) {
  31106. effect.setTexture("txColorTransform", this.colorGradingTexture);
  31107. var textureSize = this.colorGradingTexture.getSize().height;
  31108. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  31109. 0.5 / textureSize, // textureOffset
  31110. textureSize, // textureSize
  31111. this.colorGradingTexture.level // weight
  31112. );
  31113. }
  31114. };
  31115. /**
  31116. * Clones the current image processing instance.
  31117. * @return The cloned image processing
  31118. */
  31119. ImageProcessingConfiguration.prototype.clone = function () {
  31120. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  31121. };
  31122. /**
  31123. * Serializes the current image processing instance to a json representation.
  31124. * @return a JSON representation
  31125. */
  31126. ImageProcessingConfiguration.prototype.serialize = function () {
  31127. return BABYLON.SerializationHelper.Serialize(this);
  31128. };
  31129. /**
  31130. * Parses the image processing from a json representation.
  31131. * @param source the JSON source to parse
  31132. * @return The parsed image processing
  31133. */
  31134. ImageProcessingConfiguration.Parse = function (source) {
  31135. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  31136. };
  31137. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  31138. /**
  31139. * Used to apply the vignette as a mix with the pixel color.
  31140. */
  31141. get: function () {
  31142. return this._VIGNETTEMODE_MULTIPLY;
  31143. },
  31144. enumerable: true,
  31145. configurable: true
  31146. });
  31147. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  31148. /**
  31149. * Used to apply the vignette as a replacement of the pixel color.
  31150. */
  31151. get: function () {
  31152. return this._VIGNETTEMODE_OPAQUE;
  31153. },
  31154. enumerable: true,
  31155. configurable: true
  31156. });
  31157. // Static constants associated to the image processing.
  31158. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  31159. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  31160. __decorate([
  31161. BABYLON.serializeAsColorCurves()
  31162. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  31163. __decorate([
  31164. BABYLON.serialize()
  31165. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  31166. __decorate([
  31167. BABYLON.serializeAsTexture()
  31168. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  31169. __decorate([
  31170. BABYLON.serialize()
  31171. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  31172. __decorate([
  31173. BABYLON.serialize()
  31174. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  31175. __decorate([
  31176. BABYLON.serialize()
  31177. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  31178. __decorate([
  31179. BABYLON.serialize()
  31180. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  31181. __decorate([
  31182. BABYLON.serialize()
  31183. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  31184. __decorate([
  31185. BABYLON.serialize()
  31186. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  31187. __decorate([
  31188. BABYLON.serialize()
  31189. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  31190. __decorate([
  31191. BABYLON.serialize()
  31192. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  31193. __decorate([
  31194. BABYLON.serialize()
  31195. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  31196. __decorate([
  31197. BABYLON.serialize()
  31198. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  31199. __decorate([
  31200. BABYLON.serializeAsColor4()
  31201. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  31202. __decorate([
  31203. BABYLON.serialize()
  31204. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  31205. __decorate([
  31206. BABYLON.serialize()
  31207. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  31208. __decorate([
  31209. BABYLON.serialize()
  31210. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  31211. __decorate([
  31212. BABYLON.serialize()
  31213. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  31214. return ImageProcessingConfiguration;
  31215. }());
  31216. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  31217. })(BABYLON || (BABYLON = {}));
  31218. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  31219. var BABYLON;
  31220. (function (BABYLON) {
  31221. /**
  31222. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  31223. * It can help converting any input color in a desired output one. This can then be used to create effects
  31224. * from sepia, black and white to sixties or futuristic rendering...
  31225. *
  31226. * The only supported format is currently 3dl.
  31227. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  31228. */
  31229. var ColorGradingTexture = (function (_super) {
  31230. __extends(ColorGradingTexture, _super);
  31231. /**
  31232. * Instantiates a ColorGradingTexture from the following parameters.
  31233. *
  31234. * @param url The location of the color gradind data (currently only supporting 3dl)
  31235. * @param scene The scene the texture will be used in
  31236. */
  31237. function ColorGradingTexture(url, scene) {
  31238. var _this = _super.call(this, scene) || this;
  31239. if (!url) {
  31240. return _this;
  31241. }
  31242. _this._textureMatrix = BABYLON.Matrix.Identity();
  31243. _this.name = url;
  31244. _this.url = url;
  31245. _this.hasAlpha = false;
  31246. _this.isCube = false;
  31247. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31248. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31249. _this.anisotropicFilteringLevel = 1;
  31250. _this._texture = _this._getFromCache(url, true);
  31251. if (!_this._texture) {
  31252. if (!scene.useDelayedTextureLoading) {
  31253. _this.loadTexture();
  31254. }
  31255. else {
  31256. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31257. }
  31258. }
  31259. return _this;
  31260. }
  31261. /**
  31262. * Returns the texture matrix used in most of the material.
  31263. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  31264. */
  31265. ColorGradingTexture.prototype.getTextureMatrix = function () {
  31266. return this._textureMatrix;
  31267. };
  31268. /**
  31269. * Occurs when the file being loaded is a .3dl LUT file.
  31270. */
  31271. ColorGradingTexture.prototype.load3dlTexture = function () {
  31272. var _this = this;
  31273. var mipLevels = 0;
  31274. var floatArrayView = null;
  31275. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31276. this._texture = texture;
  31277. var callback = function (text) {
  31278. var data;
  31279. var tempData;
  31280. var line;
  31281. var lines = text.split('\n');
  31282. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  31283. var maxColor = 0;
  31284. for (var i = 0; i < lines.length; i++) {
  31285. line = lines[i];
  31286. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  31287. continue;
  31288. if (line.indexOf('#') === 0)
  31289. continue;
  31290. var words = line.split(" ");
  31291. if (size === 0) {
  31292. // Number of space + one
  31293. size = words.length;
  31294. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  31295. tempData = new Float32Array(size * size * size * 4);
  31296. continue;
  31297. }
  31298. if (size != 0) {
  31299. var r = Math.max(parseInt(words[0]), 0);
  31300. var g = Math.max(parseInt(words[1]), 0);
  31301. var b = Math.max(parseInt(words[2]), 0);
  31302. maxColor = Math.max(r, maxColor);
  31303. maxColor = Math.max(g, maxColor);
  31304. maxColor = Math.max(b, maxColor);
  31305. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  31306. tempData[pixelStorageIndex + 0] = r;
  31307. tempData[pixelStorageIndex + 1] = g;
  31308. tempData[pixelStorageIndex + 2] = b;
  31309. pixelIndexSlice++;
  31310. if (pixelIndexSlice % size == 0) {
  31311. pixelIndexH++;
  31312. pixelIndexSlice = 0;
  31313. if (pixelIndexH % size == 0) {
  31314. pixelIndexW++;
  31315. pixelIndexH = 0;
  31316. }
  31317. }
  31318. }
  31319. }
  31320. for (var i = 0; i < tempData.length; i++) {
  31321. if (i > 0 && (i + 1) % 4 === 0) {
  31322. data[i] = 255;
  31323. }
  31324. else {
  31325. var value = tempData[i];
  31326. data[i] = (value / maxColor * 255);
  31327. }
  31328. }
  31329. texture.updateSize(size * size, size);
  31330. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  31331. };
  31332. BABYLON.Tools.LoadFile(this.url, callback);
  31333. return this._texture;
  31334. };
  31335. /**
  31336. * Starts the loading process of the texture.
  31337. */
  31338. ColorGradingTexture.prototype.loadTexture = function () {
  31339. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  31340. this.load3dlTexture();
  31341. }
  31342. };
  31343. /**
  31344. * Clones the color gradind texture.
  31345. */
  31346. ColorGradingTexture.prototype.clone = function () {
  31347. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  31348. // Base texture
  31349. newTexture.level = this.level;
  31350. return newTexture;
  31351. };
  31352. /**
  31353. * Called during delayed load for textures.
  31354. */
  31355. ColorGradingTexture.prototype.delayLoad = function () {
  31356. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31357. return;
  31358. }
  31359. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31360. this._texture = this._getFromCache(this.url, true);
  31361. if (!this._texture) {
  31362. this.loadTexture();
  31363. }
  31364. };
  31365. /**
  31366. * Parses a color grading texture serialized by Babylon.
  31367. * @param parsedTexture The texture information being parsedTexture
  31368. * @param scene The scene to load the texture in
  31369. * @param rootUrl The root url of the data assets to load
  31370. * @return A color gradind texture
  31371. */
  31372. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  31373. var texture = null;
  31374. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  31375. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  31376. texture.name = parsedTexture.name;
  31377. texture.level = parsedTexture.level;
  31378. }
  31379. return texture;
  31380. };
  31381. /**
  31382. * Serializes the LUT texture to json format.
  31383. */
  31384. ColorGradingTexture.prototype.serialize = function () {
  31385. if (!this.name) {
  31386. return null;
  31387. }
  31388. var serializationObject = {};
  31389. serializationObject.name = this.name;
  31390. serializationObject.level = this.level;
  31391. serializationObject.customType = "BABYLON.ColorGradingTexture";
  31392. return serializationObject;
  31393. };
  31394. /**
  31395. * Empty line regex stored for GC.
  31396. */
  31397. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  31398. return ColorGradingTexture;
  31399. }(BABYLON.BaseTexture));
  31400. BABYLON.ColorGradingTexture = ColorGradingTexture;
  31401. })(BABYLON || (BABYLON = {}));
  31402. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  31403. var BABYLON;
  31404. (function (BABYLON) {
  31405. /**
  31406. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  31407. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  31408. * 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;
  31409. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  31410. */
  31411. var ColorCurves = (function () {
  31412. function ColorCurves() {
  31413. this._dirty = true;
  31414. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  31415. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  31416. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  31417. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  31418. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  31419. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  31420. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  31421. this._globalHue = 30;
  31422. this._globalDensity = 0;
  31423. this._globalSaturation = 0;
  31424. this._globalExposure = 0;
  31425. this._highlightsHue = 30;
  31426. this._highlightsDensity = 0;
  31427. this._highlightsSaturation = 0;
  31428. this._highlightsExposure = 0;
  31429. this._midtonesHue = 30;
  31430. this._midtonesDensity = 0;
  31431. this._midtonesSaturation = 0;
  31432. this._midtonesExposure = 0;
  31433. this._shadowsHue = 30;
  31434. this._shadowsDensity = 0;
  31435. this._shadowsSaturation = 0;
  31436. this._shadowsExposure = 0;
  31437. }
  31438. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  31439. /**
  31440. * Gets the global Hue value.
  31441. * 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).
  31442. */
  31443. get: function () {
  31444. return this._globalHue;
  31445. },
  31446. /**
  31447. * Sets the global Hue value.
  31448. * 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).
  31449. */
  31450. set: function (value) {
  31451. this._globalHue = value;
  31452. this._dirty = true;
  31453. },
  31454. enumerable: true,
  31455. configurable: true
  31456. });
  31457. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  31458. /**
  31459. * Gets the global Density value.
  31460. * 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.
  31461. * Values less than zero provide a filter of opposite hue.
  31462. */
  31463. get: function () {
  31464. return this._globalDensity;
  31465. },
  31466. /**
  31467. * Sets the global Density value.
  31468. * 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.
  31469. * Values less than zero provide a filter of opposite hue.
  31470. */
  31471. set: function (value) {
  31472. this._globalDensity = value;
  31473. this._dirty = true;
  31474. },
  31475. enumerable: true,
  31476. configurable: true
  31477. });
  31478. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  31479. /**
  31480. * Gets the global Saturation value.
  31481. * 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.
  31482. */
  31483. get: function () {
  31484. return this._globalSaturation;
  31485. },
  31486. /**
  31487. * Sets the global Saturation value.
  31488. * 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.
  31489. */
  31490. set: function (value) {
  31491. this._globalSaturation = value;
  31492. this._dirty = true;
  31493. },
  31494. enumerable: true,
  31495. configurable: true
  31496. });
  31497. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  31498. /**
  31499. * Gets the highlights Hue value.
  31500. * 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).
  31501. */
  31502. get: function () {
  31503. return this._highlightsHue;
  31504. },
  31505. /**
  31506. * Sets the highlights Hue value.
  31507. * 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).
  31508. */
  31509. set: function (value) {
  31510. this._highlightsHue = value;
  31511. this._dirty = true;
  31512. },
  31513. enumerable: true,
  31514. configurable: true
  31515. });
  31516. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  31517. /**
  31518. * Gets the highlights Density value.
  31519. * 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.
  31520. * Values less than zero provide a filter of opposite hue.
  31521. */
  31522. get: function () {
  31523. return this._highlightsDensity;
  31524. },
  31525. /**
  31526. * Sets the highlights Density value.
  31527. * 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.
  31528. * Values less than zero provide a filter of opposite hue.
  31529. */
  31530. set: function (value) {
  31531. this._highlightsDensity = value;
  31532. this._dirty = true;
  31533. },
  31534. enumerable: true,
  31535. configurable: true
  31536. });
  31537. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  31538. /**
  31539. * Gets the highlights Saturation value.
  31540. * 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.
  31541. */
  31542. get: function () {
  31543. return this._highlightsSaturation;
  31544. },
  31545. /**
  31546. * Sets the highlights Saturation value.
  31547. * 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.
  31548. */
  31549. set: function (value) {
  31550. this._highlightsSaturation = value;
  31551. this._dirty = true;
  31552. },
  31553. enumerable: true,
  31554. configurable: true
  31555. });
  31556. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  31557. /**
  31558. * Gets the highlights Exposure value.
  31559. * 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.
  31560. */
  31561. get: function () {
  31562. return this._highlightsExposure;
  31563. },
  31564. /**
  31565. * Sets the highlights Exposure value.
  31566. * 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.
  31567. */
  31568. set: function (value) {
  31569. this._highlightsExposure = value;
  31570. this._dirty = true;
  31571. },
  31572. enumerable: true,
  31573. configurable: true
  31574. });
  31575. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  31576. /**
  31577. * Gets the midtones Hue value.
  31578. * 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).
  31579. */
  31580. get: function () {
  31581. return this._midtonesHue;
  31582. },
  31583. /**
  31584. * Sets the midtones Hue value.
  31585. * 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).
  31586. */
  31587. set: function (value) {
  31588. this._midtonesHue = value;
  31589. this._dirty = true;
  31590. },
  31591. enumerable: true,
  31592. configurable: true
  31593. });
  31594. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  31595. /**
  31596. * Gets the midtones Density value.
  31597. * 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.
  31598. * Values less than zero provide a filter of opposite hue.
  31599. */
  31600. get: function () {
  31601. return this._midtonesDensity;
  31602. },
  31603. /**
  31604. * Sets the midtones Density value.
  31605. * 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.
  31606. * Values less than zero provide a filter of opposite hue.
  31607. */
  31608. set: function (value) {
  31609. this._midtonesDensity = value;
  31610. this._dirty = true;
  31611. },
  31612. enumerable: true,
  31613. configurable: true
  31614. });
  31615. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  31616. /**
  31617. * Gets the midtones Saturation value.
  31618. * 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.
  31619. */
  31620. get: function () {
  31621. return this._midtonesSaturation;
  31622. },
  31623. /**
  31624. * Sets the midtones Saturation value.
  31625. * 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.
  31626. */
  31627. set: function (value) {
  31628. this._midtonesSaturation = value;
  31629. this._dirty = true;
  31630. },
  31631. enumerable: true,
  31632. configurable: true
  31633. });
  31634. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  31635. /**
  31636. * Gets the midtones Exposure value.
  31637. * 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.
  31638. */
  31639. get: function () {
  31640. return this._midtonesExposure;
  31641. },
  31642. /**
  31643. * Sets the midtones Exposure value.
  31644. * 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.
  31645. */
  31646. set: function (value) {
  31647. this._midtonesExposure = value;
  31648. this._dirty = true;
  31649. },
  31650. enumerable: true,
  31651. configurable: true
  31652. });
  31653. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  31654. /**
  31655. * Gets the shadows Hue value.
  31656. * 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).
  31657. */
  31658. get: function () {
  31659. return this._shadowsHue;
  31660. },
  31661. /**
  31662. * Sets the shadows Hue value.
  31663. * 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).
  31664. */
  31665. set: function (value) {
  31666. this._shadowsHue = value;
  31667. this._dirty = true;
  31668. },
  31669. enumerable: true,
  31670. configurable: true
  31671. });
  31672. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  31673. /**
  31674. * Gets the shadows Density value.
  31675. * 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.
  31676. * Values less than zero provide a filter of opposite hue.
  31677. */
  31678. get: function () {
  31679. return this._shadowsDensity;
  31680. },
  31681. /**
  31682. * Sets the shadows Density value.
  31683. * 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.
  31684. * Values less than zero provide a filter of opposite hue.
  31685. */
  31686. set: function (value) {
  31687. this._shadowsDensity = value;
  31688. this._dirty = true;
  31689. },
  31690. enumerable: true,
  31691. configurable: true
  31692. });
  31693. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  31694. /**
  31695. * Gets the shadows Saturation value.
  31696. * 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.
  31697. */
  31698. get: function () {
  31699. return this._shadowsSaturation;
  31700. },
  31701. /**
  31702. * Sets the shadows Saturation value.
  31703. * 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.
  31704. */
  31705. set: function (value) {
  31706. this._shadowsSaturation = value;
  31707. this._dirty = true;
  31708. },
  31709. enumerable: true,
  31710. configurable: true
  31711. });
  31712. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  31713. /**
  31714. * Gets the shadows Exposure value.
  31715. * 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.
  31716. */
  31717. get: function () {
  31718. return this._shadowsExposure;
  31719. },
  31720. /**
  31721. * Sets the shadows Exposure value.
  31722. * 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.
  31723. */
  31724. set: function (value) {
  31725. this._shadowsExposure = value;
  31726. this._dirty = true;
  31727. },
  31728. enumerable: true,
  31729. configurable: true
  31730. });
  31731. ColorCurves.prototype.getClassName = function () {
  31732. return "ColorCurves";
  31733. };
  31734. /**
  31735. * Binds the color curves to the shader.
  31736. * @param colorCurves The color curve to bind
  31737. * @param effect The effect to bind to
  31738. */
  31739. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  31740. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  31741. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  31742. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  31743. if (colorCurves._dirty) {
  31744. colorCurves._dirty = false;
  31745. // Fill in global info.
  31746. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  31747. // Compute highlights info.
  31748. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  31749. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  31750. // Compute midtones info.
  31751. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  31752. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  31753. // Compute shadows info.
  31754. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  31755. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  31756. // Compute deltas (neutral is midtones).
  31757. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  31758. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  31759. }
  31760. if (effect) {
  31761. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  31762. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  31763. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  31764. }
  31765. };
  31766. /**
  31767. * Prepare the list of uniforms associated with the ColorCurves effects.
  31768. * @param uniformsList The list of uniforms used in the effect
  31769. */
  31770. ColorCurves.PrepareUniforms = function (uniformsList) {
  31771. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  31772. };
  31773. /**
  31774. * Returns color grading data based on a hue, density, saturation and exposure value.
  31775. * @param filterHue The hue of the color filter.
  31776. * @param filterDensity The density of the color filter.
  31777. * @param saturation The saturation.
  31778. * @param exposure The exposure.
  31779. * @param result The result data container.
  31780. */
  31781. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  31782. if (hue == null) {
  31783. return;
  31784. }
  31785. hue = ColorCurves.clamp(hue, 0, 360);
  31786. density = ColorCurves.clamp(density, -100, 100);
  31787. saturation = ColorCurves.clamp(saturation, -100, 100);
  31788. exposure = ColorCurves.clamp(exposure, -100, 100);
  31789. // Remap the slider/config filter density with non-linear mapping and also scale by half
  31790. // so that the maximum filter density is only 50% control. This provides fine control
  31791. // for small values and reasonable range.
  31792. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  31793. density *= 0.5;
  31794. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  31795. if (density < 0) {
  31796. density *= -1;
  31797. hue = (hue + 180) % 360;
  31798. }
  31799. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  31800. result.scaleToRef(2, result);
  31801. result.a = 1 + 0.01 * saturation;
  31802. };
  31803. /**
  31804. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  31805. * @param value The input slider value in range [-100,100].
  31806. * @returns Adjusted value.
  31807. */
  31808. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  31809. value /= 100;
  31810. var x = Math.abs(value);
  31811. x = Math.pow(x, 2);
  31812. if (value < 0) {
  31813. x *= -1;
  31814. }
  31815. x *= 100;
  31816. return x;
  31817. };
  31818. /**
  31819. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  31820. * @param hue The hue (H) input.
  31821. * @param saturation The saturation (S) input.
  31822. * @param brightness The brightness (B) input.
  31823. * @result An RGBA color represented as Vector4.
  31824. */
  31825. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  31826. var h = ColorCurves.clamp(hue, 0, 360);
  31827. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  31828. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  31829. if (s === 0) {
  31830. result.r = v;
  31831. result.g = v;
  31832. result.b = v;
  31833. }
  31834. else {
  31835. // sector 0 to 5
  31836. h /= 60;
  31837. var i = Math.floor(h);
  31838. // fractional part of h
  31839. var f = h - i;
  31840. var p = v * (1 - s);
  31841. var q = v * (1 - s * f);
  31842. var t = v * (1 - s * (1 - f));
  31843. switch (i) {
  31844. case 0:
  31845. result.r = v;
  31846. result.g = t;
  31847. result.b = p;
  31848. break;
  31849. case 1:
  31850. result.r = q;
  31851. result.g = v;
  31852. result.b = p;
  31853. break;
  31854. case 2:
  31855. result.r = p;
  31856. result.g = v;
  31857. result.b = t;
  31858. break;
  31859. case 3:
  31860. result.r = p;
  31861. result.g = q;
  31862. result.b = v;
  31863. break;
  31864. case 4:
  31865. result.r = t;
  31866. result.g = p;
  31867. result.b = v;
  31868. break;
  31869. default:// case 5:
  31870. result.r = v;
  31871. result.g = p;
  31872. result.b = q;
  31873. break;
  31874. }
  31875. }
  31876. result.a = 1;
  31877. };
  31878. /**
  31879. * Returns a value clamped between min and max
  31880. * @param value The value to clamp
  31881. * @param min The minimum of value
  31882. * @param max The maximum of value
  31883. * @returns The clamped value.
  31884. */
  31885. ColorCurves.clamp = function (value, min, max) {
  31886. return Math.min(Math.max(value, min), max);
  31887. };
  31888. /**
  31889. * Clones the current color curve instance.
  31890. * @return The cloned curves
  31891. */
  31892. ColorCurves.prototype.clone = function () {
  31893. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  31894. };
  31895. /**
  31896. * Serializes the current color curve instance to a json representation.
  31897. * @return a JSON representation
  31898. */
  31899. ColorCurves.prototype.serialize = function () {
  31900. return BABYLON.SerializationHelper.Serialize(this);
  31901. };
  31902. /**
  31903. * Parses the color curve from a json representation.
  31904. * @param source the JSON source to parse
  31905. * @return The parsed curves
  31906. */
  31907. ColorCurves.Parse = function (source) {
  31908. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  31909. };
  31910. __decorate([
  31911. BABYLON.serialize()
  31912. ], ColorCurves.prototype, "_globalHue", void 0);
  31913. __decorate([
  31914. BABYLON.serialize()
  31915. ], ColorCurves.prototype, "_globalDensity", void 0);
  31916. __decorate([
  31917. BABYLON.serialize()
  31918. ], ColorCurves.prototype, "_globalSaturation", void 0);
  31919. __decorate([
  31920. BABYLON.serialize()
  31921. ], ColorCurves.prototype, "_globalExposure", void 0);
  31922. __decorate([
  31923. BABYLON.serialize()
  31924. ], ColorCurves.prototype, "_highlightsHue", void 0);
  31925. __decorate([
  31926. BABYLON.serialize()
  31927. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  31928. __decorate([
  31929. BABYLON.serialize()
  31930. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  31931. __decorate([
  31932. BABYLON.serialize()
  31933. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  31934. __decorate([
  31935. BABYLON.serialize()
  31936. ], ColorCurves.prototype, "_midtonesHue", void 0);
  31937. __decorate([
  31938. BABYLON.serialize()
  31939. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  31940. __decorate([
  31941. BABYLON.serialize()
  31942. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  31943. __decorate([
  31944. BABYLON.serialize()
  31945. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  31946. return ColorCurves;
  31947. }());
  31948. BABYLON.ColorCurves = ColorCurves;
  31949. })(BABYLON || (BABYLON = {}));
  31950. //# sourceMappingURL=babylon.colorCurves.js.map
  31951. var BABYLON;
  31952. (function (BABYLON) {
  31953. var StandardMaterialDefines = (function (_super) {
  31954. __extends(StandardMaterialDefines, _super);
  31955. function StandardMaterialDefines() {
  31956. var _this = _super.call(this) || this;
  31957. _this.MAINUV1 = false;
  31958. _this.MAINUV2 = false;
  31959. _this.DIFFUSE = false;
  31960. _this.DIFFUSEDIRECTUV = 0;
  31961. _this.AMBIENT = false;
  31962. _this.AMBIENTDIRECTUV = 0;
  31963. _this.OPACITY = false;
  31964. _this.OPACITYDIRECTUV = 0;
  31965. _this.OPACITYRGB = false;
  31966. _this.REFLECTION = false;
  31967. _this.EMISSIVE = false;
  31968. _this.EMISSIVEDIRECTUV = 0;
  31969. _this.SPECULAR = false;
  31970. _this.SPECULARDIRECTUV = 0;
  31971. _this.BUMP = false;
  31972. _this.BUMPDIRECTUV = 0;
  31973. _this.PARALLAX = false;
  31974. _this.PARALLAXOCCLUSION = false;
  31975. _this.SPECULAROVERALPHA = false;
  31976. _this.CLIPPLANE = false;
  31977. _this.ALPHATEST = false;
  31978. _this.DEPTHPREPASS = false;
  31979. _this.ALPHAFROMDIFFUSE = false;
  31980. _this.POINTSIZE = false;
  31981. _this.FOG = false;
  31982. _this.SPECULARTERM = false;
  31983. _this.DIFFUSEFRESNEL = false;
  31984. _this.OPACITYFRESNEL = false;
  31985. _this.REFLECTIONFRESNEL = false;
  31986. _this.REFRACTIONFRESNEL = false;
  31987. _this.EMISSIVEFRESNEL = false;
  31988. _this.FRESNEL = false;
  31989. _this.NORMAL = false;
  31990. _this.UV1 = false;
  31991. _this.UV2 = false;
  31992. _this.VERTEXCOLOR = false;
  31993. _this.VERTEXALPHA = false;
  31994. _this.NUM_BONE_INFLUENCERS = 0;
  31995. _this.BonesPerMesh = 0;
  31996. _this.INSTANCES = false;
  31997. _this.GLOSSINESS = false;
  31998. _this.ROUGHNESS = false;
  31999. _this.EMISSIVEASILLUMINATION = false;
  32000. _this.LINKEMISSIVEWITHDIFFUSE = false;
  32001. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  32002. _this.LIGHTMAP = false;
  32003. _this.LIGHTMAPDIRECTUV = 0;
  32004. _this.USELIGHTMAPASSHADOWMAP = false;
  32005. _this.REFLECTIONMAP_3D = false;
  32006. _this.REFLECTIONMAP_SPHERICAL = false;
  32007. _this.REFLECTIONMAP_PLANAR = false;
  32008. _this.REFLECTIONMAP_CUBIC = false;
  32009. _this.REFLECTIONMAP_PROJECTION = false;
  32010. _this.REFLECTIONMAP_SKYBOX = false;
  32011. _this.REFLECTIONMAP_EXPLICIT = false;
  32012. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  32013. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  32014. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  32015. _this.INVERTCUBICMAP = false;
  32016. _this.LOGARITHMICDEPTH = false;
  32017. _this.REFRACTION = false;
  32018. _this.REFRACTIONMAP_3D = false;
  32019. _this.REFLECTIONOVERALPHA = false;
  32020. _this.TWOSIDEDLIGHTING = false;
  32021. _this.SHADOWFLOAT = false;
  32022. _this.MORPHTARGETS = false;
  32023. _this.MORPHTARGETS_NORMAL = false;
  32024. _this.MORPHTARGETS_TANGENT = false;
  32025. _this.NUM_MORPH_INFLUENCERS = 0;
  32026. _this.IMAGEPROCESSING = false;
  32027. _this.VIGNETTE = false;
  32028. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  32029. _this.VIGNETTEBLENDMODEOPAQUE = false;
  32030. _this.TONEMAPPING = false;
  32031. _this.CONTRAST = false;
  32032. _this.COLORCURVES = false;
  32033. _this.COLORGRADING = false;
  32034. _this.SAMPLER3DGREENDEPTH = false;
  32035. _this.SAMPLER3DBGRMAP = false;
  32036. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  32037. _this.EXPOSURE = false;
  32038. _this.rebuild();
  32039. return _this;
  32040. }
  32041. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  32042. var modes = [
  32043. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  32044. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  32045. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  32046. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  32047. ];
  32048. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  32049. var mode = modes_1[_i];
  32050. this[mode] = (mode === modeToEnable);
  32051. }
  32052. };
  32053. return StandardMaterialDefines;
  32054. }(BABYLON.MaterialDefines));
  32055. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  32056. var StandardMaterial = (function (_super) {
  32057. __extends(StandardMaterial, _super);
  32058. function StandardMaterial(name, scene) {
  32059. var _this = _super.call(this, name, scene) || this;
  32060. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  32061. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  32062. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  32063. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  32064. _this.specularPower = 64;
  32065. _this._useAlphaFromDiffuseTexture = false;
  32066. _this._useEmissiveAsIllumination = false;
  32067. _this._linkEmissiveWithDiffuse = false;
  32068. _this._useSpecularOverAlpha = false;
  32069. _this._useReflectionOverAlpha = false;
  32070. _this._disableLighting = false;
  32071. _this._useParallax = false;
  32072. _this._useParallaxOcclusion = false;
  32073. _this.parallaxScaleBias = 0.05;
  32074. _this._roughness = 0;
  32075. _this.indexOfRefraction = 0.98;
  32076. _this.invertRefractionY = true;
  32077. _this._useLightmapAsShadowmap = false;
  32078. _this._useReflectionFresnelFromSpecular = false;
  32079. _this._useGlossinessFromSpecularMapAlpha = false;
  32080. _this._maxSimultaneousLights = 4;
  32081. /**
  32082. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  32083. */
  32084. _this._invertNormalMapX = false;
  32085. /**
  32086. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  32087. */
  32088. _this._invertNormalMapY = false;
  32089. /**
  32090. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  32091. */
  32092. _this._twoSidedLighting = false;
  32093. _this._renderTargets = new BABYLON.SmartArray(16);
  32094. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  32095. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  32096. // Setup the default processing configuration to the scene.
  32097. _this._attachImageProcessingConfiguration(null);
  32098. _this.getRenderTargetTextures = function () {
  32099. _this._renderTargets.reset();
  32100. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  32101. _this._renderTargets.push(_this._reflectionTexture);
  32102. }
  32103. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  32104. _this._renderTargets.push(_this._refractionTexture);
  32105. }
  32106. return _this._renderTargets;
  32107. };
  32108. return _this;
  32109. }
  32110. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  32111. /**
  32112. * Gets the image processing configuration used either in this material.
  32113. */
  32114. get: function () {
  32115. return this._imageProcessingConfiguration;
  32116. },
  32117. /**
  32118. * Sets the Default image processing configuration used either in the this material.
  32119. *
  32120. * If sets to null, the scene one is in use.
  32121. */
  32122. set: function (value) {
  32123. this._attachImageProcessingConfiguration(value);
  32124. // Ensure the effect will be rebuilt.
  32125. this._markAllSubMeshesAsTexturesDirty();
  32126. },
  32127. enumerable: true,
  32128. configurable: true
  32129. });
  32130. /**
  32131. * Attaches a new image processing configuration to the Standard Material.
  32132. * @param configuration
  32133. */
  32134. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  32135. var _this = this;
  32136. if (configuration === this._imageProcessingConfiguration) {
  32137. return;
  32138. }
  32139. // Detaches observer.
  32140. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  32141. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  32142. }
  32143. // Pick the scene configuration if needed.
  32144. if (!configuration) {
  32145. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  32146. }
  32147. else {
  32148. this._imageProcessingConfiguration = configuration;
  32149. }
  32150. // Attaches observer.
  32151. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  32152. _this._markAllSubMeshesAsImageProcessingDirty();
  32153. });
  32154. };
  32155. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  32156. /**
  32157. * Gets wether the color curves effect is enabled.
  32158. */
  32159. get: function () {
  32160. return this.imageProcessingConfiguration.colorCurvesEnabled;
  32161. },
  32162. /**
  32163. * Sets wether the color curves effect is enabled.
  32164. */
  32165. set: function (value) {
  32166. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  32167. },
  32168. enumerable: true,
  32169. configurable: true
  32170. });
  32171. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  32172. /**
  32173. * Gets wether the color grading effect is enabled.
  32174. */
  32175. get: function () {
  32176. return this.imageProcessingConfiguration.colorGradingEnabled;
  32177. },
  32178. /**
  32179. * Gets wether the color grading effect is enabled.
  32180. */
  32181. set: function (value) {
  32182. this.imageProcessingConfiguration.colorGradingEnabled = value;
  32183. },
  32184. enumerable: true,
  32185. configurable: true
  32186. });
  32187. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  32188. /**
  32189. * Gets wether tonemapping is enabled or not.
  32190. */
  32191. get: function () {
  32192. return this._imageProcessingConfiguration.toneMappingEnabled;
  32193. },
  32194. /**
  32195. * Sets wether tonemapping is enabled or not
  32196. */
  32197. set: function (value) {
  32198. this._imageProcessingConfiguration.toneMappingEnabled = value;
  32199. },
  32200. enumerable: true,
  32201. configurable: true
  32202. });
  32203. ;
  32204. ;
  32205. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  32206. /**
  32207. * The camera exposure used on this material.
  32208. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  32209. * This corresponds to a photographic exposure.
  32210. */
  32211. get: function () {
  32212. return this._imageProcessingConfiguration.exposure;
  32213. },
  32214. /**
  32215. * The camera exposure used on this material.
  32216. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  32217. * This corresponds to a photographic exposure.
  32218. */
  32219. set: function (value) {
  32220. this._imageProcessingConfiguration.exposure = value;
  32221. },
  32222. enumerable: true,
  32223. configurable: true
  32224. });
  32225. ;
  32226. ;
  32227. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  32228. /**
  32229. * Gets The camera contrast used on this material.
  32230. */
  32231. get: function () {
  32232. return this._imageProcessingConfiguration.contrast;
  32233. },
  32234. /**
  32235. * Sets The camera contrast used on this material.
  32236. */
  32237. set: function (value) {
  32238. this._imageProcessingConfiguration.contrast = value;
  32239. },
  32240. enumerable: true,
  32241. configurable: true
  32242. });
  32243. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  32244. /**
  32245. * Gets the Color Grading 2D Lookup Texture.
  32246. */
  32247. get: function () {
  32248. return this._imageProcessingConfiguration.colorGradingTexture;
  32249. },
  32250. /**
  32251. * Sets the Color Grading 2D Lookup Texture.
  32252. */
  32253. set: function (value) {
  32254. this._imageProcessingConfiguration.colorGradingTexture = value;
  32255. },
  32256. enumerable: true,
  32257. configurable: true
  32258. });
  32259. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  32260. /**
  32261. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32262. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32263. * 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;
  32264. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32265. */
  32266. get: function () {
  32267. return this._imageProcessingConfiguration.colorCurves;
  32268. },
  32269. /**
  32270. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32271. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32272. * 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;
  32273. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32274. */
  32275. set: function (value) {
  32276. this._imageProcessingConfiguration.colorCurves = value;
  32277. },
  32278. enumerable: true,
  32279. configurable: true
  32280. });
  32281. StandardMaterial.prototype.getClassName = function () {
  32282. return "StandardMaterial";
  32283. };
  32284. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  32285. get: function () {
  32286. return this._useLogarithmicDepth;
  32287. },
  32288. set: function (value) {
  32289. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  32290. this._markAllSubMeshesAsMiscDirty();
  32291. },
  32292. enumerable: true,
  32293. configurable: true
  32294. });
  32295. StandardMaterial.prototype.needAlphaBlending = function () {
  32296. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  32297. };
  32298. StandardMaterial.prototype.needAlphaTesting = function () {
  32299. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  32300. };
  32301. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  32302. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  32303. };
  32304. StandardMaterial.prototype.getAlphaTestTexture = function () {
  32305. return this._diffuseTexture;
  32306. };
  32307. /**
  32308. * Child classes can use it to update shaders
  32309. */
  32310. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  32311. if (this.isFrozen) {
  32312. if (this._wasPreviouslyReady && subMesh.effect) {
  32313. return true;
  32314. }
  32315. }
  32316. if (!subMesh._materialDefines) {
  32317. subMesh._materialDefines = new StandardMaterialDefines();
  32318. }
  32319. var scene = this.getScene();
  32320. var defines = subMesh._materialDefines;
  32321. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  32322. if (defines._renderId === scene.getRenderId()) {
  32323. return true;
  32324. }
  32325. }
  32326. var engine = scene.getEngine();
  32327. // Lights
  32328. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  32329. // Textures
  32330. if (defines._areTexturesDirty) {
  32331. defines._needUVs = false;
  32332. defines.MAINUV1 = false;
  32333. defines.MAINUV2 = false;
  32334. if (scene.texturesEnabled) {
  32335. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  32336. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  32337. return false;
  32338. }
  32339. else {
  32340. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  32341. }
  32342. }
  32343. else {
  32344. defines.DIFFUSE = false;
  32345. }
  32346. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  32347. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  32348. return false;
  32349. }
  32350. else {
  32351. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  32352. }
  32353. }
  32354. else {
  32355. defines.AMBIENT = false;
  32356. }
  32357. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  32358. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  32359. return false;
  32360. }
  32361. else {
  32362. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  32363. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  32364. }
  32365. }
  32366. else {
  32367. defines.OPACITY = false;
  32368. }
  32369. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  32370. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  32371. return false;
  32372. }
  32373. else {
  32374. defines._needNormals = true;
  32375. defines.REFLECTION = true;
  32376. defines.ROUGHNESS = (this._roughness > 0);
  32377. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  32378. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  32379. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  32380. switch (this._reflectionTexture.coordinatesMode) {
  32381. case BABYLON.Texture.CUBIC_MODE:
  32382. case BABYLON.Texture.INVCUBIC_MODE:
  32383. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  32384. break;
  32385. case BABYLON.Texture.EXPLICIT_MODE:
  32386. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  32387. break;
  32388. case BABYLON.Texture.PLANAR_MODE:
  32389. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  32390. break;
  32391. case BABYLON.Texture.PROJECTION_MODE:
  32392. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  32393. break;
  32394. case BABYLON.Texture.SKYBOX_MODE:
  32395. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  32396. break;
  32397. case BABYLON.Texture.SPHERICAL_MODE:
  32398. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  32399. break;
  32400. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  32401. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  32402. break;
  32403. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  32404. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  32405. break;
  32406. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  32407. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  32408. break;
  32409. }
  32410. }
  32411. }
  32412. else {
  32413. defines.REFLECTION = false;
  32414. }
  32415. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  32416. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  32417. return false;
  32418. }
  32419. else {
  32420. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  32421. }
  32422. }
  32423. else {
  32424. defines.EMISSIVE = false;
  32425. }
  32426. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  32427. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  32428. return false;
  32429. }
  32430. else {
  32431. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  32432. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  32433. }
  32434. }
  32435. else {
  32436. defines.LIGHTMAP = false;
  32437. }
  32438. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  32439. if (!this._specularTexture.isReadyOrNotBlocking()) {
  32440. return false;
  32441. }
  32442. else {
  32443. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  32444. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  32445. }
  32446. }
  32447. else {
  32448. defines.SPECULAR = false;
  32449. }
  32450. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  32451. // Bump texure can not be not blocking.
  32452. if (!this._bumpTexture.isReady()) {
  32453. return false;
  32454. }
  32455. else {
  32456. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  32457. defines.PARALLAX = this._useParallax;
  32458. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  32459. }
  32460. }
  32461. else {
  32462. defines.BUMP = false;
  32463. }
  32464. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  32465. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  32466. return false;
  32467. }
  32468. else {
  32469. defines._needUVs = true;
  32470. defines.REFRACTION = true;
  32471. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  32472. }
  32473. }
  32474. else {
  32475. defines.REFRACTION = false;
  32476. }
  32477. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  32478. }
  32479. else {
  32480. defines.DIFFUSE = false;
  32481. defines.AMBIENT = false;
  32482. defines.OPACITY = false;
  32483. defines.REFLECTION = false;
  32484. defines.EMISSIVE = false;
  32485. defines.LIGHTMAP = false;
  32486. defines.BUMP = false;
  32487. defines.REFRACTION = false;
  32488. }
  32489. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  32490. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  32491. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  32492. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  32493. }
  32494. if (defines._areImageProcessingDirty) {
  32495. if (!this._imageProcessingConfiguration.isReady()) {
  32496. return false;
  32497. }
  32498. this._imageProcessingConfiguration.prepareDefines(defines);
  32499. }
  32500. if (defines._areFresnelDirty) {
  32501. if (StandardMaterial.FresnelEnabled) {
  32502. // Fresnel
  32503. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  32504. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  32505. this._reflectionFresnelParameters) {
  32506. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  32507. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  32508. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  32509. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  32510. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  32511. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  32512. defines._needNormals = true;
  32513. defines.FRESNEL = true;
  32514. }
  32515. }
  32516. else {
  32517. defines.FRESNEL = false;
  32518. }
  32519. }
  32520. // Misc.
  32521. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  32522. // Attribs
  32523. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  32524. // Values that need to be evaluated on every frame
  32525. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  32526. // Get correct effect
  32527. if (defines.isDirty) {
  32528. defines.markAsProcessed();
  32529. scene.resetCachedMaterial();
  32530. // Fallbacks
  32531. var fallbacks = new BABYLON.EffectFallbacks();
  32532. if (defines.REFLECTION) {
  32533. fallbacks.addFallback(0, "REFLECTION");
  32534. }
  32535. if (defines.SPECULAR) {
  32536. fallbacks.addFallback(0, "SPECULAR");
  32537. }
  32538. if (defines.BUMP) {
  32539. fallbacks.addFallback(0, "BUMP");
  32540. }
  32541. if (defines.PARALLAX) {
  32542. fallbacks.addFallback(1, "PARALLAX");
  32543. }
  32544. if (defines.PARALLAXOCCLUSION) {
  32545. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  32546. }
  32547. if (defines.SPECULAROVERALPHA) {
  32548. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  32549. }
  32550. if (defines.FOG) {
  32551. fallbacks.addFallback(1, "FOG");
  32552. }
  32553. if (defines.POINTSIZE) {
  32554. fallbacks.addFallback(0, "POINTSIZE");
  32555. }
  32556. if (defines.LOGARITHMICDEPTH) {
  32557. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  32558. }
  32559. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  32560. if (defines.SPECULARTERM) {
  32561. fallbacks.addFallback(0, "SPECULARTERM");
  32562. }
  32563. if (defines.DIFFUSEFRESNEL) {
  32564. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  32565. }
  32566. if (defines.OPACITYFRESNEL) {
  32567. fallbacks.addFallback(2, "OPACITYFRESNEL");
  32568. }
  32569. if (defines.REFLECTIONFRESNEL) {
  32570. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  32571. }
  32572. if (defines.EMISSIVEFRESNEL) {
  32573. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  32574. }
  32575. if (defines.FRESNEL) {
  32576. fallbacks.addFallback(4, "FRESNEL");
  32577. }
  32578. //Attributes
  32579. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32580. if (defines.NORMAL) {
  32581. attribs.push(BABYLON.VertexBuffer.NormalKind);
  32582. }
  32583. if (defines.UV1) {
  32584. attribs.push(BABYLON.VertexBuffer.UVKind);
  32585. }
  32586. if (defines.UV2) {
  32587. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32588. }
  32589. if (defines.VERTEXCOLOR) {
  32590. attribs.push(BABYLON.VertexBuffer.ColorKind);
  32591. }
  32592. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  32593. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  32594. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  32595. var shaderName = "default";
  32596. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  32597. "vFogInfos", "vFogColor", "pointSize",
  32598. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  32599. "mBones",
  32600. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  32601. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  32602. "logarithmicDepthConstant", "vTangentSpaceParams"
  32603. ];
  32604. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  32605. var uniformBuffers = ["Material", "Scene"];
  32606. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  32607. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  32608. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  32609. uniformsNames: uniforms,
  32610. uniformBuffersNames: uniformBuffers,
  32611. samplers: samplers,
  32612. defines: defines,
  32613. maxSimultaneousLights: this._maxSimultaneousLights
  32614. });
  32615. if (this.customShaderNameResolve) {
  32616. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  32617. }
  32618. var join = defines.toString();
  32619. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  32620. attributes: attribs,
  32621. uniformsNames: uniforms,
  32622. uniformBuffersNames: uniformBuffers,
  32623. samplers: samplers,
  32624. defines: join,
  32625. fallbacks: fallbacks,
  32626. onCompiled: this.onCompiled,
  32627. onError: this.onError,
  32628. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  32629. }, engine), defines);
  32630. this.buildUniformLayout();
  32631. }
  32632. if (!subMesh.effect.isReady()) {
  32633. return false;
  32634. }
  32635. defines._renderId = scene.getRenderId();
  32636. this._wasPreviouslyReady = true;
  32637. return true;
  32638. };
  32639. StandardMaterial.prototype.buildUniformLayout = function () {
  32640. // Order is important !
  32641. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  32642. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  32643. this._uniformBuffer.addUniform("opacityParts", 4);
  32644. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  32645. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  32646. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  32647. this._uniformBuffer.addUniform("refractionRightColor", 4);
  32648. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  32649. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  32650. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  32651. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  32652. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  32653. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  32654. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  32655. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  32656. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  32657. this._uniformBuffer.addUniform("vBumpInfos", 3);
  32658. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  32659. this._uniformBuffer.addUniform("ambientMatrix", 16);
  32660. this._uniformBuffer.addUniform("opacityMatrix", 16);
  32661. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  32662. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  32663. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  32664. this._uniformBuffer.addUniform("specularMatrix", 16);
  32665. this._uniformBuffer.addUniform("bumpMatrix", 16);
  32666. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  32667. this._uniformBuffer.addUniform("refractionMatrix", 16);
  32668. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  32669. this._uniformBuffer.addUniform("vSpecularColor", 4);
  32670. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  32671. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  32672. this._uniformBuffer.addUniform("pointSize", 1);
  32673. this._uniformBuffer.create();
  32674. };
  32675. StandardMaterial.prototype.unbind = function () {
  32676. if (this._activeEffect) {
  32677. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  32678. this._activeEffect.setTexture("reflection2DSampler", null);
  32679. }
  32680. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  32681. this._activeEffect.setTexture("refraction2DSampler", null);
  32682. }
  32683. }
  32684. _super.prototype.unbind.call(this);
  32685. };
  32686. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  32687. var scene = this.getScene();
  32688. var defines = subMesh._materialDefines;
  32689. if (!defines) {
  32690. return;
  32691. }
  32692. var effect = subMesh.effect;
  32693. this._activeEffect = effect;
  32694. // Matrices
  32695. this.bindOnlyWorldMatrix(world);
  32696. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  32697. // Bones
  32698. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  32699. if (mustRebind) {
  32700. this._uniformBuffer.bindToEffect(effect, "Material");
  32701. this.bindViewProjection(effect);
  32702. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  32703. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  32704. // Fresnel
  32705. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  32706. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  32707. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  32708. }
  32709. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  32710. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  32711. }
  32712. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  32713. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  32714. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  32715. }
  32716. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  32717. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  32718. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  32719. }
  32720. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  32721. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  32722. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  32723. }
  32724. }
  32725. // Textures
  32726. if (scene.texturesEnabled) {
  32727. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  32728. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  32729. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  32730. }
  32731. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  32732. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  32733. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  32734. }
  32735. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  32736. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  32737. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  32738. }
  32739. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  32740. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  32741. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  32742. }
  32743. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  32744. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  32745. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  32746. }
  32747. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  32748. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  32749. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  32750. }
  32751. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  32752. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  32753. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  32754. }
  32755. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  32756. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  32757. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  32758. if (scene._mirroredCameraPosition) {
  32759. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this.invertNormalMapX ? 1.0 : -1.0, this.invertNormalMapY ? 1.0 : -1.0);
  32760. }
  32761. else {
  32762. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this.invertNormalMapX ? -1.0 : 1.0, this.invertNormalMapY ? -1.0 : 1.0);
  32763. }
  32764. }
  32765. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  32766. var depth = 1.0;
  32767. if (!this._refractionTexture.isCube) {
  32768. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  32769. if (this._refractionTexture.depth) {
  32770. depth = this._refractionTexture.depth;
  32771. }
  32772. }
  32773. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  32774. }
  32775. }
  32776. // Point size
  32777. if (this.pointsCloud) {
  32778. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  32779. }
  32780. if (defines.SPECULARTERM) {
  32781. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  32782. }
  32783. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  32784. // Diffuse
  32785. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  32786. }
  32787. // Textures
  32788. if (scene.texturesEnabled) {
  32789. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  32790. effect.setTexture("diffuseSampler", this._diffuseTexture);
  32791. }
  32792. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  32793. effect.setTexture("ambientSampler", this._ambientTexture);
  32794. }
  32795. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  32796. effect.setTexture("opacitySampler", this._opacityTexture);
  32797. }
  32798. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  32799. if (this._reflectionTexture.isCube) {
  32800. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  32801. }
  32802. else {
  32803. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  32804. }
  32805. }
  32806. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  32807. effect.setTexture("emissiveSampler", this._emissiveTexture);
  32808. }
  32809. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  32810. effect.setTexture("lightmapSampler", this._lightmapTexture);
  32811. }
  32812. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  32813. effect.setTexture("specularSampler", this._specularTexture);
  32814. }
  32815. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  32816. effect.setTexture("bumpSampler", this._bumpTexture);
  32817. }
  32818. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  32819. var depth = 1.0;
  32820. if (this._refractionTexture.isCube) {
  32821. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  32822. }
  32823. else {
  32824. effect.setTexture("refraction2DSampler", this._refractionTexture);
  32825. }
  32826. }
  32827. }
  32828. // Clip plane
  32829. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  32830. // Colors
  32831. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  32832. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  32833. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  32834. }
  32835. if (mustRebind || !this.isFrozen) {
  32836. // Lights
  32837. if (scene.lightsEnabled && !this._disableLighting) {
  32838. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  32839. }
  32840. // View
  32841. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  32842. this.bindView(effect);
  32843. }
  32844. // Fog
  32845. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  32846. // Morph targets
  32847. if (defines.NUM_MORPH_INFLUENCERS) {
  32848. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  32849. }
  32850. // Log. depth
  32851. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  32852. // image processing
  32853. this._imageProcessingConfiguration.bind(this._activeEffect);
  32854. }
  32855. this._uniformBuffer.update();
  32856. this._afterBind(mesh, this._activeEffect);
  32857. };
  32858. StandardMaterial.prototype.getAnimatables = function () {
  32859. var results = [];
  32860. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  32861. results.push(this._diffuseTexture);
  32862. }
  32863. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  32864. results.push(this._ambientTexture);
  32865. }
  32866. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  32867. results.push(this._opacityTexture);
  32868. }
  32869. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  32870. results.push(this._reflectionTexture);
  32871. }
  32872. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  32873. results.push(this._emissiveTexture);
  32874. }
  32875. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  32876. results.push(this._specularTexture);
  32877. }
  32878. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  32879. results.push(this._bumpTexture);
  32880. }
  32881. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  32882. results.push(this._lightmapTexture);
  32883. }
  32884. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  32885. results.push(this._refractionTexture);
  32886. }
  32887. return results;
  32888. };
  32889. StandardMaterial.prototype.getActiveTextures = function () {
  32890. var activeTextures = _super.prototype.getActiveTextures.call(this);
  32891. if (this._diffuseTexture) {
  32892. activeTextures.push(this._diffuseTexture);
  32893. }
  32894. if (this._ambientTexture) {
  32895. activeTextures.push(this._ambientTexture);
  32896. }
  32897. if (this._opacityTexture) {
  32898. activeTextures.push(this._opacityTexture);
  32899. }
  32900. if (this._reflectionTexture) {
  32901. activeTextures.push(this._reflectionTexture);
  32902. }
  32903. if (this._emissiveTexture) {
  32904. activeTextures.push(this._emissiveTexture);
  32905. }
  32906. if (this._specularTexture) {
  32907. activeTextures.push(this._specularTexture);
  32908. }
  32909. if (this._bumpTexture) {
  32910. activeTextures.push(this._bumpTexture);
  32911. }
  32912. if (this._lightmapTexture) {
  32913. activeTextures.push(this._lightmapTexture);
  32914. }
  32915. if (this._refractionTexture) {
  32916. activeTextures.push(this._refractionTexture);
  32917. }
  32918. return activeTextures;
  32919. };
  32920. StandardMaterial.prototype.hasTexture = function (texture) {
  32921. if (_super.prototype.hasTexture.call(this, texture)) {
  32922. return true;
  32923. }
  32924. if (this._diffuseTexture === texture) {
  32925. return true;
  32926. }
  32927. if (this._ambientTexture === texture) {
  32928. return true;
  32929. }
  32930. if (this._opacityTexture === texture) {
  32931. return true;
  32932. }
  32933. if (this._reflectionTexture === texture) {
  32934. return true;
  32935. }
  32936. if (this._emissiveTexture === texture) {
  32937. return true;
  32938. }
  32939. if (this._specularTexture === texture) {
  32940. return true;
  32941. }
  32942. if (this._bumpTexture === texture) {
  32943. return true;
  32944. }
  32945. if (this._lightmapTexture === texture) {
  32946. return true;
  32947. }
  32948. if (this._refractionTexture === texture) {
  32949. return true;
  32950. }
  32951. return false;
  32952. };
  32953. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32954. if (forceDisposeTextures) {
  32955. if (this._diffuseTexture) {
  32956. this._diffuseTexture.dispose();
  32957. }
  32958. if (this._ambientTexture) {
  32959. this._ambientTexture.dispose();
  32960. }
  32961. if (this._opacityTexture) {
  32962. this._opacityTexture.dispose();
  32963. }
  32964. if (this._reflectionTexture) {
  32965. this._reflectionTexture.dispose();
  32966. }
  32967. if (this._emissiveTexture) {
  32968. this._emissiveTexture.dispose();
  32969. }
  32970. if (this._specularTexture) {
  32971. this._specularTexture.dispose();
  32972. }
  32973. if (this._bumpTexture) {
  32974. this._bumpTexture.dispose();
  32975. }
  32976. if (this._lightmapTexture) {
  32977. this._lightmapTexture.dispose();
  32978. }
  32979. if (this._refractionTexture) {
  32980. this._refractionTexture.dispose();
  32981. }
  32982. }
  32983. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  32984. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  32985. }
  32986. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  32987. };
  32988. StandardMaterial.prototype.clone = function (name) {
  32989. var _this = this;
  32990. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  32991. result.name = name;
  32992. result.id = name;
  32993. return result;
  32994. };
  32995. StandardMaterial.prototype.serialize = function () {
  32996. return BABYLON.SerializationHelper.Serialize(this);
  32997. };
  32998. // Statics
  32999. StandardMaterial.Parse = function (source, scene, rootUrl) {
  33000. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  33001. };
  33002. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  33003. get: function () {
  33004. return StandardMaterial._DiffuseTextureEnabled;
  33005. },
  33006. set: function (value) {
  33007. if (StandardMaterial._DiffuseTextureEnabled === value) {
  33008. return;
  33009. }
  33010. StandardMaterial._DiffuseTextureEnabled = value;
  33011. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33012. },
  33013. enumerable: true,
  33014. configurable: true
  33015. });
  33016. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  33017. get: function () {
  33018. return StandardMaterial._AmbientTextureEnabled;
  33019. },
  33020. set: function (value) {
  33021. if (StandardMaterial._AmbientTextureEnabled === value) {
  33022. return;
  33023. }
  33024. StandardMaterial._AmbientTextureEnabled = value;
  33025. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33026. },
  33027. enumerable: true,
  33028. configurable: true
  33029. });
  33030. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  33031. get: function () {
  33032. return StandardMaterial._OpacityTextureEnabled;
  33033. },
  33034. set: function (value) {
  33035. if (StandardMaterial._OpacityTextureEnabled === value) {
  33036. return;
  33037. }
  33038. StandardMaterial._OpacityTextureEnabled = value;
  33039. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33040. },
  33041. enumerable: true,
  33042. configurable: true
  33043. });
  33044. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  33045. get: function () {
  33046. return StandardMaterial._ReflectionTextureEnabled;
  33047. },
  33048. set: function (value) {
  33049. if (StandardMaterial._ReflectionTextureEnabled === value) {
  33050. return;
  33051. }
  33052. StandardMaterial._ReflectionTextureEnabled = value;
  33053. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33054. },
  33055. enumerable: true,
  33056. configurable: true
  33057. });
  33058. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  33059. get: function () {
  33060. return StandardMaterial._EmissiveTextureEnabled;
  33061. },
  33062. set: function (value) {
  33063. if (StandardMaterial._EmissiveTextureEnabled === value) {
  33064. return;
  33065. }
  33066. StandardMaterial._EmissiveTextureEnabled = value;
  33067. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33068. },
  33069. enumerable: true,
  33070. configurable: true
  33071. });
  33072. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  33073. get: function () {
  33074. return StandardMaterial._SpecularTextureEnabled;
  33075. },
  33076. set: function (value) {
  33077. if (StandardMaterial._SpecularTextureEnabled === value) {
  33078. return;
  33079. }
  33080. StandardMaterial._SpecularTextureEnabled = value;
  33081. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33082. },
  33083. enumerable: true,
  33084. configurable: true
  33085. });
  33086. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  33087. get: function () {
  33088. return StandardMaterial._BumpTextureEnabled;
  33089. },
  33090. set: function (value) {
  33091. if (StandardMaterial._BumpTextureEnabled === value) {
  33092. return;
  33093. }
  33094. StandardMaterial._BumpTextureEnabled = value;
  33095. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33096. },
  33097. enumerable: true,
  33098. configurable: true
  33099. });
  33100. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  33101. get: function () {
  33102. return StandardMaterial._LightmapTextureEnabled;
  33103. },
  33104. set: function (value) {
  33105. if (StandardMaterial._LightmapTextureEnabled === value) {
  33106. return;
  33107. }
  33108. StandardMaterial._LightmapTextureEnabled = value;
  33109. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33110. },
  33111. enumerable: true,
  33112. configurable: true
  33113. });
  33114. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  33115. get: function () {
  33116. return StandardMaterial._RefractionTextureEnabled;
  33117. },
  33118. set: function (value) {
  33119. if (StandardMaterial._RefractionTextureEnabled === value) {
  33120. return;
  33121. }
  33122. StandardMaterial._RefractionTextureEnabled = value;
  33123. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33124. },
  33125. enumerable: true,
  33126. configurable: true
  33127. });
  33128. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  33129. get: function () {
  33130. return StandardMaterial._ColorGradingTextureEnabled;
  33131. },
  33132. set: function (value) {
  33133. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  33134. return;
  33135. }
  33136. StandardMaterial._ColorGradingTextureEnabled = value;
  33137. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  33138. },
  33139. enumerable: true,
  33140. configurable: true
  33141. });
  33142. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  33143. get: function () {
  33144. return StandardMaterial._FresnelEnabled;
  33145. },
  33146. set: function (value) {
  33147. if (StandardMaterial._FresnelEnabled === value) {
  33148. return;
  33149. }
  33150. StandardMaterial._FresnelEnabled = value;
  33151. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  33152. },
  33153. enumerable: true,
  33154. configurable: true
  33155. });
  33156. // Flags used to enable or disable a type of texture for all Standard Materials
  33157. StandardMaterial._DiffuseTextureEnabled = true;
  33158. StandardMaterial._AmbientTextureEnabled = true;
  33159. StandardMaterial._OpacityTextureEnabled = true;
  33160. StandardMaterial._ReflectionTextureEnabled = true;
  33161. StandardMaterial._EmissiveTextureEnabled = true;
  33162. StandardMaterial._SpecularTextureEnabled = true;
  33163. StandardMaterial._BumpTextureEnabled = true;
  33164. StandardMaterial._LightmapTextureEnabled = true;
  33165. StandardMaterial._RefractionTextureEnabled = true;
  33166. StandardMaterial._ColorGradingTextureEnabled = true;
  33167. StandardMaterial._FresnelEnabled = true;
  33168. __decorate([
  33169. BABYLON.serializeAsTexture("diffuseTexture")
  33170. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  33171. __decorate([
  33172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33173. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  33174. __decorate([
  33175. BABYLON.serializeAsTexture("ambientTexture")
  33176. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  33177. __decorate([
  33178. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33179. ], StandardMaterial.prototype, "ambientTexture", void 0);
  33180. __decorate([
  33181. BABYLON.serializeAsTexture("opacityTexture")
  33182. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  33183. __decorate([
  33184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33185. ], StandardMaterial.prototype, "opacityTexture", void 0);
  33186. __decorate([
  33187. BABYLON.serializeAsTexture("reflectionTexture")
  33188. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  33189. __decorate([
  33190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33191. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  33192. __decorate([
  33193. BABYLON.serializeAsTexture("emissiveTexture")
  33194. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  33195. __decorate([
  33196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33197. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  33198. __decorate([
  33199. BABYLON.serializeAsTexture("specularTexture")
  33200. ], StandardMaterial.prototype, "_specularTexture", void 0);
  33201. __decorate([
  33202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33203. ], StandardMaterial.prototype, "specularTexture", void 0);
  33204. __decorate([
  33205. BABYLON.serializeAsTexture("bumpTexture")
  33206. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  33207. __decorate([
  33208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33209. ], StandardMaterial.prototype, "bumpTexture", void 0);
  33210. __decorate([
  33211. BABYLON.serializeAsTexture("lightmapTexture")
  33212. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  33213. __decorate([
  33214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33215. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  33216. __decorate([
  33217. BABYLON.serializeAsTexture("refractionTexture")
  33218. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  33219. __decorate([
  33220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33221. ], StandardMaterial.prototype, "refractionTexture", void 0);
  33222. __decorate([
  33223. BABYLON.serializeAsColor3("ambient")
  33224. ], StandardMaterial.prototype, "ambientColor", void 0);
  33225. __decorate([
  33226. BABYLON.serializeAsColor3("diffuse")
  33227. ], StandardMaterial.prototype, "diffuseColor", void 0);
  33228. __decorate([
  33229. BABYLON.serializeAsColor3("specular")
  33230. ], StandardMaterial.prototype, "specularColor", void 0);
  33231. __decorate([
  33232. BABYLON.serializeAsColor3("emissive")
  33233. ], StandardMaterial.prototype, "emissiveColor", void 0);
  33234. __decorate([
  33235. BABYLON.serialize()
  33236. ], StandardMaterial.prototype, "specularPower", void 0);
  33237. __decorate([
  33238. BABYLON.serialize("useAlphaFromDiffuseTexture")
  33239. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  33240. __decorate([
  33241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33242. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  33243. __decorate([
  33244. BABYLON.serialize("useEmissiveAsIllumination")
  33245. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  33246. __decorate([
  33247. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33248. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  33249. __decorate([
  33250. BABYLON.serialize("linkEmissiveWithDiffuse")
  33251. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  33252. __decorate([
  33253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33254. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  33255. __decorate([
  33256. BABYLON.serialize("useSpecularOverAlpha")
  33257. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  33258. __decorate([
  33259. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33260. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  33261. __decorate([
  33262. BABYLON.serialize("useReflectionOverAlpha")
  33263. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  33264. __decorate([
  33265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33266. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  33267. __decorate([
  33268. BABYLON.serialize("disableLighting")
  33269. ], StandardMaterial.prototype, "_disableLighting", void 0);
  33270. __decorate([
  33271. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33272. ], StandardMaterial.prototype, "disableLighting", void 0);
  33273. __decorate([
  33274. BABYLON.serialize("useParallax")
  33275. ], StandardMaterial.prototype, "_useParallax", void 0);
  33276. __decorate([
  33277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33278. ], StandardMaterial.prototype, "useParallax", void 0);
  33279. __decorate([
  33280. BABYLON.serialize("useParallaxOcclusion")
  33281. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  33282. __decorate([
  33283. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33284. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  33285. __decorate([
  33286. BABYLON.serialize()
  33287. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  33288. __decorate([
  33289. BABYLON.serialize("roughness")
  33290. ], StandardMaterial.prototype, "_roughness", void 0);
  33291. __decorate([
  33292. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33293. ], StandardMaterial.prototype, "roughness", void 0);
  33294. __decorate([
  33295. BABYLON.serialize()
  33296. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  33297. __decorate([
  33298. BABYLON.serialize()
  33299. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  33300. __decorate([
  33301. BABYLON.serialize("useLightmapAsShadowmap")
  33302. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  33303. __decorate([
  33304. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33305. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  33306. __decorate([
  33307. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  33308. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  33309. __decorate([
  33310. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  33311. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  33312. __decorate([
  33313. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  33314. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  33315. __decorate([
  33316. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  33317. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  33318. __decorate([
  33319. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  33320. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  33321. __decorate([
  33322. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  33323. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  33324. __decorate([
  33325. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  33326. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  33327. __decorate([
  33328. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  33329. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  33330. __decorate([
  33331. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  33332. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  33333. __decorate([
  33334. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  33335. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  33336. __decorate([
  33337. BABYLON.serialize("useReflectionFresnelFromSpecular")
  33338. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  33339. __decorate([
  33340. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  33341. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  33342. __decorate([
  33343. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  33344. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  33345. __decorate([
  33346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33347. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  33348. __decorate([
  33349. BABYLON.serialize("maxSimultaneousLights")
  33350. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  33351. __decorate([
  33352. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33353. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  33354. __decorate([
  33355. BABYLON.serialize("invertNormalMapX")
  33356. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  33357. __decorate([
  33358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33359. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  33360. __decorate([
  33361. BABYLON.serialize("invertNormalMapY")
  33362. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  33363. __decorate([
  33364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33365. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  33366. __decorate([
  33367. BABYLON.serialize("twoSidedLighting")
  33368. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  33369. __decorate([
  33370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33371. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  33372. __decorate([
  33373. BABYLON.serialize()
  33374. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  33375. return StandardMaterial;
  33376. }(BABYLON.PushMaterial));
  33377. BABYLON.StandardMaterial = StandardMaterial;
  33378. })(BABYLON || (BABYLON = {}));
  33379. //# sourceMappingURL=babylon.standardMaterial.js.map
  33380. var BABYLON;
  33381. (function (BABYLON) {
  33382. var PBRMaterialDefines = (function (_super) {
  33383. __extends(PBRMaterialDefines, _super);
  33384. function PBRMaterialDefines() {
  33385. var _this = _super.call(this) || this;
  33386. _this.PBR = true;
  33387. _this.MAINUV1 = false;
  33388. _this.MAINUV2 = false;
  33389. _this.UV1 = false;
  33390. _this.UV2 = false;
  33391. _this.ALBEDO = false;
  33392. _this.ALBEDODIRECTUV = 0;
  33393. _this.VERTEXCOLOR = false;
  33394. _this.AMBIENT = false;
  33395. _this.AMBIENTDIRECTUV = 0;
  33396. _this.AMBIENTINGRAYSCALE = false;
  33397. _this.OPACITY = false;
  33398. _this.VERTEXALPHA = false;
  33399. _this.OPACITYDIRECTUV = 0;
  33400. _this.OPACITYRGB = false;
  33401. _this.ALPHATEST = false;
  33402. _this.DEPTHPREPASS = false;
  33403. _this.ALPHABLEND = false;
  33404. _this.ALPHAFROMALBEDO = false;
  33405. _this.ALPHATESTVALUE = 0.5;
  33406. _this.SPECULAROVERALPHA = false;
  33407. _this.RADIANCEOVERALPHA = false;
  33408. _this.ALPHAFRESNEL = false;
  33409. _this.PREMULTIPLYALPHA = false;
  33410. _this.EMISSIVE = false;
  33411. _this.EMISSIVEDIRECTUV = 0;
  33412. _this.REFLECTIVITY = false;
  33413. _this.REFLECTIVITYDIRECTUV = 0;
  33414. _this.SPECULARTERM = false;
  33415. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  33416. _this.MICROSURFACEAUTOMATIC = false;
  33417. _this.LODBASEDMICROSFURACE = false;
  33418. _this.MICROSURFACEMAP = false;
  33419. _this.MICROSURFACEMAPDIRECTUV = 0;
  33420. _this.METALLICWORKFLOW = false;
  33421. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  33422. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  33423. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  33424. _this.AOSTOREINMETALMAPRED = false;
  33425. _this.ENVIRONMENTBRDF = false;
  33426. _this.NORMAL = false;
  33427. _this.TANGENT = false;
  33428. _this.BUMP = false;
  33429. _this.BUMPDIRECTUV = 0;
  33430. _this.PARALLAX = false;
  33431. _this.PARALLAXOCCLUSION = false;
  33432. _this.NORMALXYSCALE = true;
  33433. _this.LIGHTMAP = false;
  33434. _this.LIGHTMAPDIRECTUV = 0;
  33435. _this.USELIGHTMAPASSHADOWMAP = false;
  33436. _this.REFLECTION = false;
  33437. _this.REFLECTIONMAP_3D = false;
  33438. _this.REFLECTIONMAP_SPHERICAL = false;
  33439. _this.REFLECTIONMAP_PLANAR = false;
  33440. _this.REFLECTIONMAP_CUBIC = false;
  33441. _this.REFLECTIONMAP_PROJECTION = false;
  33442. _this.REFLECTIONMAP_SKYBOX = false;
  33443. _this.REFLECTIONMAP_EXPLICIT = false;
  33444. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  33445. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  33446. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  33447. _this.INVERTCUBICMAP = false;
  33448. _this.USESPHERICALFROMREFLECTIONMAP = false;
  33449. _this.USESPHERICALINFRAGMENT = false;
  33450. _this.REFLECTIONMAP_OPPOSITEZ = false;
  33451. _this.LODINREFLECTIONALPHA = false;
  33452. _this.GAMMAREFLECTION = false;
  33453. _this.REFRACTION = false;
  33454. _this.REFRACTIONMAP_3D = false;
  33455. _this.REFRACTIONMAP_OPPOSITEZ = false;
  33456. _this.LODINREFRACTIONALPHA = false;
  33457. _this.GAMMAREFRACTION = false;
  33458. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  33459. _this.INSTANCES = false;
  33460. _this.NUM_BONE_INFLUENCERS = 0;
  33461. _this.BonesPerMesh = 0;
  33462. _this.MORPHTARGETS = false;
  33463. _this.MORPHTARGETS_NORMAL = false;
  33464. _this.MORPHTARGETS_TANGENT = false;
  33465. _this.NUM_MORPH_INFLUENCERS = 0;
  33466. _this.IMAGEPROCESSING = false;
  33467. _this.VIGNETTE = false;
  33468. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  33469. _this.VIGNETTEBLENDMODEOPAQUE = false;
  33470. _this.TONEMAPPING = false;
  33471. _this.CONTRAST = false;
  33472. _this.COLORCURVES = false;
  33473. _this.COLORGRADING = false;
  33474. _this.SAMPLER3DGREENDEPTH = false;
  33475. _this.SAMPLER3DBGRMAP = false;
  33476. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  33477. _this.EXPOSURE = false;
  33478. _this.USEPHYSICALLIGHTFALLOFF = false;
  33479. _this.TWOSIDEDLIGHTING = false;
  33480. _this.SHADOWFLOAT = false;
  33481. _this.CLIPPLANE = false;
  33482. _this.POINTSIZE = false;
  33483. _this.FOG = false;
  33484. _this.LOGARITHMICDEPTH = false;
  33485. _this.FORCENORMALFORWARD = false;
  33486. _this.rebuild();
  33487. return _this;
  33488. }
  33489. PBRMaterialDefines.prototype.reset = function () {
  33490. _super.prototype.reset.call(this);
  33491. this.ALPHATESTVALUE = 0.5;
  33492. this.PBR = true;
  33493. };
  33494. return PBRMaterialDefines;
  33495. }(BABYLON.MaterialDefines));
  33496. /**
  33497. * The Physically based material base class of BJS.
  33498. *
  33499. * This offers the main features of a standard PBR material.
  33500. * For more information, please refer to the documentation :
  33501. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  33502. */
  33503. var PBRBaseMaterial = (function (_super) {
  33504. __extends(PBRBaseMaterial, _super);
  33505. /**
  33506. * Instantiates a new PBRMaterial instance.
  33507. *
  33508. * @param name The material name
  33509. * @param scene The scene the material will be use in.
  33510. */
  33511. function PBRBaseMaterial(name, scene) {
  33512. var _this = _super.call(this, name, scene) || this;
  33513. /**
  33514. * Intensity of the direct lights e.g. the four lights available in your scene.
  33515. * This impacts both the direct diffuse and specular highlights.
  33516. */
  33517. _this._directIntensity = 1.0;
  33518. /**
  33519. * Intensity of the emissive part of the material.
  33520. * This helps controlling the emissive effect without modifying the emissive color.
  33521. */
  33522. _this._emissiveIntensity = 1.0;
  33523. /**
  33524. * Intensity of the environment e.g. how much the environment will light the object
  33525. * either through harmonics for rough material or through the refelction for shiny ones.
  33526. */
  33527. _this._environmentIntensity = 1.0;
  33528. /**
  33529. * This is a special control allowing the reduction of the specular highlights coming from the
  33530. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  33531. */
  33532. _this._specularIntensity = 1.0;
  33533. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  33534. /**
  33535. * Debug Control allowing disabling the bump map on this material.
  33536. */
  33537. _this._disableBumpMap = false;
  33538. /**
  33539. * AKA Occlusion Texture Intensity in other nomenclature.
  33540. */
  33541. _this._ambientTextureStrength = 1.0;
  33542. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  33543. /**
  33544. * AKA Diffuse Color in other nomenclature.
  33545. */
  33546. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  33547. /**
  33548. * AKA Specular Color in other nomenclature.
  33549. */
  33550. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  33551. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  33552. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  33553. /**
  33554. * AKA Glossiness in other nomenclature.
  33555. */
  33556. _this._microSurface = 0.9;
  33557. /**
  33558. * source material index of refraction (IOR)' / 'destination material IOR.
  33559. */
  33560. _this._indexOfRefraction = 0.66;
  33561. /**
  33562. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  33563. */
  33564. _this._invertRefractionY = false;
  33565. /**
  33566. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  33567. * Materials half opaque for instance using refraction could benefit from this control.
  33568. */
  33569. _this._linkRefractionWithTransparency = false;
  33570. _this._useLightmapAsShadowmap = false;
  33571. /**
  33572. * Specifies that the alpha is coming form the albedo channel alpha channel.
  33573. */
  33574. _this._useAlphaFromAlbedoTexture = false;
  33575. /**
  33576. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  33577. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  33578. */
  33579. _this._useSpecularOverAlpha = true;
  33580. /**
  33581. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  33582. */
  33583. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  33584. /**
  33585. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  33586. */
  33587. _this._useRoughnessFromMetallicTextureAlpha = true;
  33588. /**
  33589. * Specifies if the metallic texture contains the roughness information in its green channel.
  33590. */
  33591. _this._useRoughnessFromMetallicTextureGreen = false;
  33592. /**
  33593. * Specifies if the metallic texture contains the metallness information in its blue channel.
  33594. */
  33595. _this._useMetallnessFromMetallicTextureBlue = false;
  33596. /**
  33597. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  33598. */
  33599. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  33600. /**
  33601. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  33602. */
  33603. _this._useAmbientInGrayScale = false;
  33604. /**
  33605. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  33606. * The material will try to infer what glossiness each pixel should be.
  33607. */
  33608. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  33609. /**
  33610. * BJS is using an harcoded light falloff based on a manually sets up range.
  33611. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  33612. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  33613. */
  33614. _this._usePhysicalLightFalloff = true;
  33615. /**
  33616. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  33617. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  33618. */
  33619. _this._useRadianceOverAlpha = true;
  33620. /**
  33621. * Allows using the bump map in parallax mode.
  33622. */
  33623. _this._useParallax = false;
  33624. /**
  33625. * Allows using the bump map in parallax occlusion mode.
  33626. */
  33627. _this._useParallaxOcclusion = false;
  33628. /**
  33629. * Controls the scale bias of the parallax mode.
  33630. */
  33631. _this._parallaxScaleBias = 0.05;
  33632. /**
  33633. * If sets to true, disables all the lights affecting the material.
  33634. */
  33635. _this._disableLighting = false;
  33636. /**
  33637. * Number of Simultaneous lights allowed on the material.
  33638. */
  33639. _this._maxSimultaneousLights = 4;
  33640. /**
  33641. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  33642. */
  33643. _this._invertNormalMapX = false;
  33644. /**
  33645. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  33646. */
  33647. _this._invertNormalMapY = false;
  33648. /**
  33649. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33650. */
  33651. _this._twoSidedLighting = false;
  33652. /**
  33653. * Defines the alpha limits in alpha test mode.
  33654. */
  33655. _this._alphaCutOff = 0.4;
  33656. /**
  33657. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  33658. */
  33659. _this._forceAlphaTest = false;
  33660. /**
  33661. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  33662. * in your scene composition.
  33663. */
  33664. _this._preMultiplyAlpha = false;
  33665. /**
  33666. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  33667. * And/Or occlude the blended part.
  33668. */
  33669. _this._useAlphaFresnel = false;
  33670. /**
  33671. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  33672. * from cos thetav and roughness:
  33673. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  33674. */
  33675. _this._environmentBRDFTexture = null;
  33676. /**
  33677. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  33678. */
  33679. _this._forceIrradianceInFragment = false;
  33680. /**
  33681. * Force normal to face away from face.
  33682. * (Temporary internal fix to remove before 3.1)
  33683. */
  33684. _this._forceNormalForward = false;
  33685. _this._renderTargets = new BABYLON.SmartArray(16);
  33686. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  33687. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  33688. _this._tempColor = new BABYLON.Color3();
  33689. // Setup the default processing configuration to the scene.
  33690. _this._attachImageProcessingConfiguration(null);
  33691. _this.getRenderTargetTextures = function () {
  33692. _this._renderTargets.reset();
  33693. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  33694. _this._renderTargets.push(_this._reflectionTexture);
  33695. }
  33696. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  33697. _this._renderTargets.push(_this._refractionTexture);
  33698. }
  33699. return _this._renderTargets;
  33700. };
  33701. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  33702. return _this;
  33703. }
  33704. /**
  33705. * Attaches a new image processing configuration to the PBR Material.
  33706. * @param configuration
  33707. */
  33708. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  33709. var _this = this;
  33710. if (configuration === this._imageProcessingConfiguration) {
  33711. return;
  33712. }
  33713. // Detaches observer.
  33714. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  33715. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  33716. }
  33717. // Pick the scene configuration if needed.
  33718. if (!configuration) {
  33719. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  33720. }
  33721. else {
  33722. this._imageProcessingConfiguration = configuration;
  33723. }
  33724. // Attaches observer.
  33725. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  33726. _this._markAllSubMeshesAsImageProcessingDirty();
  33727. });
  33728. };
  33729. PBRBaseMaterial.prototype.getClassName = function () {
  33730. return "PBRBaseMaterial";
  33731. };
  33732. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  33733. get: function () {
  33734. return this._useLogarithmicDepth;
  33735. },
  33736. set: function (value) {
  33737. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  33738. },
  33739. enumerable: true,
  33740. configurable: true
  33741. });
  33742. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  33743. if (this._linkRefractionWithTransparency) {
  33744. return false;
  33745. }
  33746. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  33747. };
  33748. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  33749. if (this._forceAlphaTest) {
  33750. return true;
  33751. }
  33752. if (this._linkRefractionWithTransparency) {
  33753. return false;
  33754. }
  33755. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  33756. };
  33757. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  33758. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  33759. };
  33760. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  33761. return this._albedoTexture;
  33762. };
  33763. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  33764. if (this.isFrozen) {
  33765. if (this._wasPreviouslyReady) {
  33766. return true;
  33767. }
  33768. }
  33769. if (!subMesh._materialDefines) {
  33770. subMesh._materialDefines = new PBRMaterialDefines();
  33771. }
  33772. var scene = this.getScene();
  33773. var defines = subMesh._materialDefines;
  33774. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  33775. if (defines._renderId === scene.getRenderId()) {
  33776. return true;
  33777. }
  33778. }
  33779. var engine = scene.getEngine();
  33780. // Lights
  33781. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  33782. defines._needNormals = true;
  33783. // Textures
  33784. if (defines._areTexturesDirty) {
  33785. defines._needUVs = false;
  33786. if (scene.texturesEnabled) {
  33787. if (scene.getEngine().getCaps().textureLOD) {
  33788. defines.LODBASEDMICROSFURACE = true;
  33789. }
  33790. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  33791. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  33792. return false;
  33793. }
  33794. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  33795. }
  33796. else {
  33797. defines.ALBEDO = false;
  33798. }
  33799. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  33800. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  33801. return false;
  33802. }
  33803. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  33804. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  33805. }
  33806. else {
  33807. defines.AMBIENT = false;
  33808. }
  33809. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  33810. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  33811. return false;
  33812. }
  33813. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  33814. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  33815. }
  33816. else {
  33817. defines.OPACITY = false;
  33818. }
  33819. var reflectionTexture = this._getReflectionTexture();
  33820. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  33821. if (!reflectionTexture.isReadyOrNotBlocking()) {
  33822. return false;
  33823. }
  33824. defines.REFLECTION = true;
  33825. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  33826. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  33827. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  33828. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  33829. defines.INVERTCUBICMAP = true;
  33830. }
  33831. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  33832. switch (reflectionTexture.coordinatesMode) {
  33833. case BABYLON.Texture.CUBIC_MODE:
  33834. case BABYLON.Texture.INVCUBIC_MODE:
  33835. defines.REFLECTIONMAP_CUBIC = true;
  33836. break;
  33837. case BABYLON.Texture.EXPLICIT_MODE:
  33838. defines.REFLECTIONMAP_EXPLICIT = true;
  33839. break;
  33840. case BABYLON.Texture.PLANAR_MODE:
  33841. defines.REFLECTIONMAP_PLANAR = true;
  33842. break;
  33843. case BABYLON.Texture.PROJECTION_MODE:
  33844. defines.REFLECTIONMAP_PROJECTION = true;
  33845. break;
  33846. case BABYLON.Texture.SKYBOX_MODE:
  33847. defines.REFLECTIONMAP_SKYBOX = true;
  33848. break;
  33849. case BABYLON.Texture.SPHERICAL_MODE:
  33850. defines.REFLECTIONMAP_SPHERICAL = true;
  33851. break;
  33852. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  33853. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  33854. break;
  33855. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  33856. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  33857. break;
  33858. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  33859. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  33860. break;
  33861. }
  33862. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  33863. if (reflectionTexture.sphericalPolynomial) {
  33864. defines.USESPHERICALFROMREFLECTIONMAP = true;
  33865. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  33866. defines.USESPHERICALINFRAGMENT = true;
  33867. }
  33868. }
  33869. }
  33870. }
  33871. else {
  33872. defines.REFLECTION = false;
  33873. defines.REFLECTIONMAP_3D = false;
  33874. defines.REFLECTIONMAP_SPHERICAL = false;
  33875. defines.REFLECTIONMAP_PLANAR = false;
  33876. defines.REFLECTIONMAP_CUBIC = false;
  33877. defines.REFLECTIONMAP_PROJECTION = false;
  33878. defines.REFLECTIONMAP_SKYBOX = false;
  33879. defines.REFLECTIONMAP_EXPLICIT = false;
  33880. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  33881. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  33882. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  33883. defines.INVERTCUBICMAP = false;
  33884. defines.USESPHERICALFROMREFLECTIONMAP = false;
  33885. defines.USESPHERICALINFRAGMENT = false;
  33886. defines.REFLECTIONMAP_OPPOSITEZ = false;
  33887. defines.LODINREFLECTIONALPHA = false;
  33888. defines.GAMMAREFLECTION = false;
  33889. }
  33890. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  33891. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  33892. return false;
  33893. }
  33894. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  33895. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  33896. }
  33897. else {
  33898. defines.LIGHTMAP = false;
  33899. }
  33900. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  33901. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  33902. return false;
  33903. }
  33904. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  33905. }
  33906. else {
  33907. defines.EMISSIVE = false;
  33908. }
  33909. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  33910. if (this._metallicTexture) {
  33911. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  33912. return false;
  33913. }
  33914. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  33915. defines.METALLICWORKFLOW = true;
  33916. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  33917. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  33918. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  33919. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  33920. }
  33921. else if (this._reflectivityTexture) {
  33922. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  33923. return false;
  33924. }
  33925. defines.METALLICWORKFLOW = false;
  33926. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  33927. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  33928. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  33929. }
  33930. else {
  33931. defines.METALLICWORKFLOW = false;
  33932. defines.REFLECTIVITY = false;
  33933. }
  33934. if (this._microSurfaceTexture) {
  33935. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  33936. return false;
  33937. }
  33938. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  33939. }
  33940. else {
  33941. defines.MICROSURFACEMAP = false;
  33942. }
  33943. }
  33944. else {
  33945. defines.REFLECTIVITY = false;
  33946. defines.MICROSURFACEMAP = false;
  33947. }
  33948. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  33949. // Bump texure can not be none blocking.
  33950. if (!this._bumpTexture.isReady()) {
  33951. return false;
  33952. }
  33953. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  33954. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  33955. defines.PARALLAX = true;
  33956. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  33957. }
  33958. else {
  33959. defines.PARALLAX = false;
  33960. }
  33961. }
  33962. else {
  33963. defines.BUMP = false;
  33964. }
  33965. var refractionTexture = this._getRefractionTexture();
  33966. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  33967. if (!refractionTexture.isReadyOrNotBlocking()) {
  33968. return false;
  33969. }
  33970. defines.REFRACTION = true;
  33971. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  33972. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  33973. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  33974. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  33975. if (this._linkRefractionWithTransparency) {
  33976. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  33977. }
  33978. }
  33979. else {
  33980. defines.REFRACTION = false;
  33981. }
  33982. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  33983. // This is blocking.
  33984. if (!this._environmentBRDFTexture.isReady()) {
  33985. return false;
  33986. }
  33987. defines.ENVIRONMENTBRDF = true;
  33988. }
  33989. if (this._shouldUseAlphaFromAlbedoTexture()) {
  33990. defines.ALPHAFROMALBEDO = true;
  33991. }
  33992. }
  33993. if (this._useSpecularOverAlpha) {
  33994. defines.SPECULAROVERALPHA = true;
  33995. }
  33996. if (this._usePhysicalLightFalloff) {
  33997. defines.USEPHYSICALLIGHTFALLOFF = true;
  33998. }
  33999. if (this._useRadianceOverAlpha) {
  34000. defines.RADIANCEOVERALPHA = true;
  34001. }
  34002. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  34003. defines.METALLICWORKFLOW = true;
  34004. }
  34005. if (!this.backFaceCulling && this._twoSidedLighting) {
  34006. defines.TWOSIDEDLIGHTING = true;
  34007. }
  34008. defines.ALPHATESTVALUE = this._alphaCutOff;
  34009. defines.PREMULTIPLYALPHA = this._preMultiplyAlpha;
  34010. defines.ALPHABLEND = this.needAlphaBlending();
  34011. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  34012. }
  34013. if (defines._areImageProcessingDirty) {
  34014. if (!this._imageProcessingConfiguration.isReady()) {
  34015. return false;
  34016. }
  34017. this._imageProcessingConfiguration.prepareDefines(defines);
  34018. }
  34019. defines.FORCENORMALFORWARD = this._forceNormalForward;
  34020. // Misc.
  34021. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  34022. // Values that need to be evaluated on every frame
  34023. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  34024. // Attribs
  34025. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  34026. if (mesh) {
  34027. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34028. mesh.createNormals(true);
  34029. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  34030. }
  34031. }
  34032. }
  34033. // Get correct effect
  34034. if (defines.isDirty) {
  34035. defines.markAsProcessed();
  34036. scene.resetCachedMaterial();
  34037. // Fallbacks
  34038. var fallbacks = new BABYLON.EffectFallbacks();
  34039. if (defines.ENVIRONMENTBRDF) {
  34040. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  34041. }
  34042. if (defines.REFLECTION) {
  34043. fallbacks.addFallback(0, "REFLECTION");
  34044. }
  34045. if (defines.REFRACTION) {
  34046. fallbacks.addFallback(0, "REFRACTION");
  34047. }
  34048. if (defines.REFLECTIVITY) {
  34049. fallbacks.addFallback(0, "REFLECTIVITY");
  34050. }
  34051. if (defines.BUMP) {
  34052. fallbacks.addFallback(0, "BUMP");
  34053. }
  34054. if (defines.PARALLAX) {
  34055. fallbacks.addFallback(1, "PARALLAX");
  34056. }
  34057. if (defines.PARALLAXOCCLUSION) {
  34058. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  34059. }
  34060. if (defines.SPECULAROVERALPHA) {
  34061. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  34062. }
  34063. if (defines.FOG) {
  34064. fallbacks.addFallback(1, "FOG");
  34065. }
  34066. if (defines.POINTSIZE) {
  34067. fallbacks.addFallback(0, "POINTSIZE");
  34068. }
  34069. if (defines.LOGARITHMICDEPTH) {
  34070. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  34071. }
  34072. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  34073. if (defines.SPECULARTERM) {
  34074. fallbacks.addFallback(0, "SPECULARTERM");
  34075. }
  34076. if (defines.NUM_BONE_INFLUENCERS > 0) {
  34077. fallbacks.addCPUSkinningFallback(0, mesh);
  34078. }
  34079. //Attributes
  34080. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34081. if (defines.NORMAL) {
  34082. attribs.push(BABYLON.VertexBuffer.NormalKind);
  34083. }
  34084. if (defines.TANGENT) {
  34085. attribs.push(BABYLON.VertexBuffer.TangentKind);
  34086. }
  34087. if (defines.UV1) {
  34088. attribs.push(BABYLON.VertexBuffer.UVKind);
  34089. }
  34090. if (defines.UV2) {
  34091. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34092. }
  34093. if (defines.VERTEXCOLOR) {
  34094. attribs.push(BABYLON.VertexBuffer.ColorKind);
  34095. }
  34096. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  34097. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  34098. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  34099. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  34100. "vFogInfos", "vFogColor", "pointSize",
  34101. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  34102. "mBones",
  34103. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  34104. "vLightingIntensity",
  34105. "logarithmicDepthConstant",
  34106. "vSphericalX", "vSphericalY", "vSphericalZ",
  34107. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  34108. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  34109. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  34110. "vTangentSpaceParams"
  34111. ];
  34112. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  34113. "bumpSampler", "lightmapSampler", "opacitySampler",
  34114. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  34115. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  34116. "microSurfaceSampler", "environmentBrdfSampler"];
  34117. var uniformBuffers = ["Material", "Scene"];
  34118. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  34119. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  34120. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  34121. uniformsNames: uniforms,
  34122. uniformBuffersNames: uniformBuffers,
  34123. samplers: samplers,
  34124. defines: defines,
  34125. maxSimultaneousLights: this._maxSimultaneousLights
  34126. });
  34127. var onCompiled = function (effect) {
  34128. if (this.onCompiled) {
  34129. this.onCompiled(effect);
  34130. }
  34131. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  34132. }.bind(this);
  34133. var join = defines.toString();
  34134. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  34135. attributes: attribs,
  34136. uniformsNames: uniforms,
  34137. uniformBuffersNames: uniformBuffers,
  34138. samplers: samplers,
  34139. defines: join,
  34140. fallbacks: fallbacks,
  34141. onCompiled: onCompiled,
  34142. onError: this.onError,
  34143. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  34144. }, engine), defines);
  34145. this.buildUniformLayout();
  34146. }
  34147. if (!subMesh.effect.isReady()) {
  34148. return false;
  34149. }
  34150. defines._renderId = scene.getRenderId();
  34151. this._wasPreviouslyReady = true;
  34152. return true;
  34153. };
  34154. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  34155. // Order is important !
  34156. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  34157. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  34158. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  34159. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  34160. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  34161. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  34162. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  34163. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  34164. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  34165. this._uniformBuffer.addUniform("vBumpInfos", 3);
  34166. this._uniformBuffer.addUniform("albedoMatrix", 16);
  34167. this._uniformBuffer.addUniform("ambientMatrix", 16);
  34168. this._uniformBuffer.addUniform("opacityMatrix", 16);
  34169. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  34170. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  34171. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  34172. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  34173. this._uniformBuffer.addUniform("bumpMatrix", 16);
  34174. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  34175. this._uniformBuffer.addUniform("refractionMatrix", 16);
  34176. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  34177. this._uniformBuffer.addUniform("vReflectionColor", 3);
  34178. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  34179. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  34180. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  34181. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  34182. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  34183. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  34184. this._uniformBuffer.addUniform("pointSize", 1);
  34185. this._uniformBuffer.create();
  34186. };
  34187. PBRBaseMaterial.prototype.unbind = function () {
  34188. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  34189. this._uniformBuffer.setTexture("reflectionSampler", null);
  34190. }
  34191. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  34192. this._uniformBuffer.setTexture("refractionSampler", null);
  34193. }
  34194. _super.prototype.unbind.call(this);
  34195. };
  34196. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34197. this._activeEffect.setMatrix("world", world);
  34198. };
  34199. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34200. var scene = this.getScene();
  34201. var defines = subMesh._materialDefines;
  34202. if (!defines) {
  34203. return;
  34204. }
  34205. var effect = subMesh.effect;
  34206. this._activeEffect = effect;
  34207. // Matrices
  34208. this.bindOnlyWorldMatrix(world);
  34209. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  34210. // Bones
  34211. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  34212. if (mustRebind) {
  34213. this._uniformBuffer.bindToEffect(effect, "Material");
  34214. this.bindViewProjection(effect);
  34215. var reflectionTexture = this._getReflectionTexture();
  34216. var refractionTexture = this._getRefractionTexture();
  34217. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  34218. // Texture uniforms
  34219. if (scene.texturesEnabled) {
  34220. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  34221. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  34222. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  34223. }
  34224. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  34225. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  34226. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  34227. }
  34228. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  34229. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  34230. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  34231. }
  34232. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  34233. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  34234. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  34235. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  34236. var polynomials = reflectionTexture.sphericalPolynomial;
  34237. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  34238. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  34239. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  34240. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  34241. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  34242. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  34243. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  34244. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  34245. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  34246. }
  34247. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  34248. }
  34249. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  34250. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  34251. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  34252. }
  34253. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  34254. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  34255. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  34256. }
  34257. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  34258. if (this._metallicTexture) {
  34259. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  34260. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  34261. }
  34262. else if (this._reflectivityTexture) {
  34263. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  34264. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  34265. }
  34266. if (this._microSurfaceTexture) {
  34267. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  34268. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  34269. }
  34270. }
  34271. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  34272. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  34273. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  34274. if (scene._mirroredCameraPosition) {
  34275. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  34276. }
  34277. else {
  34278. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  34279. }
  34280. }
  34281. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  34282. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  34283. var depth = 1.0;
  34284. if (!refractionTexture.isCube) {
  34285. if (refractionTexture.depth) {
  34286. depth = refractionTexture.depth;
  34287. }
  34288. }
  34289. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  34290. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  34291. }
  34292. }
  34293. // Point size
  34294. if (this.pointsCloud) {
  34295. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  34296. }
  34297. // Colors
  34298. if (defines.METALLICWORKFLOW) {
  34299. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  34300. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  34301. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  34302. }
  34303. else {
  34304. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  34305. }
  34306. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  34307. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  34308. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  34309. // Misc
  34310. this._lightingInfos.x = this._directIntensity;
  34311. this._lightingInfos.y = this._emissiveIntensity;
  34312. this._lightingInfos.z = this._environmentIntensity;
  34313. this._lightingInfos.w = this._specularIntensity;
  34314. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  34315. }
  34316. // Textures
  34317. if (scene.texturesEnabled) {
  34318. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  34319. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  34320. }
  34321. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  34322. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  34323. }
  34324. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  34325. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  34326. }
  34327. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  34328. if (defines.LODBASEDMICROSFURACE) {
  34329. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  34330. }
  34331. else {
  34332. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  34333. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  34334. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  34335. }
  34336. }
  34337. if (defines.ENVIRONMENTBRDF) {
  34338. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  34339. }
  34340. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  34341. if (defines.LODBASEDMICROSFURACE) {
  34342. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  34343. }
  34344. else {
  34345. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  34346. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  34347. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  34348. }
  34349. }
  34350. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  34351. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  34352. }
  34353. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  34354. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  34355. }
  34356. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  34357. if (this._metallicTexture) {
  34358. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  34359. }
  34360. else if (this._reflectivityTexture) {
  34361. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  34362. }
  34363. if (this._microSurfaceTexture) {
  34364. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  34365. }
  34366. }
  34367. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  34368. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  34369. }
  34370. }
  34371. // Clip plane
  34372. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  34373. // Colors
  34374. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  34375. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  34376. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  34377. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  34378. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  34379. }
  34380. if (mustRebind || !this.isFrozen) {
  34381. // Lights
  34382. if (scene.lightsEnabled && !this._disableLighting) {
  34383. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  34384. }
  34385. // View
  34386. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  34387. this.bindView(effect);
  34388. }
  34389. // Fog
  34390. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  34391. // Morph targets
  34392. if (defines.NUM_MORPH_INFLUENCERS) {
  34393. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  34394. }
  34395. // image processing
  34396. this._imageProcessingConfiguration.bind(this._activeEffect);
  34397. // Log. depth
  34398. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  34399. }
  34400. this._uniformBuffer.update();
  34401. this._afterBind(mesh);
  34402. scene = null;
  34403. };
  34404. PBRBaseMaterial.prototype.getAnimatables = function () {
  34405. var results = [];
  34406. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  34407. results.push(this._albedoTexture);
  34408. }
  34409. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  34410. results.push(this._ambientTexture);
  34411. }
  34412. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  34413. results.push(this._opacityTexture);
  34414. }
  34415. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  34416. results.push(this._reflectionTexture);
  34417. }
  34418. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  34419. results.push(this._emissiveTexture);
  34420. }
  34421. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  34422. results.push(this._metallicTexture);
  34423. }
  34424. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  34425. results.push(this._reflectivityTexture);
  34426. }
  34427. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  34428. results.push(this._bumpTexture);
  34429. }
  34430. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  34431. results.push(this._lightmapTexture);
  34432. }
  34433. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  34434. results.push(this._refractionTexture);
  34435. }
  34436. return results;
  34437. };
  34438. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  34439. if (this._reflectionTexture) {
  34440. return this._reflectionTexture;
  34441. }
  34442. return this.getScene().environmentTexture;
  34443. };
  34444. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  34445. if (this._refractionTexture) {
  34446. return this._refractionTexture;
  34447. }
  34448. if (this._linkRefractionWithTransparency) {
  34449. return this.getScene().environmentTexture;
  34450. }
  34451. return null;
  34452. };
  34453. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34454. if (forceDisposeTextures) {
  34455. if (this._albedoTexture) {
  34456. this._albedoTexture.dispose();
  34457. }
  34458. if (this._ambientTexture) {
  34459. this._ambientTexture.dispose();
  34460. }
  34461. if (this._opacityTexture) {
  34462. this._opacityTexture.dispose();
  34463. }
  34464. if (this._reflectionTexture) {
  34465. this._reflectionTexture.dispose();
  34466. }
  34467. if (this._environmentBRDFTexture) {
  34468. this._environmentBRDFTexture.dispose();
  34469. }
  34470. if (this._emissiveTexture) {
  34471. this._emissiveTexture.dispose();
  34472. }
  34473. if (this._metallicTexture) {
  34474. this._metallicTexture.dispose();
  34475. }
  34476. if (this._reflectivityTexture) {
  34477. this._reflectivityTexture.dispose();
  34478. }
  34479. if (this._bumpTexture) {
  34480. this._bumpTexture.dispose();
  34481. }
  34482. if (this._lightmapTexture) {
  34483. this._lightmapTexture.dispose();
  34484. }
  34485. if (this._refractionTexture) {
  34486. this._refractionTexture.dispose();
  34487. }
  34488. }
  34489. this._renderTargets.dispose();
  34490. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34491. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34492. }
  34493. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  34494. };
  34495. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  34496. __decorate([
  34497. BABYLON.serializeAsImageProcessingConfiguration()
  34498. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  34499. __decorate([
  34500. BABYLON.serialize()
  34501. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  34502. return PBRBaseMaterial;
  34503. }(BABYLON.PushMaterial));
  34504. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  34505. })(BABYLON || (BABYLON = {}));
  34506. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  34507. var BABYLON;
  34508. (function (BABYLON) {
  34509. var Internals;
  34510. (function (Internals) {
  34511. /**
  34512. * The Physically based simple base material of BJS.
  34513. *
  34514. * This enables better naming and convention enforcements on top of the pbrMaterial.
  34515. * It is used as the base class for both the specGloss and metalRough conventions.
  34516. */
  34517. var PBRBaseSimpleMaterial = (function (_super) {
  34518. __extends(PBRBaseSimpleMaterial, _super);
  34519. /**
  34520. * Instantiates a new PBRMaterial instance.
  34521. *
  34522. * @param name The material name
  34523. * @param scene The scene the material will be use in.
  34524. */
  34525. function PBRBaseSimpleMaterial(name, scene) {
  34526. var _this = _super.call(this, name, scene) || this;
  34527. /**
  34528. * Number of Simultaneous lights allowed on the material.
  34529. */
  34530. _this.maxSimultaneousLights = 4;
  34531. /**
  34532. * If sets to true, disables all the lights affecting the material.
  34533. */
  34534. _this.disableLighting = false;
  34535. /**
  34536. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34537. */
  34538. _this.invertNormalMapX = false;
  34539. /**
  34540. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34541. */
  34542. _this.invertNormalMapY = false;
  34543. /**
  34544. * Emissivie color used to self-illuminate the model.
  34545. */
  34546. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  34547. /**
  34548. * Occlusion Channel Strenght.
  34549. */
  34550. _this.occlusionStrength = 1.0;
  34551. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  34552. _this._useAmbientInGrayScale = true;
  34553. return _this;
  34554. }
  34555. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  34556. /**
  34557. * Gets the current transparency mode.
  34558. */
  34559. get: function () {
  34560. return this._transparencyMode;
  34561. },
  34562. /**
  34563. * Sets the transparency mode of the material.
  34564. */
  34565. set: function (value) {
  34566. if (this._transparencyMode === value) {
  34567. return;
  34568. }
  34569. this._transparencyMode = value;
  34570. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  34571. this._forceAlphaTest = true;
  34572. }
  34573. else {
  34574. this._forceAlphaTest = false;
  34575. }
  34576. this._markAllSubMeshesAsTexturesDirty();
  34577. },
  34578. enumerable: true,
  34579. configurable: true
  34580. });
  34581. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  34582. /**
  34583. * Gets the current double sided mode.
  34584. */
  34585. get: function () {
  34586. return this._twoSidedLighting;
  34587. },
  34588. /**
  34589. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34590. */
  34591. set: function (value) {
  34592. if (this._twoSidedLighting === value) {
  34593. return;
  34594. }
  34595. this._twoSidedLighting = value;
  34596. this.backFaceCulling = !value;
  34597. this._markAllSubMeshesAsTexturesDirty();
  34598. },
  34599. enumerable: true,
  34600. configurable: true
  34601. });
  34602. /**
  34603. * Specifies wether or not the alpha value of the albedo texture should be used.
  34604. */
  34605. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  34606. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  34607. };
  34608. /**
  34609. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  34610. */
  34611. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  34612. if (this._linkRefractionWithTransparency) {
  34613. return false;
  34614. }
  34615. return (this.alpha < 1.0) ||
  34616. (this._shouldUseAlphaFromAlbedoTexture() &&
  34617. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  34618. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  34619. };
  34620. /**
  34621. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  34622. */
  34623. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  34624. if (this._linkRefractionWithTransparency) {
  34625. return false;
  34626. }
  34627. return this._shouldUseAlphaFromAlbedoTexture() &&
  34628. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  34629. };
  34630. /**
  34631. * Return the active textures of the material.
  34632. */
  34633. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  34634. var activeTextures = _super.prototype.getActiveTextures.call(this);
  34635. if (this.environmentTexture) {
  34636. activeTextures.push(this.environmentTexture);
  34637. }
  34638. if (this.normalTexture) {
  34639. activeTextures.push(this.normalTexture);
  34640. }
  34641. if (this.emissiveTexture) {
  34642. activeTextures.push(this.emissiveTexture);
  34643. }
  34644. if (this.occlusionTexture) {
  34645. activeTextures.push(this.occlusionTexture);
  34646. }
  34647. return activeTextures;
  34648. };
  34649. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  34650. return "PBRBaseSimpleMaterial";
  34651. };
  34652. __decorate([
  34653. BABYLON.serialize(),
  34654. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34655. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  34656. __decorate([
  34657. BABYLON.serialize(),
  34658. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34659. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  34660. __decorate([
  34661. BABYLON.serializeAsTexture(),
  34662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  34663. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  34664. __decorate([
  34665. BABYLON.serialize(),
  34666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34667. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  34668. __decorate([
  34669. BABYLON.serialize(),
  34670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34671. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  34672. __decorate([
  34673. BABYLON.serializeAsTexture(),
  34674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  34675. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  34676. __decorate([
  34677. BABYLON.serializeAsColor3("emissive"),
  34678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34679. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  34680. __decorate([
  34681. BABYLON.serializeAsTexture(),
  34682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34683. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  34684. __decorate([
  34685. BABYLON.serialize(),
  34686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  34687. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  34688. __decorate([
  34689. BABYLON.serializeAsTexture(),
  34690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  34691. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  34692. __decorate([
  34693. BABYLON.serialize(),
  34694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  34695. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  34696. __decorate([
  34697. BABYLON.serialize()
  34698. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  34699. __decorate([
  34700. BABYLON.serialize()
  34701. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  34702. return PBRBaseSimpleMaterial;
  34703. }(BABYLON.PBRBaseMaterial));
  34704. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  34705. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34706. })(BABYLON || (BABYLON = {}));
  34707. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  34708. var BABYLON;
  34709. (function (BABYLON) {
  34710. /**
  34711. * The Physically based material of BJS.
  34712. *
  34713. * This offers the main features of a standard PBR material.
  34714. * For more information, please refer to the documentation :
  34715. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  34716. */
  34717. var PBRMaterial = (function (_super) {
  34718. __extends(PBRMaterial, _super);
  34719. /**
  34720. * Instantiates a new PBRMaterial instance.
  34721. *
  34722. * @param name The material name
  34723. * @param scene The scene the material will be use in.
  34724. */
  34725. function PBRMaterial(name, scene) {
  34726. var _this = _super.call(this, name, scene) || this;
  34727. /**
  34728. * Intensity of the direct lights e.g. the four lights available in your scene.
  34729. * This impacts both the direct diffuse and specular highlights.
  34730. */
  34731. _this.directIntensity = 1.0;
  34732. /**
  34733. * Intensity of the emissive part of the material.
  34734. * This helps controlling the emissive effect without modifying the emissive color.
  34735. */
  34736. _this.emissiveIntensity = 1.0;
  34737. /**
  34738. * Intensity of the environment e.g. how much the environment will light the object
  34739. * either through harmonics for rough material or through the refelction for shiny ones.
  34740. */
  34741. _this.environmentIntensity = 1.0;
  34742. /**
  34743. * This is a special control allowing the reduction of the specular highlights coming from the
  34744. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  34745. */
  34746. _this.specularIntensity = 1.0;
  34747. /**
  34748. * Debug Control allowing disabling the bump map on this material.
  34749. */
  34750. _this.disableBumpMap = false;
  34751. /**
  34752. * AKA Occlusion Texture Intensity in other nomenclature.
  34753. */
  34754. _this.ambientTextureStrength = 1.0;
  34755. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  34756. /**
  34757. * AKA Diffuse Color in other nomenclature.
  34758. */
  34759. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  34760. /**
  34761. * AKA Specular Color in other nomenclature.
  34762. */
  34763. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  34764. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  34765. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  34766. /**
  34767. * AKA Glossiness in other nomenclature.
  34768. */
  34769. _this.microSurface = 1.0;
  34770. /**
  34771. * source material index of refraction (IOR)' / 'destination material IOR.
  34772. */
  34773. _this.indexOfRefraction = 0.66;
  34774. /**
  34775. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  34776. */
  34777. _this.invertRefractionY = false;
  34778. /**
  34779. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  34780. * Materials half opaque for instance using refraction could benefit from this control.
  34781. */
  34782. _this.linkRefractionWithTransparency = false;
  34783. _this.useLightmapAsShadowmap = false;
  34784. /**
  34785. * Specifies that the alpha is coming form the albedo channel alpha channel.
  34786. */
  34787. _this.useAlphaFromAlbedoTexture = false;
  34788. /**
  34789. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  34790. */
  34791. _this.forceAlphaTest = false;
  34792. /**
  34793. * Defines the alpha limits in alpha test mode.
  34794. */
  34795. _this.alphaCutOff = 0.4;
  34796. /**
  34797. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  34798. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  34799. */
  34800. _this.useSpecularOverAlpha = true;
  34801. /**
  34802. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  34803. */
  34804. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  34805. /**
  34806. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  34807. */
  34808. _this.useRoughnessFromMetallicTextureAlpha = true;
  34809. /**
  34810. * Specifies if the metallic texture contains the roughness information in its green channel.
  34811. */
  34812. _this.useRoughnessFromMetallicTextureGreen = false;
  34813. /**
  34814. * Specifies if the metallic texture contains the metallness information in its blue channel.
  34815. */
  34816. _this.useMetallnessFromMetallicTextureBlue = false;
  34817. /**
  34818. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  34819. */
  34820. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  34821. /**
  34822. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  34823. */
  34824. _this.useAmbientInGrayScale = false;
  34825. /**
  34826. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  34827. * The material will try to infer what glossiness each pixel should be.
  34828. */
  34829. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  34830. /**
  34831. * BJS is using an harcoded light falloff based on a manually sets up range.
  34832. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  34833. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  34834. */
  34835. _this.usePhysicalLightFalloff = true;
  34836. /**
  34837. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  34838. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  34839. */
  34840. _this.useRadianceOverAlpha = true;
  34841. /**
  34842. * Allows using the bump map in parallax mode.
  34843. */
  34844. _this.useParallax = false;
  34845. /**
  34846. * Allows using the bump map in parallax occlusion mode.
  34847. */
  34848. _this.useParallaxOcclusion = false;
  34849. /**
  34850. * Controls the scale bias of the parallax mode.
  34851. */
  34852. _this.parallaxScaleBias = 0.05;
  34853. /**
  34854. * If sets to true, disables all the lights affecting the material.
  34855. */
  34856. _this.disableLighting = false;
  34857. /**
  34858. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  34859. */
  34860. _this.forceIrradianceInFragment = false;
  34861. /**
  34862. * Number of Simultaneous lights allowed on the material.
  34863. */
  34864. _this.maxSimultaneousLights = 4;
  34865. /**
  34866. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34867. */
  34868. _this.invertNormalMapX = false;
  34869. /**
  34870. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34871. */
  34872. _this.invertNormalMapY = false;
  34873. /**
  34874. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34875. */
  34876. _this.twoSidedLighting = false;
  34877. /**
  34878. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  34879. * in your scene composition.
  34880. */
  34881. _this.preMultiplyAlpha = false;
  34882. /**
  34883. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  34884. * And/Or occlude the blended part.
  34885. */
  34886. _this.useAlphaFresnel = false;
  34887. /**
  34888. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  34889. * And/Or occlude the blended part.
  34890. */
  34891. _this.environmentBRDFTexture = null;
  34892. /**
  34893. * Force normal to face away from face.
  34894. * (Temporary internal fix to remove before 3.1)
  34895. */
  34896. _this.forceNormalForward = false;
  34897. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  34898. return _this;
  34899. }
  34900. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  34901. /**
  34902. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  34903. */
  34904. get: function () {
  34905. return this._PBRMATERIAL_OPAQUE;
  34906. },
  34907. enumerable: true,
  34908. configurable: true
  34909. });
  34910. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  34911. /**
  34912. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  34913. */
  34914. get: function () {
  34915. return this._PBRMATERIAL_ALPHATEST;
  34916. },
  34917. enumerable: true,
  34918. configurable: true
  34919. });
  34920. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  34921. /**
  34922. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  34923. */
  34924. get: function () {
  34925. return this._PBRMATERIAL_ALPHABLEND;
  34926. },
  34927. enumerable: true,
  34928. configurable: true
  34929. });
  34930. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  34931. /**
  34932. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  34933. * They are also discarded below the alpha cutoff threshold to improve performances.
  34934. */
  34935. get: function () {
  34936. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  34937. },
  34938. enumerable: true,
  34939. configurable: true
  34940. });
  34941. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  34942. /**
  34943. * Gets the image processing configuration used either in this material.
  34944. */
  34945. get: function () {
  34946. return this._imageProcessingConfiguration;
  34947. },
  34948. /**
  34949. * Sets the Default image processing configuration used either in the this material.
  34950. *
  34951. * If sets to null, the scene one is in use.
  34952. */
  34953. set: function (value) {
  34954. this._attachImageProcessingConfiguration(value);
  34955. // Ensure the effect will be rebuilt.
  34956. this._markAllSubMeshesAsTexturesDirty();
  34957. },
  34958. enumerable: true,
  34959. configurable: true
  34960. });
  34961. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  34962. /**
  34963. * Gets wether the color curves effect is enabled.
  34964. */
  34965. get: function () {
  34966. return this.imageProcessingConfiguration.colorCurvesEnabled;
  34967. },
  34968. /**
  34969. * Sets wether the color curves effect is enabled.
  34970. */
  34971. set: function (value) {
  34972. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  34973. },
  34974. enumerable: true,
  34975. configurable: true
  34976. });
  34977. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  34978. /**
  34979. * Gets wether the color grading effect is enabled.
  34980. */
  34981. get: function () {
  34982. return this.imageProcessingConfiguration.colorGradingEnabled;
  34983. },
  34984. /**
  34985. * Gets wether the color grading effect is enabled.
  34986. */
  34987. set: function (value) {
  34988. this.imageProcessingConfiguration.colorGradingEnabled = value;
  34989. },
  34990. enumerable: true,
  34991. configurable: true
  34992. });
  34993. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  34994. /**
  34995. * Gets wether tonemapping is enabled or not.
  34996. */
  34997. get: function () {
  34998. return this._imageProcessingConfiguration.toneMappingEnabled;
  34999. },
  35000. /**
  35001. * Sets wether tonemapping is enabled or not
  35002. */
  35003. set: function (value) {
  35004. this._imageProcessingConfiguration.toneMappingEnabled = value;
  35005. },
  35006. enumerable: true,
  35007. configurable: true
  35008. });
  35009. ;
  35010. ;
  35011. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  35012. /**
  35013. * The camera exposure used on this material.
  35014. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35015. * This corresponds to a photographic exposure.
  35016. */
  35017. get: function () {
  35018. return this._imageProcessingConfiguration.exposure;
  35019. },
  35020. /**
  35021. * The camera exposure used on this material.
  35022. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35023. * This corresponds to a photographic exposure.
  35024. */
  35025. set: function (value) {
  35026. this._imageProcessingConfiguration.exposure = value;
  35027. },
  35028. enumerable: true,
  35029. configurable: true
  35030. });
  35031. ;
  35032. ;
  35033. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  35034. /**
  35035. * Gets The camera contrast used on this material.
  35036. */
  35037. get: function () {
  35038. return this._imageProcessingConfiguration.contrast;
  35039. },
  35040. /**
  35041. * Sets The camera contrast used on this material.
  35042. */
  35043. set: function (value) {
  35044. this._imageProcessingConfiguration.contrast = value;
  35045. },
  35046. enumerable: true,
  35047. configurable: true
  35048. });
  35049. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  35050. /**
  35051. * Gets the Color Grading 2D Lookup Texture.
  35052. */
  35053. get: function () {
  35054. return this._imageProcessingConfiguration.colorGradingTexture;
  35055. },
  35056. /**
  35057. * Sets the Color Grading 2D Lookup Texture.
  35058. */
  35059. set: function (value) {
  35060. this._imageProcessingConfiguration.colorGradingTexture = value;
  35061. },
  35062. enumerable: true,
  35063. configurable: true
  35064. });
  35065. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  35066. /**
  35067. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35068. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35069. * 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;
  35070. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35071. */
  35072. get: function () {
  35073. return this._imageProcessingConfiguration.colorCurves;
  35074. },
  35075. /**
  35076. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35077. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35078. * 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;
  35079. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35080. */
  35081. set: function (value) {
  35082. this._imageProcessingConfiguration.colorCurves = value;
  35083. },
  35084. enumerable: true,
  35085. configurable: true
  35086. });
  35087. PBRMaterial.prototype.getClassName = function () {
  35088. return "PBRMaterial";
  35089. };
  35090. PBRMaterial.prototype.getActiveTextures = function () {
  35091. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35092. if (this._albedoTexture) {
  35093. activeTextures.push(this._albedoTexture);
  35094. }
  35095. if (this._ambientTexture) {
  35096. activeTextures.push(this._ambientTexture);
  35097. }
  35098. if (this._opacityTexture) {
  35099. activeTextures.push(this._opacityTexture);
  35100. }
  35101. if (this._reflectionTexture) {
  35102. activeTextures.push(this._reflectionTexture);
  35103. }
  35104. if (this._emissiveTexture) {
  35105. activeTextures.push(this._emissiveTexture);
  35106. }
  35107. if (this._reflectivityTexture) {
  35108. activeTextures.push(this._reflectivityTexture);
  35109. }
  35110. if (this._metallicTexture) {
  35111. activeTextures.push(this._metallicTexture);
  35112. }
  35113. if (this._microSurfaceTexture) {
  35114. activeTextures.push(this._microSurfaceTexture);
  35115. }
  35116. if (this._bumpTexture) {
  35117. activeTextures.push(this._bumpTexture);
  35118. }
  35119. if (this._lightmapTexture) {
  35120. activeTextures.push(this._lightmapTexture);
  35121. }
  35122. if (this._refractionTexture) {
  35123. activeTextures.push(this._refractionTexture);
  35124. }
  35125. return activeTextures;
  35126. };
  35127. PBRMaterial.prototype.hasTexture = function (texture) {
  35128. if (_super.prototype.hasTexture.call(this, texture)) {
  35129. return true;
  35130. }
  35131. if (this._albedoTexture === texture) {
  35132. return true;
  35133. }
  35134. if (this._ambientTexture === texture) {
  35135. return true;
  35136. }
  35137. if (this._opacityTexture === texture) {
  35138. return true;
  35139. }
  35140. if (this._reflectionTexture === texture) {
  35141. return true;
  35142. }
  35143. if (this._reflectivityTexture === texture) {
  35144. return true;
  35145. }
  35146. if (this._metallicTexture === texture) {
  35147. return true;
  35148. }
  35149. if (this._microSurfaceTexture === texture) {
  35150. return true;
  35151. }
  35152. if (this._bumpTexture === texture) {
  35153. return true;
  35154. }
  35155. if (this._lightmapTexture === texture) {
  35156. return true;
  35157. }
  35158. if (this._refractionTexture === texture) {
  35159. return true;
  35160. }
  35161. return false;
  35162. };
  35163. PBRMaterial.prototype.clone = function (name) {
  35164. var _this = this;
  35165. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  35166. clone.id = name;
  35167. clone.name = name;
  35168. return clone;
  35169. };
  35170. PBRMaterial.prototype.serialize = function () {
  35171. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  35172. serializationObject.customType = "BABYLON.PBRMaterial";
  35173. return serializationObject;
  35174. };
  35175. // Statics
  35176. PBRMaterial.Parse = function (source, scene, rootUrl) {
  35177. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  35178. };
  35179. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  35180. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  35181. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  35182. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  35183. __decorate([
  35184. BABYLON.serialize(),
  35185. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35186. ], PBRMaterial.prototype, "directIntensity", void 0);
  35187. __decorate([
  35188. BABYLON.serialize(),
  35189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35190. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  35191. __decorate([
  35192. BABYLON.serialize(),
  35193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35194. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  35195. __decorate([
  35196. BABYLON.serialize(),
  35197. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35198. ], PBRMaterial.prototype, "specularIntensity", void 0);
  35199. __decorate([
  35200. BABYLON.serialize(),
  35201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35202. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  35203. __decorate([
  35204. BABYLON.serializeAsTexture(),
  35205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35206. ], PBRMaterial.prototype, "albedoTexture", void 0);
  35207. __decorate([
  35208. BABYLON.serializeAsTexture(),
  35209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35210. ], PBRMaterial.prototype, "ambientTexture", void 0);
  35211. __decorate([
  35212. BABYLON.serialize(),
  35213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35214. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  35215. __decorate([
  35216. BABYLON.serializeAsTexture(),
  35217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35218. ], PBRMaterial.prototype, "opacityTexture", void 0);
  35219. __decorate([
  35220. BABYLON.serializeAsTexture(),
  35221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35222. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  35223. __decorate([
  35224. BABYLON.serializeAsTexture(),
  35225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35226. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  35227. __decorate([
  35228. BABYLON.serializeAsTexture(),
  35229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35230. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  35231. __decorate([
  35232. BABYLON.serializeAsTexture(),
  35233. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35234. ], PBRMaterial.prototype, "metallicTexture", void 0);
  35235. __decorate([
  35236. BABYLON.serialize(),
  35237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35238. ], PBRMaterial.prototype, "metallic", void 0);
  35239. __decorate([
  35240. BABYLON.serialize(),
  35241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35242. ], PBRMaterial.prototype, "roughness", void 0);
  35243. __decorate([
  35244. BABYLON.serializeAsTexture(),
  35245. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35246. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  35247. __decorate([
  35248. BABYLON.serializeAsTexture(),
  35249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35250. ], PBRMaterial.prototype, "bumpTexture", void 0);
  35251. __decorate([
  35252. BABYLON.serializeAsTexture(),
  35253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  35254. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  35255. __decorate([
  35256. BABYLON.serializeAsTexture(),
  35257. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35258. ], PBRMaterial.prototype, "refractionTexture", void 0);
  35259. __decorate([
  35260. BABYLON.serializeAsColor3("ambient"),
  35261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35262. ], PBRMaterial.prototype, "ambientColor", void 0);
  35263. __decorate([
  35264. BABYLON.serializeAsColor3("albedo"),
  35265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35266. ], PBRMaterial.prototype, "albedoColor", void 0);
  35267. __decorate([
  35268. BABYLON.serializeAsColor3("reflectivity"),
  35269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35270. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  35271. __decorate([
  35272. BABYLON.serializeAsColor3("reflection"),
  35273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35274. ], PBRMaterial.prototype, "reflectionColor", void 0);
  35275. __decorate([
  35276. BABYLON.serializeAsColor3("emissive"),
  35277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35278. ], PBRMaterial.prototype, "emissiveColor", void 0);
  35279. __decorate([
  35280. BABYLON.serialize(),
  35281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35282. ], PBRMaterial.prototype, "microSurface", void 0);
  35283. __decorate([
  35284. BABYLON.serialize(),
  35285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35286. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  35287. __decorate([
  35288. BABYLON.serialize(),
  35289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35290. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  35291. __decorate([
  35292. BABYLON.serialize(),
  35293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35294. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  35295. __decorate([
  35296. BABYLON.serialize(),
  35297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35298. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  35299. __decorate([
  35300. BABYLON.serialize(),
  35301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35302. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  35303. __decorate([
  35304. BABYLON.serialize(),
  35305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35306. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  35307. __decorate([
  35308. BABYLON.serialize(),
  35309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35310. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  35311. __decorate([
  35312. BABYLON.serialize(),
  35313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35314. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  35315. __decorate([
  35316. BABYLON.serialize(),
  35317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35318. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  35319. __decorate([
  35320. BABYLON.serialize(),
  35321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35322. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  35323. __decorate([
  35324. BABYLON.serialize(),
  35325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35326. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  35327. __decorate([
  35328. BABYLON.serialize(),
  35329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35330. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  35331. __decorate([
  35332. BABYLON.serialize(),
  35333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35334. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  35335. __decorate([
  35336. BABYLON.serialize(),
  35337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35338. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  35339. __decorate([
  35340. BABYLON.serialize(),
  35341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35342. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  35343. __decorate([
  35344. BABYLON.serialize(),
  35345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35346. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  35347. __decorate([
  35348. BABYLON.serialize(),
  35349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35350. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  35351. __decorate([
  35352. BABYLON.serialize(),
  35353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35354. ], PBRMaterial.prototype, "useParallax", void 0);
  35355. __decorate([
  35356. BABYLON.serialize(),
  35357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35358. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  35359. __decorate([
  35360. BABYLON.serialize(),
  35361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35362. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  35363. __decorate([
  35364. BABYLON.serialize(),
  35365. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35366. ], PBRMaterial.prototype, "disableLighting", void 0);
  35367. __decorate([
  35368. BABYLON.serialize(),
  35369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35370. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  35371. __decorate([
  35372. BABYLON.serialize(),
  35373. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35374. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  35375. __decorate([
  35376. BABYLON.serialize(),
  35377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35378. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  35379. __decorate([
  35380. BABYLON.serialize(),
  35381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35382. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  35383. __decorate([
  35384. BABYLON.serialize(),
  35385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35386. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  35387. __decorate([
  35388. BABYLON.serialize(),
  35389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35390. ], PBRMaterial.prototype, "preMultiplyAlpha", void 0);
  35391. __decorate([
  35392. BABYLON.serialize(),
  35393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35394. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  35395. __decorate([
  35396. BABYLON.serializeAsTexture(),
  35397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35398. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  35399. __decorate([
  35400. BABYLON.serialize(),
  35401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35402. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  35403. return PBRMaterial;
  35404. }(BABYLON.PBRBaseMaterial));
  35405. BABYLON.PBRMaterial = PBRMaterial;
  35406. })(BABYLON || (BABYLON = {}));
  35407. //# sourceMappingURL=babylon.pbrMaterial.js.map
  35408. var BABYLON;
  35409. (function (BABYLON) {
  35410. /**
  35411. * The PBR material of BJS following the metal roughness convention.
  35412. *
  35413. * This fits to the PBR convention in the GLTF definition:
  35414. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  35415. */
  35416. var PBRMetallicRoughnessMaterial = (function (_super) {
  35417. __extends(PBRMetallicRoughnessMaterial, _super);
  35418. /**
  35419. * Instantiates a new PBRMetalRoughnessMaterial instance.
  35420. *
  35421. * @param name The material name
  35422. * @param scene The scene the material will be use in.
  35423. */
  35424. function PBRMetallicRoughnessMaterial(name, scene) {
  35425. var _this = _super.call(this, name, scene) || this;
  35426. _this._useRoughnessFromMetallicTextureAlpha = false;
  35427. _this._useRoughnessFromMetallicTextureGreen = true;
  35428. _this._useMetallnessFromMetallicTextureBlue = true;
  35429. return _this;
  35430. }
  35431. /**
  35432. * Return the currrent class name of the material.
  35433. */
  35434. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  35435. return "PBRMetallicRoughnessMaterial";
  35436. };
  35437. /**
  35438. * Return the active textures of the material.
  35439. */
  35440. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  35441. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35442. if (this.baseTexture) {
  35443. activeTextures.push(this.baseTexture);
  35444. }
  35445. if (this.metallicRoughnessTexture) {
  35446. activeTextures.push(this.metallicRoughnessTexture);
  35447. }
  35448. return activeTextures;
  35449. };
  35450. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  35451. if (_super.prototype.hasTexture.call(this, texture)) {
  35452. return true;
  35453. }
  35454. if (this.baseTexture === texture) {
  35455. return true;
  35456. }
  35457. if (this.metallicRoughnessTexture === texture) {
  35458. return true;
  35459. }
  35460. return false;
  35461. };
  35462. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  35463. var _this = this;
  35464. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  35465. clone.id = name;
  35466. clone.name = name;
  35467. return clone;
  35468. };
  35469. /**
  35470. * Serialize the material to a parsable JSON object.
  35471. */
  35472. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  35473. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  35474. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  35475. return serializationObject;
  35476. };
  35477. /**
  35478. * Parses a JSON object correponding to the serialize function.
  35479. */
  35480. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  35481. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  35482. };
  35483. __decorate([
  35484. BABYLON.serializeAsColor3(),
  35485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  35486. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  35487. __decorate([
  35488. BABYLON.serializeAsTexture(),
  35489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  35490. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  35491. __decorate([
  35492. BABYLON.serialize(),
  35493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35494. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  35495. __decorate([
  35496. BABYLON.serialize(),
  35497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35498. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  35499. __decorate([
  35500. BABYLON.serializeAsTexture(),
  35501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  35502. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  35503. return PBRMetallicRoughnessMaterial;
  35504. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  35505. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  35506. })(BABYLON || (BABYLON = {}));
  35507. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  35508. var BABYLON;
  35509. (function (BABYLON) {
  35510. /**
  35511. * The PBR material of BJS following the specular glossiness convention.
  35512. *
  35513. * This fits to the PBR convention in the GLTF definition:
  35514. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  35515. */
  35516. var PBRSpecularGlossinessMaterial = (function (_super) {
  35517. __extends(PBRSpecularGlossinessMaterial, _super);
  35518. /**
  35519. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  35520. *
  35521. * @param name The material name
  35522. * @param scene The scene the material will be use in.
  35523. */
  35524. function PBRSpecularGlossinessMaterial(name, scene) {
  35525. var _this = _super.call(this, name, scene) || this;
  35526. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  35527. return _this;
  35528. }
  35529. /**
  35530. * Return the currrent class name of the material.
  35531. */
  35532. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  35533. return "PBRSpecularGlossinessMaterial";
  35534. };
  35535. /**
  35536. * Return the active textures of the material.
  35537. */
  35538. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  35539. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35540. if (this.diffuseTexture) {
  35541. activeTextures.push(this.diffuseTexture);
  35542. }
  35543. if (this.specularGlossinessTexture) {
  35544. activeTextures.push(this.specularGlossinessTexture);
  35545. }
  35546. return activeTextures;
  35547. };
  35548. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  35549. if (_super.prototype.hasTexture.call(this, texture)) {
  35550. return true;
  35551. }
  35552. if (this.diffuseTexture === texture) {
  35553. return true;
  35554. }
  35555. if (this.specularGlossinessTexture === texture) {
  35556. return true;
  35557. }
  35558. return false;
  35559. };
  35560. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  35561. var _this = this;
  35562. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  35563. clone.id = name;
  35564. clone.name = name;
  35565. return clone;
  35566. };
  35567. /**
  35568. * Serialize the material to a parsable JSON object.
  35569. */
  35570. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  35571. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  35572. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  35573. return serializationObject;
  35574. };
  35575. /**
  35576. * Parses a JSON object correponding to the serialize function.
  35577. */
  35578. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  35579. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  35580. };
  35581. __decorate([
  35582. BABYLON.serializeAsColor3("diffuse"),
  35583. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  35584. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  35585. __decorate([
  35586. BABYLON.serializeAsTexture(),
  35587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  35588. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  35589. __decorate([
  35590. BABYLON.serializeAsColor3("specular"),
  35591. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  35592. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  35593. __decorate([
  35594. BABYLON.serialize(),
  35595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  35596. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  35597. __decorate([
  35598. BABYLON.serializeAsTexture(),
  35599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  35600. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  35601. return PBRSpecularGlossinessMaterial;
  35602. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  35603. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  35604. })(BABYLON || (BABYLON = {}));
  35605. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  35606. var BABYLON;
  35607. (function (BABYLON) {
  35608. BABYLON.CameraInputTypes = {};
  35609. var CameraInputsManager = (function () {
  35610. function CameraInputsManager(camera) {
  35611. this.attached = {};
  35612. this.camera = camera;
  35613. this.checkInputs = function () { };
  35614. }
  35615. CameraInputsManager.prototype.add = function (input) {
  35616. var type = input.getSimpleName();
  35617. if (this.attached[type]) {
  35618. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  35619. return;
  35620. }
  35621. this.attached[type] = input;
  35622. input.camera = this.camera;
  35623. //for checkInputs, we are dynamically creating a function
  35624. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  35625. if (input.checkInputs) {
  35626. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  35627. }
  35628. if (this.attachedElement) {
  35629. input.attachControl(this.attachedElement);
  35630. }
  35631. };
  35632. CameraInputsManager.prototype.remove = function (inputToRemove) {
  35633. for (var cam in this.attached) {
  35634. var input = this.attached[cam];
  35635. if (input === inputToRemove) {
  35636. input.detachControl(this.attachedElement);
  35637. input.camera = null;
  35638. delete this.attached[cam];
  35639. this.rebuildInputCheck();
  35640. }
  35641. }
  35642. };
  35643. CameraInputsManager.prototype.removeByType = function (inputType) {
  35644. for (var cam in this.attached) {
  35645. var input = this.attached[cam];
  35646. if (input.getClassName() === inputType) {
  35647. input.detachControl(this.attachedElement);
  35648. input.camera = null;
  35649. delete this.attached[cam];
  35650. this.rebuildInputCheck();
  35651. }
  35652. }
  35653. };
  35654. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  35655. var current = this.checkInputs;
  35656. return function () {
  35657. current();
  35658. fn();
  35659. };
  35660. };
  35661. CameraInputsManager.prototype.attachInput = function (input) {
  35662. input.attachControl(this.attachedElement, this.noPreventDefault);
  35663. };
  35664. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  35665. if (this.attachedElement) {
  35666. return;
  35667. }
  35668. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  35669. this.attachedElement = element;
  35670. this.noPreventDefault = noPreventDefault;
  35671. for (var cam in this.attached) {
  35672. var input = this.attached[cam];
  35673. this.attached[cam].attachControl(element, noPreventDefault);
  35674. }
  35675. };
  35676. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  35677. if (disconnect === void 0) { disconnect = false; }
  35678. if (this.attachedElement !== element) {
  35679. return;
  35680. }
  35681. for (var cam in this.attached) {
  35682. var input = this.attached[cam];
  35683. this.attached[cam].detachControl(element);
  35684. if (disconnect) {
  35685. this.attached[cam].camera = null;
  35686. }
  35687. }
  35688. this.attachedElement = null;
  35689. };
  35690. CameraInputsManager.prototype.rebuildInputCheck = function () {
  35691. this.checkInputs = function () { };
  35692. for (var cam in this.attached) {
  35693. var input = this.attached[cam];
  35694. if (input.checkInputs) {
  35695. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  35696. }
  35697. }
  35698. };
  35699. CameraInputsManager.prototype.clear = function () {
  35700. if (this.attachedElement) {
  35701. this.detachElement(this.attachedElement, true);
  35702. }
  35703. this.attached = {};
  35704. this.attachedElement = null;
  35705. this.checkInputs = function () { };
  35706. };
  35707. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  35708. var inputs = {};
  35709. for (var cam in this.attached) {
  35710. var input = this.attached[cam];
  35711. var res = BABYLON.SerializationHelper.Serialize(input);
  35712. inputs[input.getClassName()] = res;
  35713. }
  35714. serializedCamera.inputsmgr = inputs;
  35715. };
  35716. CameraInputsManager.prototype.parse = function (parsedCamera) {
  35717. var parsedInputs = parsedCamera.inputsmgr;
  35718. if (parsedInputs) {
  35719. this.clear();
  35720. for (var n in parsedInputs) {
  35721. var construct = BABYLON.CameraInputTypes[n];
  35722. if (construct) {
  35723. var parsedinput = parsedInputs[n];
  35724. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  35725. this.add(input);
  35726. }
  35727. }
  35728. }
  35729. else {
  35730. //2016-03-08 this part is for managing backward compatibility
  35731. for (var n in this.attached) {
  35732. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  35733. if (construct) {
  35734. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  35735. this.remove(this.attached[n]);
  35736. this.add(input);
  35737. }
  35738. }
  35739. }
  35740. };
  35741. return CameraInputsManager;
  35742. }());
  35743. BABYLON.CameraInputsManager = CameraInputsManager;
  35744. })(BABYLON || (BABYLON = {}));
  35745. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  35746. var BABYLON;
  35747. (function (BABYLON) {
  35748. var FreeCameraMouseInput = (function () {
  35749. function FreeCameraMouseInput(touchEnabled) {
  35750. if (touchEnabled === void 0) { touchEnabled = true; }
  35751. this.touchEnabled = touchEnabled;
  35752. this.buttons = [0, 1, 2];
  35753. this.angularSensibility = 2000.0;
  35754. }
  35755. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  35756. var _this = this;
  35757. var engine = this.camera.getEngine();
  35758. if (!this._pointerInput) {
  35759. this._pointerInput = function (p, s) {
  35760. var evt = p.event;
  35761. if (engine.isInVRExclusivePointerMode) {
  35762. return;
  35763. }
  35764. if (!_this.touchEnabled && evt.pointerType === "touch") {
  35765. return;
  35766. }
  35767. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  35768. return;
  35769. }
  35770. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  35771. try {
  35772. evt.srcElement.setPointerCapture(evt.pointerId);
  35773. }
  35774. catch (e) {
  35775. //Nothing to do with the error. Execution will continue.
  35776. }
  35777. _this.previousPosition = {
  35778. x: evt.clientX,
  35779. y: evt.clientY
  35780. };
  35781. if (!noPreventDefault) {
  35782. evt.preventDefault();
  35783. element.focus();
  35784. }
  35785. }
  35786. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  35787. try {
  35788. evt.srcElement.releasePointerCapture(evt.pointerId);
  35789. }
  35790. catch (e) {
  35791. //Nothing to do with the error.
  35792. }
  35793. _this.previousPosition = null;
  35794. if (!noPreventDefault) {
  35795. evt.preventDefault();
  35796. }
  35797. }
  35798. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  35799. if (!_this.previousPosition || engine.isPointerLock) {
  35800. return;
  35801. }
  35802. var offsetX = evt.clientX - _this.previousPosition.x;
  35803. var offsetY = evt.clientY - _this.previousPosition.y;
  35804. if (_this.camera.getScene().useRightHandedSystem) {
  35805. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  35806. }
  35807. else {
  35808. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  35809. }
  35810. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  35811. _this.previousPosition = {
  35812. x: evt.clientX,
  35813. y: evt.clientY
  35814. };
  35815. if (!noPreventDefault) {
  35816. evt.preventDefault();
  35817. }
  35818. }
  35819. };
  35820. }
  35821. this._onMouseMove = function (evt) {
  35822. if (!engine.isPointerLock) {
  35823. return;
  35824. }
  35825. if (engine.isInVRExclusivePointerMode) {
  35826. return;
  35827. }
  35828. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  35829. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  35830. if (_this.camera.getScene().useRightHandedSystem) {
  35831. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  35832. }
  35833. else {
  35834. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  35835. }
  35836. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  35837. _this.previousPosition = null;
  35838. if (!noPreventDefault) {
  35839. evt.preventDefault();
  35840. }
  35841. };
  35842. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  35843. element.addEventListener("mousemove", this._onMouseMove, false);
  35844. };
  35845. FreeCameraMouseInput.prototype.detachControl = function (element) {
  35846. if (this._observer && element) {
  35847. this.camera.getScene().onPointerObservable.remove(this._observer);
  35848. element.removeEventListener("mousemove", this._onMouseMove);
  35849. this._observer = null;
  35850. this._onMouseMove = null;
  35851. this.previousPosition = null;
  35852. }
  35853. };
  35854. FreeCameraMouseInput.prototype.getClassName = function () {
  35855. return "FreeCameraMouseInput";
  35856. };
  35857. FreeCameraMouseInput.prototype.getSimpleName = function () {
  35858. return "mouse";
  35859. };
  35860. __decorate([
  35861. BABYLON.serialize()
  35862. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  35863. __decorate([
  35864. BABYLON.serialize()
  35865. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  35866. return FreeCameraMouseInput;
  35867. }());
  35868. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  35869. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  35870. })(BABYLON || (BABYLON = {}));
  35871. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  35872. var BABYLON;
  35873. (function (BABYLON) {
  35874. var FreeCameraKeyboardMoveInput = (function () {
  35875. function FreeCameraKeyboardMoveInput() {
  35876. this._keys = new Array();
  35877. this.keysUp = [38];
  35878. this.keysDown = [40];
  35879. this.keysLeft = [37];
  35880. this.keysRight = [39];
  35881. }
  35882. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  35883. var _this = this;
  35884. if (this._onCanvasBlurObserver) {
  35885. return;
  35886. }
  35887. this._scene = this.camera.getScene();
  35888. this._engine = this._scene.getEngine();
  35889. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  35890. _this._keys = [];
  35891. });
  35892. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  35893. var evt = info.event;
  35894. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  35895. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  35896. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  35897. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  35898. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  35899. var index = _this._keys.indexOf(evt.keyCode);
  35900. if (index === -1) {
  35901. _this._keys.push(evt.keyCode);
  35902. }
  35903. if (!noPreventDefault) {
  35904. evt.preventDefault();
  35905. }
  35906. }
  35907. }
  35908. else {
  35909. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  35910. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  35911. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  35912. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  35913. var index = _this._keys.indexOf(evt.keyCode);
  35914. if (index >= 0) {
  35915. _this._keys.splice(index, 1);
  35916. }
  35917. if (!noPreventDefault) {
  35918. evt.preventDefault();
  35919. }
  35920. }
  35921. }
  35922. });
  35923. };
  35924. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  35925. if (this._scene) {
  35926. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  35927. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  35928. this._onKeyboardObserver = null;
  35929. this._onCanvasBlurObserver = null;
  35930. }
  35931. this._keys = [];
  35932. };
  35933. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  35934. if (this._onKeyboardObserver) {
  35935. var camera = this.camera;
  35936. // Keyboard
  35937. for (var index = 0; index < this._keys.length; index++) {
  35938. var keyCode = this._keys[index];
  35939. var speed = camera._computeLocalCameraSpeed();
  35940. if (this.keysLeft.indexOf(keyCode) !== -1) {
  35941. camera._localDirection.copyFromFloats(-speed, 0, 0);
  35942. }
  35943. else if (this.keysUp.indexOf(keyCode) !== -1) {
  35944. camera._localDirection.copyFromFloats(0, 0, speed);
  35945. }
  35946. else if (this.keysRight.indexOf(keyCode) !== -1) {
  35947. camera._localDirection.copyFromFloats(speed, 0, 0);
  35948. }
  35949. else if (this.keysDown.indexOf(keyCode) !== -1) {
  35950. camera._localDirection.copyFromFloats(0, 0, -speed);
  35951. }
  35952. if (camera.getScene().useRightHandedSystem) {
  35953. camera._localDirection.z *= -1;
  35954. }
  35955. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  35956. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  35957. camera.cameraDirection.addInPlace(camera._transformedDirection);
  35958. }
  35959. }
  35960. };
  35961. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  35962. return "FreeCameraKeyboardMoveInput";
  35963. };
  35964. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  35965. this._keys = [];
  35966. };
  35967. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  35968. return "keyboard";
  35969. };
  35970. __decorate([
  35971. BABYLON.serialize()
  35972. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  35973. __decorate([
  35974. BABYLON.serialize()
  35975. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  35976. __decorate([
  35977. BABYLON.serialize()
  35978. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  35979. __decorate([
  35980. BABYLON.serialize()
  35981. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  35982. return FreeCameraKeyboardMoveInput;
  35983. }());
  35984. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  35985. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  35986. })(BABYLON || (BABYLON = {}));
  35987. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  35988. var BABYLON;
  35989. (function (BABYLON) {
  35990. var FreeCameraInputsManager = (function (_super) {
  35991. __extends(FreeCameraInputsManager, _super);
  35992. function FreeCameraInputsManager(camera) {
  35993. return _super.call(this, camera) || this;
  35994. }
  35995. FreeCameraInputsManager.prototype.addKeyboard = function () {
  35996. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  35997. return this;
  35998. };
  35999. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  36000. if (touchEnabled === void 0) { touchEnabled = true; }
  36001. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  36002. return this;
  36003. };
  36004. FreeCameraInputsManager.prototype.addGamepad = function () {
  36005. this.add(new BABYLON.FreeCameraGamepadInput());
  36006. return this;
  36007. };
  36008. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  36009. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  36010. return this;
  36011. };
  36012. FreeCameraInputsManager.prototype.addTouch = function () {
  36013. this.add(new BABYLON.FreeCameraTouchInput());
  36014. return this;
  36015. };
  36016. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  36017. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  36018. return this;
  36019. };
  36020. return FreeCameraInputsManager;
  36021. }(BABYLON.CameraInputsManager));
  36022. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  36023. })(BABYLON || (BABYLON = {}));
  36024. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  36025. /// <reference path="babylon.camera.ts" />
  36026. var BABYLON;
  36027. (function (BABYLON) {
  36028. var TargetCamera = (function (_super) {
  36029. __extends(TargetCamera, _super);
  36030. function TargetCamera(name, position, scene) {
  36031. var _this = _super.call(this, name, position, scene) || this;
  36032. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  36033. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  36034. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  36035. _this.speed = 2.0;
  36036. _this.noRotationConstraint = false;
  36037. _this.lockedTarget = null;
  36038. _this._currentTarget = BABYLON.Vector3.Zero();
  36039. _this._viewMatrix = BABYLON.Matrix.Zero();
  36040. _this._camMatrix = BABYLON.Matrix.Zero();
  36041. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  36042. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  36043. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  36044. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  36045. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  36046. _this._lookAtTemp = BABYLON.Matrix.Zero();
  36047. _this._tempMatrix = BABYLON.Matrix.Zero();
  36048. return _this;
  36049. }
  36050. TargetCamera.prototype.getFrontPosition = function (distance) {
  36051. var direction = this.getTarget().subtract(this.position);
  36052. direction.normalize();
  36053. direction.scaleInPlace(distance);
  36054. return this.globalPosition.add(direction);
  36055. };
  36056. TargetCamera.prototype._getLockedTargetPosition = function () {
  36057. if (!this.lockedTarget) {
  36058. return null;
  36059. }
  36060. if (this.lockedTarget.absolutePosition) {
  36061. this.lockedTarget.computeWorldMatrix();
  36062. }
  36063. return this.lockedTarget.absolutePosition || this.lockedTarget;
  36064. };
  36065. TargetCamera.prototype.storeState = function () {
  36066. this._storedPosition = this.position.clone();
  36067. this._storedRotation = this.rotation.clone();
  36068. if (this.rotationQuaternion) {
  36069. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  36070. }
  36071. return _super.prototype.storeState.call(this);
  36072. };
  36073. /**
  36074. * Restored camera state. You must call storeState() first
  36075. */
  36076. TargetCamera.prototype._restoreStateValues = function () {
  36077. if (!_super.prototype._restoreStateValues.call(this)) {
  36078. return false;
  36079. }
  36080. this.position = this._storedPosition.clone();
  36081. this.rotation = this._storedRotation.clone();
  36082. if (this.rotationQuaternion) {
  36083. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  36084. }
  36085. this.cameraDirection.copyFromFloats(0, 0, 0);
  36086. this.cameraRotation.copyFromFloats(0, 0);
  36087. return true;
  36088. };
  36089. // Cache
  36090. TargetCamera.prototype._initCache = function () {
  36091. _super.prototype._initCache.call(this);
  36092. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  36093. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  36094. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  36095. };
  36096. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  36097. if (!ignoreParentClass) {
  36098. _super.prototype._updateCache.call(this);
  36099. }
  36100. var lockedTargetPosition = this._getLockedTargetPosition();
  36101. if (!lockedTargetPosition) {
  36102. this._cache.lockedTarget = null;
  36103. }
  36104. else {
  36105. if (!this._cache.lockedTarget) {
  36106. this._cache.lockedTarget = lockedTargetPosition.clone();
  36107. }
  36108. else {
  36109. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  36110. }
  36111. }
  36112. this._cache.rotation.copyFrom(this.rotation);
  36113. if (this.rotationQuaternion)
  36114. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  36115. };
  36116. // Synchronized
  36117. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  36118. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  36119. return false;
  36120. }
  36121. var lockedTargetPosition = this._getLockedTargetPosition();
  36122. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  36123. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  36124. };
  36125. // Methods
  36126. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  36127. var engine = this.getEngine();
  36128. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  36129. };
  36130. // Target
  36131. TargetCamera.prototype.setTarget = function (target) {
  36132. this.upVector.normalize();
  36133. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  36134. this._camMatrix.invert();
  36135. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  36136. var vDir = target.subtract(this.position);
  36137. if (vDir.x >= 0.0) {
  36138. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  36139. }
  36140. else {
  36141. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  36142. }
  36143. this.rotation.z = 0;
  36144. if (isNaN(this.rotation.x)) {
  36145. this.rotation.x = 0;
  36146. }
  36147. if (isNaN(this.rotation.y)) {
  36148. this.rotation.y = 0;
  36149. }
  36150. if (isNaN(this.rotation.z)) {
  36151. this.rotation.z = 0;
  36152. }
  36153. if (this.rotationQuaternion) {
  36154. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  36155. }
  36156. };
  36157. /**
  36158. * Return the current target position of the camera. This value is expressed in local space.
  36159. */
  36160. TargetCamera.prototype.getTarget = function () {
  36161. return this._currentTarget;
  36162. };
  36163. TargetCamera.prototype._decideIfNeedsToMove = function () {
  36164. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  36165. };
  36166. TargetCamera.prototype._updatePosition = function () {
  36167. if (this.parent) {
  36168. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  36169. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  36170. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  36171. return;
  36172. }
  36173. this.position.addInPlace(this.cameraDirection);
  36174. };
  36175. TargetCamera.prototype._checkInputs = function () {
  36176. var needToMove = this._decideIfNeedsToMove();
  36177. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  36178. // Move
  36179. if (needToMove) {
  36180. this._updatePosition();
  36181. }
  36182. // Rotate
  36183. if (needToRotate) {
  36184. this.rotation.x += this.cameraRotation.x;
  36185. this.rotation.y += this.cameraRotation.y;
  36186. //rotate, if quaternion is set and rotation was used
  36187. if (this.rotationQuaternion) {
  36188. var len = this.rotation.lengthSquared();
  36189. if (len) {
  36190. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  36191. }
  36192. }
  36193. if (!this.noRotationConstraint) {
  36194. var limit = (Math.PI / 2) * 0.95;
  36195. if (this.rotation.x > limit)
  36196. this.rotation.x = limit;
  36197. if (this.rotation.x < -limit)
  36198. this.rotation.x = -limit;
  36199. }
  36200. }
  36201. // Inertia
  36202. if (needToMove) {
  36203. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  36204. this.cameraDirection.x = 0;
  36205. }
  36206. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  36207. this.cameraDirection.y = 0;
  36208. }
  36209. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  36210. this.cameraDirection.z = 0;
  36211. }
  36212. this.cameraDirection.scaleInPlace(this.inertia);
  36213. }
  36214. if (needToRotate) {
  36215. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  36216. this.cameraRotation.x = 0;
  36217. }
  36218. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  36219. this.cameraRotation.y = 0;
  36220. }
  36221. this.cameraRotation.scaleInPlace(this.inertia);
  36222. }
  36223. _super.prototype._checkInputs.call(this);
  36224. };
  36225. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  36226. if (this.rotationQuaternion) {
  36227. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  36228. //update the up vector!
  36229. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  36230. }
  36231. else {
  36232. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  36233. }
  36234. };
  36235. TargetCamera.prototype._getViewMatrix = function () {
  36236. if (!this.lockedTarget) {
  36237. // Compute
  36238. this._updateCameraRotationMatrix();
  36239. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  36240. // Computing target and final matrix
  36241. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  36242. }
  36243. else {
  36244. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  36245. }
  36246. if (this.getScene().useRightHandedSystem) {
  36247. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  36248. }
  36249. else {
  36250. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  36251. }
  36252. return this._viewMatrix;
  36253. };
  36254. /**
  36255. * @override
  36256. * Override Camera.createRigCamera
  36257. */
  36258. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  36259. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  36260. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  36261. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  36262. if (!this.rotationQuaternion) {
  36263. this.rotationQuaternion = new BABYLON.Quaternion();
  36264. }
  36265. rigCamera._cameraRigParams = {};
  36266. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  36267. }
  36268. return rigCamera;
  36269. }
  36270. return null;
  36271. };
  36272. /**
  36273. * @override
  36274. * Override Camera._updateRigCameras
  36275. */
  36276. TargetCamera.prototype._updateRigCameras = function () {
  36277. var camLeft = this._rigCameras[0];
  36278. var camRight = this._rigCameras[1];
  36279. switch (this.cameraRigMode) {
  36280. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  36281. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  36282. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  36283. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  36284. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  36285. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  36286. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  36287. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  36288. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  36289. camLeft.setTarget(this.getTarget());
  36290. camRight.setTarget(this.getTarget());
  36291. break;
  36292. case BABYLON.Camera.RIG_MODE_VR:
  36293. if (camLeft.rotationQuaternion) {
  36294. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  36295. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  36296. }
  36297. else {
  36298. camLeft.rotation.copyFrom(this.rotation);
  36299. camRight.rotation.copyFrom(this.rotation);
  36300. }
  36301. camLeft.position.copyFrom(this.position);
  36302. camRight.position.copyFrom(this.position);
  36303. break;
  36304. }
  36305. _super.prototype._updateRigCameras.call(this);
  36306. };
  36307. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  36308. if (!this._rigCamTransformMatrix) {
  36309. this._rigCamTransformMatrix = new BABYLON.Matrix();
  36310. }
  36311. var target = this.getTarget();
  36312. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  36313. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  36314. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  36315. };
  36316. TargetCamera.prototype.getClassName = function () {
  36317. return "TargetCamera";
  36318. };
  36319. __decorate([
  36320. BABYLON.serializeAsVector3()
  36321. ], TargetCamera.prototype, "rotation", void 0);
  36322. __decorate([
  36323. BABYLON.serialize()
  36324. ], TargetCamera.prototype, "speed", void 0);
  36325. __decorate([
  36326. BABYLON.serializeAsMeshReference("lockedTargetId")
  36327. ], TargetCamera.prototype, "lockedTarget", void 0);
  36328. return TargetCamera;
  36329. }(BABYLON.Camera));
  36330. BABYLON.TargetCamera = TargetCamera;
  36331. })(BABYLON || (BABYLON = {}));
  36332. //# sourceMappingURL=babylon.targetCamera.js.map
  36333. var BABYLON;
  36334. (function (BABYLON) {
  36335. var FreeCamera = (function (_super) {
  36336. __extends(FreeCamera, _super);
  36337. function FreeCamera(name, position, scene) {
  36338. var _this = _super.call(this, name, position, scene) || this;
  36339. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  36340. _this.checkCollisions = false;
  36341. _this.applyGravity = false;
  36342. _this._needMoveForGravity = false;
  36343. _this._oldPosition = BABYLON.Vector3.Zero();
  36344. _this._diffPosition = BABYLON.Vector3.Zero();
  36345. _this._newPosition = BABYLON.Vector3.Zero();
  36346. // Collisions
  36347. _this._collisionMask = -1;
  36348. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  36349. if (collidedMesh === void 0) { collidedMesh = null; }
  36350. //TODO move this to the collision coordinator!
  36351. if (_this.getScene().workerCollisions)
  36352. newPosition.multiplyInPlace(_this._collider.radius);
  36353. var updatePosition = function (newPos) {
  36354. _this._newPosition.copyFrom(newPos);
  36355. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  36356. var oldPosition = _this.position.clone();
  36357. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  36358. _this.position.addInPlace(_this._diffPosition);
  36359. if (_this.onCollide && collidedMesh) {
  36360. _this.onCollide(collidedMesh);
  36361. }
  36362. }
  36363. };
  36364. updatePosition(newPosition);
  36365. };
  36366. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  36367. _this.inputs.addKeyboard().addMouse();
  36368. return _this;
  36369. }
  36370. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  36371. //-- begin properties for backward compatibility for inputs
  36372. get: function () {
  36373. var mouse = this.inputs.attached["mouse"];
  36374. if (mouse)
  36375. return mouse.angularSensibility;
  36376. },
  36377. set: function (value) {
  36378. var mouse = this.inputs.attached["mouse"];
  36379. if (mouse)
  36380. mouse.angularSensibility = value;
  36381. },
  36382. enumerable: true,
  36383. configurable: true
  36384. });
  36385. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  36386. get: function () {
  36387. var keyboard = this.inputs.attached["keyboard"];
  36388. if (keyboard)
  36389. return keyboard.keysUp;
  36390. },
  36391. set: function (value) {
  36392. var keyboard = this.inputs.attached["keyboard"];
  36393. if (keyboard)
  36394. keyboard.keysUp = value;
  36395. },
  36396. enumerable: true,
  36397. configurable: true
  36398. });
  36399. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  36400. get: function () {
  36401. var keyboard = this.inputs.attached["keyboard"];
  36402. if (keyboard)
  36403. return keyboard.keysDown;
  36404. },
  36405. set: function (value) {
  36406. var keyboard = this.inputs.attached["keyboard"];
  36407. if (keyboard)
  36408. keyboard.keysDown = value;
  36409. },
  36410. enumerable: true,
  36411. configurable: true
  36412. });
  36413. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  36414. get: function () {
  36415. var keyboard = this.inputs.attached["keyboard"];
  36416. if (keyboard)
  36417. return keyboard.keysLeft;
  36418. },
  36419. set: function (value) {
  36420. var keyboard = this.inputs.attached["keyboard"];
  36421. if (keyboard)
  36422. keyboard.keysLeft = value;
  36423. },
  36424. enumerable: true,
  36425. configurable: true
  36426. });
  36427. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  36428. get: function () {
  36429. var keyboard = this.inputs.attached["keyboard"];
  36430. if (keyboard)
  36431. return keyboard.keysRight;
  36432. },
  36433. set: function (value) {
  36434. var keyboard = this.inputs.attached["keyboard"];
  36435. if (keyboard)
  36436. keyboard.keysRight = value;
  36437. },
  36438. enumerable: true,
  36439. configurable: true
  36440. });
  36441. // Controls
  36442. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  36443. this.inputs.attachElement(element, noPreventDefault);
  36444. };
  36445. FreeCamera.prototype.detachControl = function (element) {
  36446. this.inputs.detachElement(element);
  36447. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  36448. this.cameraRotation = new BABYLON.Vector2(0, 0);
  36449. };
  36450. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  36451. get: function () {
  36452. return this._collisionMask;
  36453. },
  36454. set: function (mask) {
  36455. this._collisionMask = !isNaN(mask) ? mask : -1;
  36456. },
  36457. enumerable: true,
  36458. configurable: true
  36459. });
  36460. FreeCamera.prototype._collideWithWorld = function (displacement) {
  36461. var globalPosition;
  36462. if (this.parent) {
  36463. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  36464. }
  36465. else {
  36466. globalPosition = this.position;
  36467. }
  36468. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  36469. if (!this._collider) {
  36470. this._collider = new BABYLON.Collider();
  36471. }
  36472. this._collider.radius = this.ellipsoid;
  36473. this._collider.collisionMask = this._collisionMask;
  36474. //no need for clone, as long as gravity is not on.
  36475. var actualDisplacement = displacement;
  36476. //add gravity to the direction to prevent the dual-collision checking
  36477. if (this.applyGravity) {
  36478. //this prevents mending with cameraDirection, a global variable of the free camera class.
  36479. actualDisplacement = displacement.add(this.getScene().gravity);
  36480. }
  36481. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  36482. };
  36483. FreeCamera.prototype._checkInputs = function () {
  36484. if (!this._localDirection) {
  36485. this._localDirection = BABYLON.Vector3.Zero();
  36486. this._transformedDirection = BABYLON.Vector3.Zero();
  36487. }
  36488. this.inputs.checkInputs();
  36489. _super.prototype._checkInputs.call(this);
  36490. };
  36491. FreeCamera.prototype._decideIfNeedsToMove = function () {
  36492. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  36493. };
  36494. FreeCamera.prototype._updatePosition = function () {
  36495. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  36496. this._collideWithWorld(this.cameraDirection);
  36497. }
  36498. else {
  36499. _super.prototype._updatePosition.call(this);
  36500. }
  36501. };
  36502. FreeCamera.prototype.dispose = function () {
  36503. this.inputs.clear();
  36504. _super.prototype.dispose.call(this);
  36505. };
  36506. FreeCamera.prototype.getClassName = function () {
  36507. return "FreeCamera";
  36508. };
  36509. __decorate([
  36510. BABYLON.serializeAsVector3()
  36511. ], FreeCamera.prototype, "ellipsoid", void 0);
  36512. __decorate([
  36513. BABYLON.serialize()
  36514. ], FreeCamera.prototype, "checkCollisions", void 0);
  36515. __decorate([
  36516. BABYLON.serialize()
  36517. ], FreeCamera.prototype, "applyGravity", void 0);
  36518. return FreeCamera;
  36519. }(BABYLON.TargetCamera));
  36520. BABYLON.FreeCamera = FreeCamera;
  36521. })(BABYLON || (BABYLON = {}));
  36522. //# sourceMappingURL=babylon.freeCamera.js.map
  36523. var BABYLON;
  36524. (function (BABYLON) {
  36525. var ArcRotateCameraKeyboardMoveInput = (function () {
  36526. function ArcRotateCameraKeyboardMoveInput() {
  36527. this._keys = new Array();
  36528. this.keysUp = [38];
  36529. this.keysDown = [40];
  36530. this.keysLeft = [37];
  36531. this.keysRight = [39];
  36532. this.keysReset = [220];
  36533. this.panningSensibility = 50.0;
  36534. this.zoomingSensibility = 25.0;
  36535. this.useAltToZoom = true;
  36536. }
  36537. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  36538. var _this = this;
  36539. if (this._onCanvasBlurObserver) {
  36540. return;
  36541. }
  36542. this._scene = this.camera.getScene();
  36543. this._engine = this._scene.getEngine();
  36544. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  36545. _this._keys = [];
  36546. });
  36547. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  36548. var evt = info.event;
  36549. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  36550. _this._ctrlPressed = evt.ctrlKey;
  36551. _this._altPressed = evt.altKey;
  36552. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  36553. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  36554. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  36555. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  36556. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  36557. var index = _this._keys.indexOf(evt.keyCode);
  36558. if (index === -1) {
  36559. _this._keys.push(evt.keyCode);
  36560. }
  36561. if (evt.preventDefault) {
  36562. if (!noPreventDefault) {
  36563. evt.preventDefault();
  36564. }
  36565. }
  36566. }
  36567. }
  36568. else {
  36569. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  36570. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  36571. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  36572. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  36573. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  36574. var index = _this._keys.indexOf(evt.keyCode);
  36575. if (index >= 0) {
  36576. _this._keys.splice(index, 1);
  36577. }
  36578. if (evt.preventDefault) {
  36579. if (!noPreventDefault) {
  36580. evt.preventDefault();
  36581. }
  36582. }
  36583. }
  36584. }
  36585. });
  36586. };
  36587. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  36588. if (this._scene) {
  36589. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  36590. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  36591. this._onKeyboardObserver = null;
  36592. this._onCanvasBlurObserver = null;
  36593. }
  36594. this._keys = [];
  36595. };
  36596. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  36597. if (this._onKeyboardObserver) {
  36598. var camera = this.camera;
  36599. for (var index = 0; index < this._keys.length; index++) {
  36600. var keyCode = this._keys[index];
  36601. if (this.keysLeft.indexOf(keyCode) !== -1) {
  36602. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  36603. camera.inertialPanningX -= 1 / this.panningSensibility;
  36604. }
  36605. else {
  36606. camera.inertialAlphaOffset -= 0.01;
  36607. }
  36608. }
  36609. else if (this.keysUp.indexOf(keyCode) !== -1) {
  36610. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  36611. camera.inertialPanningY += 1 / this.panningSensibility;
  36612. }
  36613. else if (this._altPressed && this.useAltToZoom) {
  36614. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  36615. }
  36616. else {
  36617. camera.inertialBetaOffset -= 0.01;
  36618. }
  36619. }
  36620. else if (this.keysRight.indexOf(keyCode) !== -1) {
  36621. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  36622. camera.inertialPanningX += 1 / this.panningSensibility;
  36623. }
  36624. else {
  36625. camera.inertialAlphaOffset += 0.01;
  36626. }
  36627. }
  36628. else if (this.keysDown.indexOf(keyCode) !== -1) {
  36629. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  36630. camera.inertialPanningY -= 1 / this.panningSensibility;
  36631. }
  36632. else if (this._altPressed && this.useAltToZoom) {
  36633. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  36634. }
  36635. else {
  36636. camera.inertialBetaOffset += 0.01;
  36637. }
  36638. }
  36639. else if (this.keysReset.indexOf(keyCode) !== -1) {
  36640. camera.restoreState();
  36641. }
  36642. }
  36643. }
  36644. };
  36645. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  36646. return "ArcRotateCameraKeyboardMoveInput";
  36647. };
  36648. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  36649. return "keyboard";
  36650. };
  36651. __decorate([
  36652. BABYLON.serialize()
  36653. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  36654. __decorate([
  36655. BABYLON.serialize()
  36656. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  36657. __decorate([
  36658. BABYLON.serialize()
  36659. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  36660. __decorate([
  36661. BABYLON.serialize()
  36662. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  36663. __decorate([
  36664. BABYLON.serialize()
  36665. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  36666. __decorate([
  36667. BABYLON.serialize()
  36668. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  36669. __decorate([
  36670. BABYLON.serialize()
  36671. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  36672. __decorate([
  36673. BABYLON.serialize()
  36674. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  36675. return ArcRotateCameraKeyboardMoveInput;
  36676. }());
  36677. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  36678. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  36679. })(BABYLON || (BABYLON = {}));
  36680. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  36681. var BABYLON;
  36682. (function (BABYLON) {
  36683. var ArcRotateCameraMouseWheelInput = (function () {
  36684. function ArcRotateCameraMouseWheelInput() {
  36685. this.wheelPrecision = 3.0;
  36686. /**
  36687. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  36688. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  36689. */
  36690. this.wheelDeltaPercentage = 0;
  36691. }
  36692. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  36693. var _this = this;
  36694. this._wheel = function (p, s) {
  36695. //sanity check - this should be a PointerWheel event.
  36696. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  36697. return;
  36698. var event = p.event;
  36699. var delta = 0;
  36700. if (event.wheelDelta) {
  36701. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  36702. }
  36703. else if (event.detail) {
  36704. delta = -event.detail / _this.wheelPrecision;
  36705. }
  36706. if (delta)
  36707. _this.camera.inertialRadiusOffset += delta;
  36708. if (event.preventDefault) {
  36709. if (!noPreventDefault) {
  36710. event.preventDefault();
  36711. }
  36712. }
  36713. };
  36714. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  36715. };
  36716. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  36717. if (this._observer && element) {
  36718. this.camera.getScene().onPointerObservable.remove(this._observer);
  36719. this._observer = null;
  36720. this._wheel = null;
  36721. }
  36722. };
  36723. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  36724. return "ArcRotateCameraMouseWheelInput";
  36725. };
  36726. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  36727. return "mousewheel";
  36728. };
  36729. __decorate([
  36730. BABYLON.serialize()
  36731. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  36732. __decorate([
  36733. BABYLON.serialize()
  36734. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  36735. return ArcRotateCameraMouseWheelInput;
  36736. }());
  36737. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  36738. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  36739. })(BABYLON || (BABYLON = {}));
  36740. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  36741. var BABYLON;
  36742. (function (BABYLON) {
  36743. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  36744. var ArcRotateCameraPointersInput = (function () {
  36745. function ArcRotateCameraPointersInput() {
  36746. this.buttons = [0, 1, 2];
  36747. this.angularSensibilityX = 1000.0;
  36748. this.angularSensibilityY = 1000.0;
  36749. this.pinchPrecision = 12.0;
  36750. /**
  36751. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  36752. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  36753. */
  36754. this.pinchDeltaPercentage = 0;
  36755. this.panningSensibility = 1000.0;
  36756. this.multiTouchPanning = true;
  36757. this.multiTouchPanAndZoom = true;
  36758. this._isPanClick = false;
  36759. this.pinchInwards = true;
  36760. }
  36761. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  36762. var _this = this;
  36763. var engine = this.camera.getEngine();
  36764. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  36765. var pointA, pointB;
  36766. var previousPinchSquaredDistance = 0;
  36767. var initialDistance = 0;
  36768. var twoFingerActivityCount = 0;
  36769. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  36770. this._pointerInput = function (p, s) {
  36771. var evt = p.event;
  36772. if (engine.isInVRExclusivePointerMode) {
  36773. return;
  36774. }
  36775. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  36776. return;
  36777. }
  36778. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  36779. try {
  36780. evt.srcElement.setPointerCapture(evt.pointerId);
  36781. }
  36782. catch (e) {
  36783. //Nothing to do with the error. Execution will continue.
  36784. }
  36785. // Manage panning with pan button click
  36786. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  36787. // manage pointers
  36788. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  36789. if (pointA === undefined) {
  36790. pointA = cacheSoloPointer;
  36791. }
  36792. else if (pointB === undefined) {
  36793. pointB = cacheSoloPointer;
  36794. }
  36795. if (!noPreventDefault) {
  36796. evt.preventDefault();
  36797. element.focus();
  36798. }
  36799. }
  36800. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  36801. _this.camera.restoreState();
  36802. }
  36803. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  36804. try {
  36805. evt.srcElement.releasePointerCapture(evt.pointerId);
  36806. }
  36807. catch (e) {
  36808. //Nothing to do with the error.
  36809. }
  36810. cacheSoloPointer = null;
  36811. previousPinchSquaredDistance = 0;
  36812. previousMultiTouchPanPosition.isPaning = false;
  36813. previousMultiTouchPanPosition.isPinching = false;
  36814. twoFingerActivityCount = 0;
  36815. initialDistance = 0;
  36816. if (p.event.pointerType !== "touch") {
  36817. pointB = undefined; // Mouse and pen are mono pointer
  36818. }
  36819. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  36820. //but emptying completly pointers collection is required to fix a bug on iPhone :
  36821. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  36822. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  36823. if (engine.badOS) {
  36824. pointA = pointB = undefined;
  36825. }
  36826. else {
  36827. //only remove the impacted pointer in case of multitouch allowing on most
  36828. //platforms switching from rotate to zoom and pan seamlessly.
  36829. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  36830. pointA = pointB;
  36831. pointB = undefined;
  36832. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  36833. }
  36834. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  36835. pointB = undefined;
  36836. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  36837. }
  36838. else {
  36839. pointA = pointB = undefined;
  36840. }
  36841. }
  36842. if (!noPreventDefault) {
  36843. evt.preventDefault();
  36844. }
  36845. }
  36846. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  36847. if (!noPreventDefault) {
  36848. evt.preventDefault();
  36849. }
  36850. // One button down
  36851. if (pointA && pointB === undefined) {
  36852. if (_this.panningSensibility !== 0 &&
  36853. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  36854. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  36855. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  36856. }
  36857. else {
  36858. var offsetX = evt.clientX - cacheSoloPointer.x;
  36859. var offsetY = evt.clientY - cacheSoloPointer.y;
  36860. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  36861. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  36862. }
  36863. cacheSoloPointer.x = evt.clientX;
  36864. cacheSoloPointer.y = evt.clientY;
  36865. }
  36866. else if (pointA && pointB) {
  36867. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  36868. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  36869. ed.x = evt.clientX;
  36870. ed.y = evt.clientY;
  36871. var direction = _this.pinchInwards ? 1 : -1;
  36872. var distX = pointA.x - pointB.x;
  36873. var distY = pointA.y - pointB.y;
  36874. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  36875. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  36876. if (previousPinchSquaredDistance === 0) {
  36877. initialDistance = pinchDistance;
  36878. previousPinchSquaredDistance = pinchSquaredDistance;
  36879. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  36880. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  36881. return;
  36882. }
  36883. if (_this.multiTouchPanAndZoom) {
  36884. if (_this.pinchDeltaPercentage) {
  36885. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  36886. }
  36887. else {
  36888. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  36889. (_this.pinchPrecision *
  36890. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  36891. direction);
  36892. }
  36893. if (_this.panningSensibility !== 0) {
  36894. var pointersCenterX = (pointA.x + pointB.x) / 2;
  36895. var pointersCenterY = (pointA.y + pointB.y) / 2;
  36896. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  36897. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  36898. previousMultiTouchPanPosition.x = pointersCenterX;
  36899. previousMultiTouchPanPosition.y = pointersCenterY;
  36900. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  36901. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  36902. }
  36903. }
  36904. else {
  36905. twoFingerActivityCount++;
  36906. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  36907. if (_this.pinchDeltaPercentage) {
  36908. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  36909. }
  36910. else {
  36911. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  36912. (_this.pinchPrecision *
  36913. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  36914. direction);
  36915. }
  36916. previousMultiTouchPanPosition.isPaning = false;
  36917. previousMultiTouchPanPosition.isPinching = true;
  36918. }
  36919. else {
  36920. if (cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  36921. if (!previousMultiTouchPanPosition.isPaning) {
  36922. previousMultiTouchPanPosition.isPaning = true;
  36923. previousMultiTouchPanPosition.isPinching = false;
  36924. previousMultiTouchPanPosition.x = ed.x;
  36925. previousMultiTouchPanPosition.y = ed.y;
  36926. return;
  36927. }
  36928. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  36929. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  36930. }
  36931. }
  36932. if (cacheSoloPointer.pointerId === evt.pointerId) {
  36933. previousMultiTouchPanPosition.x = ed.x;
  36934. previousMultiTouchPanPosition.y = ed.y;
  36935. }
  36936. }
  36937. previousPinchSquaredDistance = pinchSquaredDistance;
  36938. }
  36939. }
  36940. };
  36941. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  36942. this._onContextMenu = function (evt) {
  36943. evt.preventDefault();
  36944. };
  36945. if (!this.camera._useCtrlForPanning) {
  36946. element.addEventListener("contextmenu", this._onContextMenu, false);
  36947. }
  36948. this._onLostFocus = function () {
  36949. //this._keys = [];
  36950. pointA = pointB = undefined;
  36951. previousPinchSquaredDistance = 0;
  36952. previousMultiTouchPanPosition.isPaning = false;
  36953. previousMultiTouchPanPosition.isPinching = false;
  36954. twoFingerActivityCount = 0;
  36955. cacheSoloPointer = null;
  36956. initialDistance = 0;
  36957. };
  36958. this._onMouseMove = function (evt) {
  36959. if (!engine.isPointerLock) {
  36960. return;
  36961. }
  36962. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  36963. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  36964. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  36965. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  36966. if (!noPreventDefault) {
  36967. evt.preventDefault();
  36968. }
  36969. };
  36970. this._onGestureStart = function (e) {
  36971. if (window.MSGesture === undefined) {
  36972. return;
  36973. }
  36974. if (!_this._MSGestureHandler) {
  36975. _this._MSGestureHandler = new MSGesture();
  36976. _this._MSGestureHandler.target = element;
  36977. }
  36978. _this._MSGestureHandler.addPointer(e.pointerId);
  36979. };
  36980. this._onGesture = function (e) {
  36981. _this.camera.radius *= e.scale;
  36982. if (e.preventDefault) {
  36983. if (!noPreventDefault) {
  36984. e.stopPropagation();
  36985. e.preventDefault();
  36986. }
  36987. }
  36988. };
  36989. element.addEventListener("mousemove", this._onMouseMove, false);
  36990. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  36991. element.addEventListener("MSGestureChange", this._onGesture, false);
  36992. BABYLON.Tools.RegisterTopRootEvents([
  36993. { name: "blur", handler: this._onLostFocus }
  36994. ]);
  36995. };
  36996. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  36997. BABYLON.Tools.UnregisterTopRootEvents([
  36998. { name: "blur", handler: this._onLostFocus }
  36999. ]);
  37000. if (element && this._observer) {
  37001. this.camera.getScene().onPointerObservable.remove(this._observer);
  37002. this._observer = null;
  37003. element.removeEventListener("contextmenu", this._onContextMenu);
  37004. element.removeEventListener("mousemove", this._onMouseMove);
  37005. element.removeEventListener("MSPointerDown", this._onGestureStart);
  37006. element.removeEventListener("MSGestureChange", this._onGesture);
  37007. this._isPanClick = false;
  37008. this.pinchInwards = true;
  37009. this._onMouseMove = null;
  37010. this._onGestureStart = null;
  37011. this._onGesture = null;
  37012. this._MSGestureHandler = null;
  37013. this._onLostFocus = null;
  37014. this._onContextMenu = null;
  37015. }
  37016. };
  37017. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  37018. return "ArcRotateCameraPointersInput";
  37019. };
  37020. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  37021. return "pointers";
  37022. };
  37023. __decorate([
  37024. BABYLON.serialize()
  37025. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  37026. __decorate([
  37027. BABYLON.serialize()
  37028. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  37029. __decorate([
  37030. BABYLON.serialize()
  37031. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  37032. __decorate([
  37033. BABYLON.serialize()
  37034. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  37035. __decorate([
  37036. BABYLON.serialize()
  37037. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  37038. __decorate([
  37039. BABYLON.serialize()
  37040. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  37041. __decorate([
  37042. BABYLON.serialize()
  37043. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  37044. __decorate([
  37045. BABYLON.serialize()
  37046. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  37047. return ArcRotateCameraPointersInput;
  37048. }());
  37049. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  37050. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  37051. })(BABYLON || (BABYLON = {}));
  37052. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  37053. /// <reference path="babylon.targetCamera.ts" />
  37054. /// <reference path="..\Tools\babylon.tools.ts" />
  37055. var BABYLON;
  37056. (function (BABYLON) {
  37057. var ArcRotateCamera = (function (_super) {
  37058. __extends(ArcRotateCamera, _super);
  37059. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  37060. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  37061. _this.inertialAlphaOffset = 0;
  37062. _this.inertialBetaOffset = 0;
  37063. _this.inertialRadiusOffset = 0;
  37064. _this.lowerAlphaLimit = null;
  37065. _this.upperAlphaLimit = null;
  37066. _this.lowerBetaLimit = 0.01;
  37067. _this.upperBetaLimit = Math.PI;
  37068. _this.lowerRadiusLimit = null;
  37069. _this.upperRadiusLimit = null;
  37070. _this.inertialPanningX = 0;
  37071. _this.inertialPanningY = 0;
  37072. _this.pinchToPanMaxDistance = 20;
  37073. _this.panningDistanceLimit = null;
  37074. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  37075. _this.panningInertia = 0.9;
  37076. //-- end properties for backward compatibility for inputs
  37077. _this.zoomOnFactor = 1;
  37078. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  37079. _this.allowUpsideDown = true;
  37080. _this._viewMatrix = new BABYLON.Matrix();
  37081. // Panning
  37082. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  37083. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  37084. _this.checkCollisions = false;
  37085. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  37086. _this._previousPosition = BABYLON.Vector3.Zero();
  37087. _this._collisionVelocity = BABYLON.Vector3.Zero();
  37088. _this._newPosition = BABYLON.Vector3.Zero();
  37089. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  37090. if (collidedMesh === void 0) { collidedMesh = null; }
  37091. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  37092. newPosition.multiplyInPlace(_this._collider.radius);
  37093. }
  37094. if (!collidedMesh) {
  37095. _this._previousPosition.copyFrom(_this.position);
  37096. }
  37097. else {
  37098. _this.setPosition(newPosition);
  37099. if (_this.onCollide) {
  37100. _this.onCollide(collidedMesh);
  37101. }
  37102. }
  37103. // Recompute because of constraints
  37104. var cosa = Math.cos(_this.alpha);
  37105. var sina = Math.sin(_this.alpha);
  37106. var cosb = Math.cos(_this.beta);
  37107. var sinb = Math.sin(_this.beta);
  37108. if (sinb === 0) {
  37109. sinb = 0.0001;
  37110. }
  37111. var target = _this._getTargetPosition();
  37112. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  37113. _this.position.copyFrom(_this._newPosition);
  37114. var up = _this.upVector;
  37115. if (_this.allowUpsideDown && _this.beta < 0) {
  37116. up = up.clone();
  37117. up = up.negate();
  37118. }
  37119. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  37120. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  37121. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  37122. _this._collisionTriggered = false;
  37123. };
  37124. _this._target = BABYLON.Vector3.Zero();
  37125. if (target) {
  37126. _this.setTarget(target);
  37127. }
  37128. _this.alpha = alpha;
  37129. _this.beta = beta;
  37130. _this.radius = radius;
  37131. _this.getViewMatrix();
  37132. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  37133. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  37134. return _this;
  37135. }
  37136. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  37137. get: function () {
  37138. return this._target;
  37139. },
  37140. set: function (value) {
  37141. this.setTarget(value);
  37142. },
  37143. enumerable: true,
  37144. configurable: true
  37145. });
  37146. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  37147. //-- begin properties for backward compatibility for inputs
  37148. get: function () {
  37149. var pointers = this.inputs.attached["pointers"];
  37150. if (pointers)
  37151. return pointers.angularSensibilityX;
  37152. },
  37153. set: function (value) {
  37154. var pointers = this.inputs.attached["pointers"];
  37155. if (pointers) {
  37156. pointers.angularSensibilityX = value;
  37157. }
  37158. },
  37159. enumerable: true,
  37160. configurable: true
  37161. });
  37162. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  37163. get: function () {
  37164. var pointers = this.inputs.attached["pointers"];
  37165. if (pointers)
  37166. return pointers.angularSensibilityY;
  37167. },
  37168. set: function (value) {
  37169. var pointers = this.inputs.attached["pointers"];
  37170. if (pointers) {
  37171. pointers.angularSensibilityY = value;
  37172. }
  37173. },
  37174. enumerable: true,
  37175. configurable: true
  37176. });
  37177. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  37178. get: function () {
  37179. var pointers = this.inputs.attached["pointers"];
  37180. if (pointers)
  37181. return pointers.pinchPrecision;
  37182. },
  37183. set: function (value) {
  37184. var pointers = this.inputs.attached["pointers"];
  37185. if (pointers) {
  37186. pointers.pinchPrecision = value;
  37187. }
  37188. },
  37189. enumerable: true,
  37190. configurable: true
  37191. });
  37192. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  37193. get: function () {
  37194. var pointers = this.inputs.attached["pointers"];
  37195. if (pointers)
  37196. return pointers.pinchDeltaPercentage;
  37197. },
  37198. set: function (value) {
  37199. var pointers = this.inputs.attached["pointers"];
  37200. if (pointers) {
  37201. pointers.pinchDeltaPercentage = value;
  37202. }
  37203. },
  37204. enumerable: true,
  37205. configurable: true
  37206. });
  37207. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  37208. get: function () {
  37209. var pointers = this.inputs.attached["pointers"];
  37210. if (pointers)
  37211. return pointers.panningSensibility;
  37212. },
  37213. set: function (value) {
  37214. var pointers = this.inputs.attached["pointers"];
  37215. if (pointers) {
  37216. pointers.panningSensibility = value;
  37217. }
  37218. },
  37219. enumerable: true,
  37220. configurable: true
  37221. });
  37222. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  37223. get: function () {
  37224. var keyboard = this.inputs.attached["keyboard"];
  37225. if (keyboard)
  37226. return keyboard.keysUp;
  37227. },
  37228. set: function (value) {
  37229. var keyboard = this.inputs.attached["keyboard"];
  37230. if (keyboard)
  37231. keyboard.keysUp = value;
  37232. },
  37233. enumerable: true,
  37234. configurable: true
  37235. });
  37236. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  37237. get: function () {
  37238. var keyboard = this.inputs.attached["keyboard"];
  37239. if (keyboard)
  37240. return keyboard.keysDown;
  37241. },
  37242. set: function (value) {
  37243. var keyboard = this.inputs.attached["keyboard"];
  37244. if (keyboard)
  37245. keyboard.keysDown = value;
  37246. },
  37247. enumerable: true,
  37248. configurable: true
  37249. });
  37250. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  37251. get: function () {
  37252. var keyboard = this.inputs.attached["keyboard"];
  37253. if (keyboard)
  37254. return keyboard.keysLeft;
  37255. },
  37256. set: function (value) {
  37257. var keyboard = this.inputs.attached["keyboard"];
  37258. if (keyboard)
  37259. keyboard.keysLeft = value;
  37260. },
  37261. enumerable: true,
  37262. configurable: true
  37263. });
  37264. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  37265. get: function () {
  37266. var keyboard = this.inputs.attached["keyboard"];
  37267. if (keyboard)
  37268. return keyboard.keysRight;
  37269. },
  37270. set: function (value) {
  37271. var keyboard = this.inputs.attached["keyboard"];
  37272. if (keyboard)
  37273. keyboard.keysRight = value;
  37274. },
  37275. enumerable: true,
  37276. configurable: true
  37277. });
  37278. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  37279. get: function () {
  37280. var mousewheel = this.inputs.attached["mousewheel"];
  37281. if (mousewheel)
  37282. return mousewheel.wheelPrecision;
  37283. },
  37284. set: function (value) {
  37285. var mousewheel = this.inputs.attached["mousewheel"];
  37286. if (mousewheel)
  37287. mousewheel.wheelPrecision = value;
  37288. },
  37289. enumerable: true,
  37290. configurable: true
  37291. });
  37292. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  37293. get: function () {
  37294. var mousewheel = this.inputs.attached["mousewheel"];
  37295. if (mousewheel)
  37296. return mousewheel.wheelDeltaPercentage;
  37297. },
  37298. set: function (value) {
  37299. var mousewheel = this.inputs.attached["mousewheel"];
  37300. if (mousewheel)
  37301. mousewheel.wheelDeltaPercentage = value;
  37302. },
  37303. enumerable: true,
  37304. configurable: true
  37305. });
  37306. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  37307. get: function () {
  37308. return this._bouncingBehavior;
  37309. },
  37310. enumerable: true,
  37311. configurable: true
  37312. });
  37313. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  37314. get: function () {
  37315. return this._bouncingBehavior != null;
  37316. },
  37317. set: function (value) {
  37318. if (value === this.useBouncingBehavior) {
  37319. return;
  37320. }
  37321. if (value) {
  37322. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  37323. this.addBehavior(this._bouncingBehavior);
  37324. }
  37325. else {
  37326. this.removeBehavior(this._bouncingBehavior);
  37327. this._bouncingBehavior = null;
  37328. }
  37329. },
  37330. enumerable: true,
  37331. configurable: true
  37332. });
  37333. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  37334. get: function () {
  37335. return this._framingBehavior;
  37336. },
  37337. enumerable: true,
  37338. configurable: true
  37339. });
  37340. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  37341. get: function () {
  37342. return this._framingBehavior != null;
  37343. },
  37344. set: function (value) {
  37345. if (value === this.useFramingBehavior) {
  37346. return;
  37347. }
  37348. if (value) {
  37349. this._framingBehavior = new BABYLON.FramingBehavior();
  37350. this.addBehavior(this._framingBehavior);
  37351. }
  37352. else {
  37353. this.removeBehavior(this._framingBehavior);
  37354. this._framingBehavior = null;
  37355. }
  37356. },
  37357. enumerable: true,
  37358. configurable: true
  37359. });
  37360. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  37361. get: function () {
  37362. return this._autoRotationBehavior;
  37363. },
  37364. enumerable: true,
  37365. configurable: true
  37366. });
  37367. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  37368. get: function () {
  37369. return this._autoRotationBehavior != null;
  37370. },
  37371. set: function (value) {
  37372. if (value === this.useAutoRotationBehavior) {
  37373. return;
  37374. }
  37375. if (value) {
  37376. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  37377. this.addBehavior(this._autoRotationBehavior);
  37378. }
  37379. else {
  37380. this.removeBehavior(this._autoRotationBehavior);
  37381. this._autoRotationBehavior = null;
  37382. }
  37383. },
  37384. enumerable: true,
  37385. configurable: true
  37386. });
  37387. // Cache
  37388. ArcRotateCamera.prototype._initCache = function () {
  37389. _super.prototype._initCache.call(this);
  37390. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37391. this._cache.alpha = undefined;
  37392. this._cache.beta = undefined;
  37393. this._cache.radius = undefined;
  37394. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  37395. };
  37396. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  37397. if (!ignoreParentClass) {
  37398. _super.prototype._updateCache.call(this);
  37399. }
  37400. this._cache._target.copyFrom(this._getTargetPosition());
  37401. this._cache.alpha = this.alpha;
  37402. this._cache.beta = this.beta;
  37403. this._cache.radius = this.radius;
  37404. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  37405. };
  37406. ArcRotateCamera.prototype._getTargetPosition = function () {
  37407. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  37408. var pos = this._targetHost.getAbsolutePosition();
  37409. if (this._targetBoundingCenter) {
  37410. pos.addToRef(this._targetBoundingCenter, this._target);
  37411. }
  37412. else {
  37413. this._target.copyFrom(pos);
  37414. }
  37415. }
  37416. var lockedTargetPosition = this._getLockedTargetPosition();
  37417. if (lockedTargetPosition) {
  37418. return lockedTargetPosition;
  37419. }
  37420. return this._target;
  37421. };
  37422. ArcRotateCamera.prototype.storeState = function () {
  37423. this._storedAlpha = this.alpha;
  37424. this._storedBeta = this.beta;
  37425. this._storedRadius = this.radius;
  37426. this._storedTarget = this._getTargetPosition().clone();
  37427. return _super.prototype.storeState.call(this);
  37428. };
  37429. /**
  37430. * Restored camera state. You must call storeState() first
  37431. */
  37432. ArcRotateCamera.prototype._restoreStateValues = function () {
  37433. if (!_super.prototype._restoreStateValues.call(this)) {
  37434. return false;
  37435. }
  37436. this.alpha = this._storedAlpha;
  37437. this.beta = this._storedBeta;
  37438. this.radius = this._storedRadius;
  37439. this.setTarget(this._storedTarget.clone());
  37440. this.inertialAlphaOffset = 0;
  37441. this.inertialBetaOffset = 0;
  37442. this.inertialRadiusOffset = 0;
  37443. this.inertialPanningX = 0;
  37444. this.inertialPanningY = 0;
  37445. return true;
  37446. };
  37447. // Synchronized
  37448. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  37449. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  37450. return false;
  37451. return this._cache._target.equals(this._getTargetPosition())
  37452. && this._cache.alpha === this.alpha
  37453. && this._cache.beta === this.beta
  37454. && this._cache.radius === this.radius
  37455. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  37456. };
  37457. // Methods
  37458. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  37459. var _this = this;
  37460. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  37461. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  37462. this._useCtrlForPanning = useCtrlForPanning;
  37463. this._panningMouseButton = panningMouseButton;
  37464. this.inputs.attachElement(element, noPreventDefault);
  37465. this._reset = function () {
  37466. _this.inertialAlphaOffset = 0;
  37467. _this.inertialBetaOffset = 0;
  37468. _this.inertialRadiusOffset = 0;
  37469. _this.inertialPanningX = 0;
  37470. _this.inertialPanningY = 0;
  37471. };
  37472. };
  37473. ArcRotateCamera.prototype.detachControl = function (element) {
  37474. this.inputs.detachElement(element);
  37475. if (this._reset) {
  37476. this._reset();
  37477. }
  37478. };
  37479. ArcRotateCamera.prototype._checkInputs = function () {
  37480. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  37481. if (this._collisionTriggered) {
  37482. return;
  37483. }
  37484. this.inputs.checkInputs();
  37485. // Inertia
  37486. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  37487. if (this.getScene().useRightHandedSystem) {
  37488. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  37489. }
  37490. else {
  37491. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  37492. }
  37493. this.beta += this.inertialBetaOffset;
  37494. this.radius -= this.inertialRadiusOffset;
  37495. this.inertialAlphaOffset *= this.inertia;
  37496. this.inertialBetaOffset *= this.inertia;
  37497. this.inertialRadiusOffset *= this.inertia;
  37498. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  37499. this.inertialAlphaOffset = 0;
  37500. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  37501. this.inertialBetaOffset = 0;
  37502. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  37503. this.inertialRadiusOffset = 0;
  37504. }
  37505. // Panning inertia
  37506. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  37507. if (!this._localDirection) {
  37508. this._localDirection = BABYLON.Vector3.Zero();
  37509. this._transformedDirection = BABYLON.Vector3.Zero();
  37510. }
  37511. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  37512. this._localDirection.multiplyInPlace(this.panningAxis);
  37513. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  37514. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  37515. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  37516. if (!this.panningAxis.y) {
  37517. this._transformedDirection.y = 0;
  37518. }
  37519. if (!this._targetHost) {
  37520. if (this.panningDistanceLimit) {
  37521. this._transformedDirection.addInPlace(this._target);
  37522. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  37523. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  37524. this._target.copyFrom(this._transformedDirection);
  37525. }
  37526. }
  37527. else {
  37528. this._target.addInPlace(this._transformedDirection);
  37529. }
  37530. }
  37531. this.inertialPanningX *= this.panningInertia;
  37532. this.inertialPanningY *= this.panningInertia;
  37533. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  37534. this.inertialPanningX = 0;
  37535. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  37536. this.inertialPanningY = 0;
  37537. }
  37538. // Limits
  37539. this._checkLimits();
  37540. _super.prototype._checkInputs.call(this);
  37541. };
  37542. ArcRotateCamera.prototype._checkLimits = function () {
  37543. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  37544. if (this.allowUpsideDown && this.beta > Math.PI) {
  37545. this.beta = this.beta - (2 * Math.PI);
  37546. }
  37547. }
  37548. else {
  37549. if (this.beta < this.lowerBetaLimit) {
  37550. this.beta = this.lowerBetaLimit;
  37551. }
  37552. }
  37553. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  37554. if (this.allowUpsideDown && this.beta < -Math.PI) {
  37555. this.beta = this.beta + (2 * Math.PI);
  37556. }
  37557. }
  37558. else {
  37559. if (this.beta > this.upperBetaLimit) {
  37560. this.beta = this.upperBetaLimit;
  37561. }
  37562. }
  37563. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  37564. this.alpha = this.lowerAlphaLimit;
  37565. }
  37566. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  37567. this.alpha = this.upperAlphaLimit;
  37568. }
  37569. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  37570. this.radius = this.lowerRadiusLimit;
  37571. }
  37572. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  37573. this.radius = this.upperRadiusLimit;
  37574. }
  37575. };
  37576. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  37577. var radiusv3 = this.position.subtract(this._getTargetPosition());
  37578. this.radius = radiusv3.length();
  37579. if (this.radius === 0) {
  37580. this.radius = 0.0001; // Just to avoid division by zero
  37581. }
  37582. // Alpha
  37583. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  37584. if (radiusv3.z < 0) {
  37585. this.alpha = 2 * Math.PI - this.alpha;
  37586. }
  37587. // Beta
  37588. this.beta = Math.acos(radiusv3.y / this.radius);
  37589. this._checkLimits();
  37590. };
  37591. ArcRotateCamera.prototype.setPosition = function (position) {
  37592. if (this.position.equals(position)) {
  37593. return;
  37594. }
  37595. this.position.copyFrom(position);
  37596. this.rebuildAnglesAndRadius();
  37597. };
  37598. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  37599. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  37600. if (allowSamePosition === void 0) { allowSamePosition = false; }
  37601. if (target.getBoundingInfo) {
  37602. if (toBoundingCenter) {
  37603. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  37604. }
  37605. else {
  37606. this._targetBoundingCenter = null;
  37607. }
  37608. this._targetHost = target;
  37609. this._target = this._getTargetPosition();
  37610. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  37611. }
  37612. else {
  37613. var newTarget = target;
  37614. var currentTarget = this._getTargetPosition();
  37615. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  37616. return;
  37617. }
  37618. this._targetHost = null;
  37619. this._target = newTarget;
  37620. this._targetBoundingCenter = null;
  37621. this.onMeshTargetChangedObservable.notifyObservers(null);
  37622. }
  37623. this.rebuildAnglesAndRadius();
  37624. };
  37625. ArcRotateCamera.prototype._getViewMatrix = function () {
  37626. // Compute
  37627. var cosa = Math.cos(this.alpha);
  37628. var sina = Math.sin(this.alpha);
  37629. var cosb = Math.cos(this.beta);
  37630. var sinb = Math.sin(this.beta);
  37631. if (sinb === 0) {
  37632. sinb = 0.0001;
  37633. }
  37634. var target = this._getTargetPosition();
  37635. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  37636. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  37637. if (!this._collider) {
  37638. this._collider = new BABYLON.Collider();
  37639. }
  37640. this._collider.radius = this.collisionRadius;
  37641. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  37642. this._collisionTriggered = true;
  37643. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  37644. }
  37645. else {
  37646. this.position.copyFrom(this._newPosition);
  37647. var up = this.upVector;
  37648. if (this.allowUpsideDown && sinb < 0) {
  37649. up = up.clone();
  37650. up = up.negate();
  37651. }
  37652. if (this.getScene().useRightHandedSystem) {
  37653. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  37654. }
  37655. else {
  37656. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  37657. }
  37658. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  37659. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  37660. }
  37661. this._currentTarget = target;
  37662. return this._viewMatrix;
  37663. };
  37664. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  37665. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  37666. meshes = meshes || this.getScene().meshes;
  37667. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  37668. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  37669. this.radius = distance * this.zoomOnFactor;
  37670. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  37671. };
  37672. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  37673. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  37674. var meshesOrMinMaxVector;
  37675. var distance;
  37676. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  37677. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  37678. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  37679. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  37680. }
  37681. else {
  37682. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  37683. meshesOrMinMaxVector = minMaxVectorAndDistance;
  37684. distance = minMaxVectorAndDistance.distance;
  37685. }
  37686. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  37687. if (!doNotUpdateMaxZ) {
  37688. this.maxZ = distance * 2;
  37689. }
  37690. };
  37691. /**
  37692. * @override
  37693. * Override Camera.createRigCamera
  37694. */
  37695. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  37696. var alphaShift;
  37697. switch (this.cameraRigMode) {
  37698. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  37699. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  37700. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  37701. case BABYLON.Camera.RIG_MODE_VR:
  37702. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  37703. break;
  37704. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  37705. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  37706. break;
  37707. }
  37708. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  37709. rigCam._cameraRigParams = {};
  37710. return rigCam;
  37711. };
  37712. /**
  37713. * @override
  37714. * Override Camera._updateRigCameras
  37715. */
  37716. ArcRotateCamera.prototype._updateRigCameras = function () {
  37717. var camLeft = this._rigCameras[0];
  37718. var camRight = this._rigCameras[1];
  37719. camLeft.beta = camRight.beta = this.beta;
  37720. camLeft.radius = camRight.radius = this.radius;
  37721. switch (this.cameraRigMode) {
  37722. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  37723. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  37724. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  37725. case BABYLON.Camera.RIG_MODE_VR:
  37726. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  37727. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  37728. break;
  37729. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  37730. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  37731. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  37732. break;
  37733. }
  37734. _super.prototype._updateRigCameras.call(this);
  37735. };
  37736. ArcRotateCamera.prototype.dispose = function () {
  37737. this.inputs.clear();
  37738. _super.prototype.dispose.call(this);
  37739. };
  37740. ArcRotateCamera.prototype.getClassName = function () {
  37741. return "ArcRotateCamera";
  37742. };
  37743. __decorate([
  37744. BABYLON.serialize()
  37745. ], ArcRotateCamera.prototype, "alpha", void 0);
  37746. __decorate([
  37747. BABYLON.serialize()
  37748. ], ArcRotateCamera.prototype, "beta", void 0);
  37749. __decorate([
  37750. BABYLON.serialize()
  37751. ], ArcRotateCamera.prototype, "radius", void 0);
  37752. __decorate([
  37753. BABYLON.serializeAsVector3("target")
  37754. ], ArcRotateCamera.prototype, "_target", void 0);
  37755. __decorate([
  37756. BABYLON.serialize()
  37757. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  37758. __decorate([
  37759. BABYLON.serialize()
  37760. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  37761. __decorate([
  37762. BABYLON.serialize()
  37763. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  37764. __decorate([
  37765. BABYLON.serialize()
  37766. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  37767. __decorate([
  37768. BABYLON.serialize()
  37769. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  37770. __decorate([
  37771. BABYLON.serialize()
  37772. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  37773. __decorate([
  37774. BABYLON.serialize()
  37775. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  37776. __decorate([
  37777. BABYLON.serialize()
  37778. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  37779. __decorate([
  37780. BABYLON.serialize()
  37781. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  37782. __decorate([
  37783. BABYLON.serialize()
  37784. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  37785. __decorate([
  37786. BABYLON.serialize()
  37787. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  37788. __decorate([
  37789. BABYLON.serialize()
  37790. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  37791. __decorate([
  37792. BABYLON.serialize()
  37793. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  37794. __decorate([
  37795. BABYLON.serializeAsVector3()
  37796. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  37797. __decorate([
  37798. BABYLON.serialize()
  37799. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  37800. __decorate([
  37801. BABYLON.serialize()
  37802. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  37803. __decorate([
  37804. BABYLON.serialize()
  37805. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  37806. return ArcRotateCamera;
  37807. }(BABYLON.TargetCamera));
  37808. BABYLON.ArcRotateCamera = ArcRotateCamera;
  37809. })(BABYLON || (BABYLON = {}));
  37810. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  37811. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  37812. var BABYLON;
  37813. (function (BABYLON) {
  37814. var ArcRotateCameraInputsManager = (function (_super) {
  37815. __extends(ArcRotateCameraInputsManager, _super);
  37816. function ArcRotateCameraInputsManager(camera) {
  37817. return _super.call(this, camera) || this;
  37818. }
  37819. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  37820. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  37821. return this;
  37822. };
  37823. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  37824. this.add(new BABYLON.ArcRotateCameraPointersInput());
  37825. return this;
  37826. };
  37827. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  37828. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  37829. return this;
  37830. };
  37831. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  37832. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  37833. return this;
  37834. };
  37835. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  37836. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  37837. return this;
  37838. };
  37839. return ArcRotateCameraInputsManager;
  37840. }(BABYLON.CameraInputsManager));
  37841. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  37842. })(BABYLON || (BABYLON = {}));
  37843. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  37844. var BABYLON;
  37845. (function (BABYLON) {
  37846. var HemisphericLight = (function (_super) {
  37847. __extends(HemisphericLight, _super);
  37848. /**
  37849. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  37850. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  37851. * The HemisphericLight can't cast shadows.
  37852. * Documentation : http://doc.babylonjs.com/tutorials/lights
  37853. */
  37854. function HemisphericLight(name, direction, scene) {
  37855. var _this = _super.call(this, name, scene) || this;
  37856. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  37857. _this.direction = direction || BABYLON.Vector3.Up();
  37858. return _this;
  37859. }
  37860. HemisphericLight.prototype._buildUniformLayout = function () {
  37861. this._uniformBuffer.addUniform("vLightData", 4);
  37862. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  37863. this._uniformBuffer.addUniform("vLightSpecular", 3);
  37864. this._uniformBuffer.addUniform("vLightGround", 3);
  37865. this._uniformBuffer.addUniform("shadowsInfo", 3);
  37866. this._uniformBuffer.addUniform("depthValues", 2);
  37867. this._uniformBuffer.create();
  37868. };
  37869. /**
  37870. * Returns the string "HemisphericLight".
  37871. */
  37872. HemisphericLight.prototype.getClassName = function () {
  37873. return "HemisphericLight";
  37874. };
  37875. /**
  37876. * Sets the HemisphericLight direction towards the passed target (Vector3).
  37877. * Returns the updated direction.
  37878. */
  37879. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  37880. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  37881. return this.direction;
  37882. };
  37883. HemisphericLight.prototype.getShadowGenerator = function () {
  37884. return null;
  37885. };
  37886. /**
  37887. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  37888. * Returns the HemisphericLight.
  37889. */
  37890. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  37891. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  37892. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  37893. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  37894. return this;
  37895. };
  37896. HemisphericLight.prototype._getWorldMatrix = function () {
  37897. if (!this._worldMatrix) {
  37898. this._worldMatrix = BABYLON.Matrix.Identity();
  37899. }
  37900. return this._worldMatrix;
  37901. };
  37902. /**
  37903. * Returns the integer 3.
  37904. */
  37905. HemisphericLight.prototype.getTypeID = function () {
  37906. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  37907. };
  37908. __decorate([
  37909. BABYLON.serializeAsColor3()
  37910. ], HemisphericLight.prototype, "groundColor", void 0);
  37911. __decorate([
  37912. BABYLON.serializeAsVector3()
  37913. ], HemisphericLight.prototype, "direction", void 0);
  37914. return HemisphericLight;
  37915. }(BABYLON.Light));
  37916. BABYLON.HemisphericLight = HemisphericLight;
  37917. })(BABYLON || (BABYLON = {}));
  37918. //# sourceMappingURL=babylon.hemisphericLight.js.map
  37919. var BABYLON;
  37920. (function (BABYLON) {
  37921. var ShadowLight = (function (_super) {
  37922. __extends(ShadowLight, _super);
  37923. function ShadowLight() {
  37924. var _this = _super !== null && _super.apply(this, arguments) || this;
  37925. _this._needProjectionMatrixCompute = true;
  37926. return _this;
  37927. }
  37928. Object.defineProperty(ShadowLight.prototype, "direction", {
  37929. get: function () {
  37930. return this._direction;
  37931. },
  37932. set: function (value) {
  37933. this._direction = value;
  37934. },
  37935. enumerable: true,
  37936. configurable: true
  37937. });
  37938. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  37939. get: function () {
  37940. return this._shadowMinZ;
  37941. },
  37942. set: function (value) {
  37943. this._shadowMinZ = value;
  37944. this.forceProjectionMatrixCompute();
  37945. },
  37946. enumerable: true,
  37947. configurable: true
  37948. });
  37949. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  37950. get: function () {
  37951. return this._shadowMaxZ;
  37952. },
  37953. set: function (value) {
  37954. this._shadowMaxZ = value;
  37955. this.forceProjectionMatrixCompute();
  37956. },
  37957. enumerable: true,
  37958. configurable: true
  37959. });
  37960. /**
  37961. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  37962. */
  37963. ShadowLight.prototype.computeTransformedInformation = function () {
  37964. if (this.parent && this.parent.getWorldMatrix) {
  37965. if (!this.transformedPosition) {
  37966. this.transformedPosition = BABYLON.Vector3.Zero();
  37967. }
  37968. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  37969. // In case the direction is present.
  37970. if (this.direction) {
  37971. if (!this.transformedDirection) {
  37972. this.transformedDirection = BABYLON.Vector3.Zero();
  37973. }
  37974. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  37975. }
  37976. return true;
  37977. }
  37978. return false;
  37979. };
  37980. /**
  37981. * Return the depth scale used for the shadow map.
  37982. */
  37983. ShadowLight.prototype.getDepthScale = function () {
  37984. return 50.0;
  37985. };
  37986. /**
  37987. * Returns the light direction (Vector3) for any passed face index.
  37988. */
  37989. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  37990. return this.transformedDirection ? this.transformedDirection : this.direction;
  37991. };
  37992. /**
  37993. * Returns the DirectionalLight absolute position in the World.
  37994. */
  37995. ShadowLight.prototype.getAbsolutePosition = function () {
  37996. return this.transformedPosition ? this.transformedPosition : this.position;
  37997. };
  37998. /**
  37999. * Sets the DirectionalLight direction toward the passed target (Vector3).
  38000. * Returns the updated DirectionalLight direction (Vector3).
  38001. */
  38002. ShadowLight.prototype.setDirectionToTarget = function (target) {
  38003. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  38004. return this.direction;
  38005. };
  38006. /**
  38007. * Returns the light rotation (Vector3).
  38008. */
  38009. ShadowLight.prototype.getRotation = function () {
  38010. this.direction.normalize();
  38011. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  38012. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  38013. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  38014. };
  38015. /**
  38016. * Boolean : false by default.
  38017. */
  38018. ShadowLight.prototype.needCube = function () {
  38019. return false;
  38020. };
  38021. /**
  38022. * Specifies wether or not the projection matrix should be recomputed this frame.
  38023. */
  38024. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  38025. return this._needProjectionMatrixCompute;
  38026. };
  38027. /**
  38028. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  38029. */
  38030. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  38031. this._needProjectionMatrixCompute = true;
  38032. };
  38033. /**
  38034. * Get the world matrix of the sahdow lights.
  38035. */
  38036. ShadowLight.prototype._getWorldMatrix = function () {
  38037. if (!this._worldMatrix) {
  38038. this._worldMatrix = BABYLON.Matrix.Identity();
  38039. }
  38040. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  38041. return this._worldMatrix;
  38042. };
  38043. /**
  38044. * Gets the minZ used for shadow according to both the scene and the light.
  38045. * @param activeCamera
  38046. */
  38047. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  38048. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  38049. };
  38050. /**
  38051. * Gets the maxZ used for shadow according to both the scene and the light.
  38052. * @param activeCamera
  38053. */
  38054. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  38055. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  38056. };
  38057. /**
  38058. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  38059. * Returns the light.
  38060. */
  38061. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  38062. if (this.customProjectionMatrixBuilder) {
  38063. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  38064. }
  38065. else {
  38066. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  38067. }
  38068. return this;
  38069. };
  38070. __decorate([
  38071. BABYLON.serializeAsVector3()
  38072. ], ShadowLight.prototype, "position", void 0);
  38073. __decorate([
  38074. BABYLON.serializeAsVector3()
  38075. ], ShadowLight.prototype, "direction", null);
  38076. __decorate([
  38077. BABYLON.serialize()
  38078. ], ShadowLight.prototype, "shadowMinZ", null);
  38079. __decorate([
  38080. BABYLON.serialize()
  38081. ], ShadowLight.prototype, "shadowMaxZ", null);
  38082. return ShadowLight;
  38083. }(BABYLON.Light));
  38084. BABYLON.ShadowLight = ShadowLight;
  38085. })(BABYLON || (BABYLON = {}));
  38086. //# sourceMappingURL=babylon.shadowLight.js.map
  38087. var BABYLON;
  38088. (function (BABYLON) {
  38089. var PointLight = (function (_super) {
  38090. __extends(PointLight, _super);
  38091. /**
  38092. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  38093. * A PointLight emits the light in every direction.
  38094. * It can cast shadows.
  38095. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  38096. * ```javascript
  38097. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  38098. * ```
  38099. * Documentation : http://doc.babylonjs.com/tutorials/lights
  38100. */
  38101. function PointLight(name, position, scene) {
  38102. var _this = _super.call(this, name, scene) || this;
  38103. _this._shadowAngle = Math.PI / 2;
  38104. _this.position = position;
  38105. return _this;
  38106. }
  38107. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  38108. /**
  38109. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  38110. * This specifies what angle the shadow will use to be created.
  38111. *
  38112. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  38113. */
  38114. get: function () {
  38115. return this._shadowAngle;
  38116. },
  38117. /**
  38118. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  38119. * This specifies what angle the shadow will use to be created.
  38120. *
  38121. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  38122. */
  38123. set: function (value) {
  38124. this._shadowAngle = value;
  38125. this.forceProjectionMatrixCompute();
  38126. },
  38127. enumerable: true,
  38128. configurable: true
  38129. });
  38130. Object.defineProperty(PointLight.prototype, "direction", {
  38131. get: function () {
  38132. return this._direction;
  38133. },
  38134. /**
  38135. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  38136. */
  38137. set: function (value) {
  38138. var previousNeedCube = this.needCube();
  38139. this._direction = value;
  38140. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  38141. this._shadowGenerator.recreateShadowMap();
  38142. }
  38143. },
  38144. enumerable: true,
  38145. configurable: true
  38146. });
  38147. /**
  38148. * Returns the string "PointLight"
  38149. */
  38150. PointLight.prototype.getClassName = function () {
  38151. return "PointLight";
  38152. };
  38153. /**
  38154. * Returns the integer 0.
  38155. */
  38156. PointLight.prototype.getTypeID = function () {
  38157. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  38158. };
  38159. /**
  38160. * Specifies wether or not the shadowmap should be a cube texture.
  38161. */
  38162. PointLight.prototype.needCube = function () {
  38163. return !this.direction;
  38164. };
  38165. /**
  38166. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  38167. */
  38168. PointLight.prototype.getShadowDirection = function (faceIndex) {
  38169. if (this.direction) {
  38170. return _super.prototype.getShadowDirection.call(this, faceIndex);
  38171. }
  38172. else {
  38173. switch (faceIndex) {
  38174. case 0:
  38175. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  38176. case 1:
  38177. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  38178. case 2:
  38179. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  38180. case 3:
  38181. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  38182. case 4:
  38183. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  38184. case 5:
  38185. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  38186. }
  38187. }
  38188. return BABYLON.Vector3.Zero();
  38189. };
  38190. /**
  38191. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  38192. * - fov = PI / 2
  38193. * - aspect ratio : 1.0
  38194. * - z-near and far equal to the active camera minZ and maxZ.
  38195. * Returns the PointLight.
  38196. */
  38197. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  38198. var activeCamera = this.getScene().activeCamera;
  38199. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  38200. };
  38201. PointLight.prototype._buildUniformLayout = function () {
  38202. this._uniformBuffer.addUniform("vLightData", 4);
  38203. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  38204. this._uniformBuffer.addUniform("vLightSpecular", 3);
  38205. this._uniformBuffer.addUniform("shadowsInfo", 3);
  38206. this._uniformBuffer.addUniform("depthValues", 2);
  38207. this._uniformBuffer.create();
  38208. };
  38209. /**
  38210. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  38211. * Returns the PointLight.
  38212. */
  38213. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  38214. if (this.computeTransformedInformation()) {
  38215. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  38216. return this;
  38217. }
  38218. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  38219. return this;
  38220. };
  38221. __decorate([
  38222. BABYLON.serialize()
  38223. ], PointLight.prototype, "shadowAngle", null);
  38224. return PointLight;
  38225. }(BABYLON.ShadowLight));
  38226. BABYLON.PointLight = PointLight;
  38227. })(BABYLON || (BABYLON = {}));
  38228. //# sourceMappingURL=babylon.pointLight.js.map
  38229. /// <reference path="babylon.light.ts" />
  38230. var BABYLON;
  38231. (function (BABYLON) {
  38232. var DirectionalLight = (function (_super) {
  38233. __extends(DirectionalLight, _super);
  38234. /**
  38235. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  38236. * The directional light is emitted from everywhere in the given direction.
  38237. * It can cast shawdows.
  38238. * Documentation : http://doc.babylonjs.com/tutorials/lights
  38239. */
  38240. function DirectionalLight(name, direction, scene) {
  38241. var _this = _super.call(this, name, scene) || this;
  38242. _this._shadowFrustumSize = 0;
  38243. _this._shadowOrthoScale = 0.5;
  38244. _this.autoUpdateExtends = true;
  38245. // Cache
  38246. _this._orthoLeft = Number.MAX_VALUE;
  38247. _this._orthoRight = Number.MIN_VALUE;
  38248. _this._orthoTop = Number.MIN_VALUE;
  38249. _this._orthoBottom = Number.MAX_VALUE;
  38250. _this.position = direction.scale(-1.0);
  38251. _this.direction = direction;
  38252. return _this;
  38253. }
  38254. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  38255. /**
  38256. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  38257. */
  38258. get: function () {
  38259. return this._shadowFrustumSize;
  38260. },
  38261. /**
  38262. * Specifies a fix frustum size for the shadow generation.
  38263. */
  38264. set: function (value) {
  38265. this._shadowFrustumSize = value;
  38266. this.forceProjectionMatrixCompute();
  38267. },
  38268. enumerable: true,
  38269. configurable: true
  38270. });
  38271. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  38272. get: function () {
  38273. return this._shadowOrthoScale;
  38274. },
  38275. set: function (value) {
  38276. this._shadowOrthoScale = value;
  38277. this.forceProjectionMatrixCompute();
  38278. },
  38279. enumerable: true,
  38280. configurable: true
  38281. });
  38282. /**
  38283. * Returns the string "DirectionalLight".
  38284. */
  38285. DirectionalLight.prototype.getClassName = function () {
  38286. return "DirectionalLight";
  38287. };
  38288. /**
  38289. * Returns the integer 1.
  38290. */
  38291. DirectionalLight.prototype.getTypeID = function () {
  38292. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  38293. };
  38294. /**
  38295. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  38296. * Returns the DirectionalLight Shadow projection matrix.
  38297. */
  38298. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  38299. if (this.shadowFrustumSize > 0) {
  38300. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  38301. }
  38302. else {
  38303. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  38304. }
  38305. };
  38306. /**
  38307. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  38308. * Returns the DirectionalLight Shadow projection matrix.
  38309. */
  38310. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  38311. var activeCamera = this.getScene().activeCamera;
  38312. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  38313. };
  38314. /**
  38315. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  38316. * Returns the DirectionalLight Shadow projection matrix.
  38317. */
  38318. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  38319. var activeCamera = this.getScene().activeCamera;
  38320. // Check extends
  38321. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  38322. var tempVector3 = BABYLON.Vector3.Zero();
  38323. this._orthoLeft = Number.MAX_VALUE;
  38324. this._orthoRight = Number.MIN_VALUE;
  38325. this._orthoTop = Number.MIN_VALUE;
  38326. this._orthoBottom = Number.MAX_VALUE;
  38327. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  38328. var mesh = renderList[meshIndex];
  38329. if (!mesh) {
  38330. continue;
  38331. }
  38332. var boundingInfo = mesh.getBoundingInfo();
  38333. if (!boundingInfo) {
  38334. continue;
  38335. }
  38336. var boundingBox = boundingInfo.boundingBox;
  38337. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  38338. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  38339. if (tempVector3.x < this._orthoLeft)
  38340. this._orthoLeft = tempVector3.x;
  38341. if (tempVector3.y < this._orthoBottom)
  38342. this._orthoBottom = tempVector3.y;
  38343. if (tempVector3.x > this._orthoRight)
  38344. this._orthoRight = tempVector3.x;
  38345. if (tempVector3.y > this._orthoTop)
  38346. this._orthoTop = tempVector3.y;
  38347. }
  38348. }
  38349. }
  38350. var xOffset = this._orthoRight - this._orthoLeft;
  38351. var yOffset = this._orthoTop - this._orthoBottom;
  38352. 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);
  38353. };
  38354. DirectionalLight.prototype._buildUniformLayout = function () {
  38355. this._uniformBuffer.addUniform("vLightData", 4);
  38356. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  38357. this._uniformBuffer.addUniform("vLightSpecular", 3);
  38358. this._uniformBuffer.addUniform("shadowsInfo", 3);
  38359. this._uniformBuffer.addUniform("depthValues", 2);
  38360. this._uniformBuffer.create();
  38361. };
  38362. /**
  38363. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  38364. * Returns the DirectionalLight.
  38365. */
  38366. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  38367. if (this.computeTransformedInformation()) {
  38368. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  38369. return this;
  38370. }
  38371. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  38372. return this;
  38373. };
  38374. /**
  38375. * Gets the minZ used for shadow according to both the scene and the light.
  38376. *
  38377. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  38378. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  38379. * @param activeCamera
  38380. */
  38381. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  38382. return 1;
  38383. };
  38384. /**
  38385. * Gets the maxZ used for shadow according to both the scene and the light.
  38386. *
  38387. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  38388. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  38389. * @param activeCamera
  38390. */
  38391. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  38392. return 1;
  38393. };
  38394. __decorate([
  38395. BABYLON.serialize()
  38396. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  38397. __decorate([
  38398. BABYLON.serialize()
  38399. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  38400. __decorate([
  38401. BABYLON.serialize()
  38402. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  38403. return DirectionalLight;
  38404. }(BABYLON.ShadowLight));
  38405. BABYLON.DirectionalLight = DirectionalLight;
  38406. })(BABYLON || (BABYLON = {}));
  38407. //# sourceMappingURL=babylon.directionalLight.js.map
  38408. var BABYLON;
  38409. (function (BABYLON) {
  38410. var SpotLight = (function (_super) {
  38411. __extends(SpotLight, _super);
  38412. /**
  38413. * Creates a SpotLight object in the scene with the passed parameters :
  38414. * - `position` (Vector3) is the initial SpotLight position,
  38415. * - `direction` (Vector3) is the initial SpotLight direction,
  38416. * - `angle` (float, in radians) is the spot light cone angle,
  38417. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  38418. * A spot light is a simply light oriented cone.
  38419. * It can cast shadows.
  38420. * Documentation : http://doc.babylonjs.com/tutorials/lights
  38421. */
  38422. function SpotLight(name, position, direction, angle, exponent, scene) {
  38423. var _this = _super.call(this, name, scene) || this;
  38424. _this.position = position;
  38425. _this.direction = direction;
  38426. _this.angle = angle;
  38427. _this.exponent = exponent;
  38428. return _this;
  38429. }
  38430. Object.defineProperty(SpotLight.prototype, "angle", {
  38431. get: function () {
  38432. return this._angle;
  38433. },
  38434. set: function (value) {
  38435. this._angle = value;
  38436. this.forceProjectionMatrixCompute();
  38437. },
  38438. enumerable: true,
  38439. configurable: true
  38440. });
  38441. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  38442. get: function () {
  38443. return this._shadowAngleScale;
  38444. },
  38445. /**
  38446. * Allows scaling the angle of the light for shadow generation only.
  38447. */
  38448. set: function (value) {
  38449. this._shadowAngleScale = value;
  38450. this.forceProjectionMatrixCompute();
  38451. },
  38452. enumerable: true,
  38453. configurable: true
  38454. });
  38455. /**
  38456. * Returns the string "SpotLight".
  38457. */
  38458. SpotLight.prototype.getClassName = function () {
  38459. return "SpotLight";
  38460. };
  38461. /**
  38462. * Returns the integer 2.
  38463. */
  38464. SpotLight.prototype.getTypeID = function () {
  38465. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  38466. };
  38467. /**
  38468. * 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.
  38469. * Returns the SpotLight.
  38470. */
  38471. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  38472. var activeCamera = this.getScene().activeCamera;
  38473. this._shadowAngleScale = this._shadowAngleScale || 1;
  38474. var angle = this._shadowAngleScale * this._angle;
  38475. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  38476. };
  38477. SpotLight.prototype._buildUniformLayout = function () {
  38478. this._uniformBuffer.addUniform("vLightData", 4);
  38479. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  38480. this._uniformBuffer.addUniform("vLightSpecular", 3);
  38481. this._uniformBuffer.addUniform("vLightDirection", 3);
  38482. this._uniformBuffer.addUniform("shadowsInfo", 3);
  38483. this._uniformBuffer.addUniform("depthValues", 2);
  38484. this._uniformBuffer.create();
  38485. };
  38486. /**
  38487. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  38488. * Return the SpotLight.
  38489. */
  38490. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  38491. var normalizeDirection;
  38492. if (this.computeTransformedInformation()) {
  38493. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  38494. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  38495. }
  38496. else {
  38497. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  38498. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  38499. }
  38500. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  38501. return this;
  38502. };
  38503. __decorate([
  38504. BABYLON.serialize()
  38505. ], SpotLight.prototype, "angle", null);
  38506. __decorate([
  38507. BABYLON.serialize()
  38508. /**
  38509. * Allows scaling the angle of the light for shadow generation only.
  38510. */
  38511. ], SpotLight.prototype, "shadowAngleScale", null);
  38512. __decorate([
  38513. BABYLON.serialize()
  38514. ], SpotLight.prototype, "exponent", void 0);
  38515. return SpotLight;
  38516. }(BABYLON.ShadowLight));
  38517. BABYLON.SpotLight = SpotLight;
  38518. })(BABYLON || (BABYLON = {}));
  38519. //# sourceMappingURL=babylon.spotLight.js.map
  38520. var BABYLON;
  38521. (function (BABYLON) {
  38522. var AnimationRange = (function () {
  38523. function AnimationRange(name, from, to) {
  38524. this.name = name;
  38525. this.from = from;
  38526. this.to = to;
  38527. }
  38528. AnimationRange.prototype.clone = function () {
  38529. return new AnimationRange(this.name, this.from, this.to);
  38530. };
  38531. return AnimationRange;
  38532. }());
  38533. BABYLON.AnimationRange = AnimationRange;
  38534. /**
  38535. * Composed of a frame, and an action function
  38536. */
  38537. var AnimationEvent = (function () {
  38538. function AnimationEvent(frame, action, onlyOnce) {
  38539. this.frame = frame;
  38540. this.action = action;
  38541. this.onlyOnce = onlyOnce;
  38542. this.isDone = false;
  38543. }
  38544. return AnimationEvent;
  38545. }());
  38546. BABYLON.AnimationEvent = AnimationEvent;
  38547. var PathCursor = (function () {
  38548. function PathCursor(path) {
  38549. this.path = path;
  38550. this._onchange = new Array();
  38551. this.value = 0;
  38552. this.animations = new Array();
  38553. }
  38554. PathCursor.prototype.getPoint = function () {
  38555. var point = this.path.getPointAtLengthPosition(this.value);
  38556. return new BABYLON.Vector3(point.x, 0, point.y);
  38557. };
  38558. PathCursor.prototype.moveAhead = function (step) {
  38559. if (step === void 0) { step = 0.002; }
  38560. this.move(step);
  38561. return this;
  38562. };
  38563. PathCursor.prototype.moveBack = function (step) {
  38564. if (step === void 0) { step = 0.002; }
  38565. this.move(-step);
  38566. return this;
  38567. };
  38568. PathCursor.prototype.move = function (step) {
  38569. if (Math.abs(step) > 1) {
  38570. throw "step size should be less than 1.";
  38571. }
  38572. this.value += step;
  38573. this.ensureLimits();
  38574. this.raiseOnChange();
  38575. return this;
  38576. };
  38577. PathCursor.prototype.ensureLimits = function () {
  38578. while (this.value > 1) {
  38579. this.value -= 1;
  38580. }
  38581. while (this.value < 0) {
  38582. this.value += 1;
  38583. }
  38584. return this;
  38585. };
  38586. // used by animation engine
  38587. PathCursor.prototype.markAsDirty = function (propertyName) {
  38588. this.ensureLimits();
  38589. this.raiseOnChange();
  38590. return this;
  38591. };
  38592. PathCursor.prototype.raiseOnChange = function () {
  38593. var _this = this;
  38594. this._onchange.forEach(function (f) { return f(_this); });
  38595. return this;
  38596. };
  38597. PathCursor.prototype.onchange = function (f) {
  38598. this._onchange.push(f);
  38599. return this;
  38600. };
  38601. return PathCursor;
  38602. }());
  38603. BABYLON.PathCursor = PathCursor;
  38604. var Animation = (function () {
  38605. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  38606. this.name = name;
  38607. this.targetProperty = targetProperty;
  38608. this.framePerSecond = framePerSecond;
  38609. this.dataType = dataType;
  38610. this.loopMode = loopMode;
  38611. this.enableBlending = enableBlending;
  38612. this._runtimeAnimations = new Array();
  38613. // The set of event that will be linked to this animation
  38614. this._events = new Array();
  38615. this.blendingSpeed = 0.01;
  38616. this._ranges = {};
  38617. this.targetPropertyPath = targetProperty.split(".");
  38618. this.dataType = dataType;
  38619. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  38620. }
  38621. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  38622. var dataType = undefined;
  38623. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  38624. dataType = Animation.ANIMATIONTYPE_FLOAT;
  38625. }
  38626. else if (from instanceof BABYLON.Quaternion) {
  38627. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  38628. }
  38629. else if (from instanceof BABYLON.Vector3) {
  38630. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  38631. }
  38632. else if (from instanceof BABYLON.Vector2) {
  38633. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  38634. }
  38635. else if (from instanceof BABYLON.Color3) {
  38636. dataType = Animation.ANIMATIONTYPE_COLOR3;
  38637. }
  38638. else if (from instanceof BABYLON.Size) {
  38639. dataType = Animation.ANIMATIONTYPE_SIZE;
  38640. }
  38641. if (dataType == undefined) {
  38642. return null;
  38643. }
  38644. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  38645. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  38646. animation.setKeys(keys);
  38647. if (easingFunction !== undefined) {
  38648. animation.setEasingFunction(easingFunction);
  38649. }
  38650. return animation;
  38651. };
  38652. /**
  38653. * Sets up an animation.
  38654. * @param property the property to animate
  38655. * @param animationType the animation type to apply
  38656. * @param easingFunction the easing function used in the animation
  38657. * @returns The created animation
  38658. */
  38659. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  38660. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  38661. animation.setEasingFunction(easingFunction);
  38662. return animation;
  38663. };
  38664. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  38665. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  38666. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  38667. };
  38668. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  38669. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  38670. node.animations.push(animation);
  38671. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  38672. };
  38673. /**
  38674. * Transition property of the Camera to the target Value.
  38675. * @param property The property to transition
  38676. * @param targetValue The target Value of the property
  38677. * @param host The object where the property to animate belongs
  38678. * @param scene Scene used to run the animation
  38679. * @param frameRate Framerate (in frame/s) to use
  38680. * @param transition The transition type we want to use
  38681. * @param duration The duration of the animation, in milliseconds
  38682. * @param onAnimationEnd Call back trigger at the end of the animation.
  38683. */
  38684. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  38685. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  38686. if (duration <= 0) {
  38687. host[property] = targetValue;
  38688. if (onAnimationEnd) {
  38689. onAnimationEnd();
  38690. }
  38691. return;
  38692. }
  38693. var endFrame = frameRate * (duration / 1000);
  38694. transition.setKeys([{
  38695. frame: 0,
  38696. value: host[property].clone ? host[property].clone() : host[property]
  38697. },
  38698. {
  38699. frame: endFrame,
  38700. value: targetValue
  38701. }]);
  38702. if (!host.animations) {
  38703. host.animations = [];
  38704. }
  38705. host.animations.push(transition);
  38706. var animation = scene.beginAnimation(host, 0, endFrame, false);
  38707. animation.onAnimationEnd = onAnimationEnd;
  38708. return animation;
  38709. };
  38710. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  38711. /**
  38712. * Return the array of runtime animations currently using this animation
  38713. */
  38714. get: function () {
  38715. return this._runtimeAnimations;
  38716. },
  38717. enumerable: true,
  38718. configurable: true
  38719. });
  38720. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  38721. get: function () {
  38722. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  38723. var runtimeAnimation = _a[_i];
  38724. if (!runtimeAnimation.isStopped) {
  38725. return true;
  38726. }
  38727. }
  38728. return false;
  38729. },
  38730. enumerable: true,
  38731. configurable: true
  38732. });
  38733. // Methods
  38734. /**
  38735. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  38736. */
  38737. Animation.prototype.toString = function (fullDetails) {
  38738. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  38739. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  38740. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  38741. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  38742. if (fullDetails) {
  38743. ret += ", Ranges: {";
  38744. var first = true;
  38745. for (var name in this._ranges) {
  38746. if (first) {
  38747. ret += ", ";
  38748. first = false;
  38749. }
  38750. ret += name;
  38751. }
  38752. ret += "}";
  38753. }
  38754. return ret;
  38755. };
  38756. /**
  38757. * Add an event to this animation.
  38758. */
  38759. Animation.prototype.addEvent = function (event) {
  38760. this._events.push(event);
  38761. };
  38762. /**
  38763. * Remove all events found at the given frame
  38764. * @param frame
  38765. */
  38766. Animation.prototype.removeEvents = function (frame) {
  38767. for (var index = 0; index < this._events.length; index++) {
  38768. if (this._events[index].frame === frame) {
  38769. this._events.splice(index, 1);
  38770. index--;
  38771. }
  38772. }
  38773. };
  38774. Animation.prototype.getEvents = function () {
  38775. return this._events;
  38776. };
  38777. Animation.prototype.createRange = function (name, from, to) {
  38778. // check name not already in use; could happen for bones after serialized
  38779. if (!this._ranges[name]) {
  38780. this._ranges[name] = new AnimationRange(name, from, to);
  38781. }
  38782. };
  38783. Animation.prototype.deleteRange = function (name, deleteFrames) {
  38784. if (deleteFrames === void 0) { deleteFrames = true; }
  38785. if (this._ranges[name]) {
  38786. if (deleteFrames) {
  38787. var from = this._ranges[name].from;
  38788. var to = this._ranges[name].to;
  38789. // this loop MUST go high to low for multiple splices to work
  38790. for (var key = this._keys.length - 1; key >= 0; key--) {
  38791. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  38792. this._keys.splice(key, 1);
  38793. }
  38794. }
  38795. }
  38796. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  38797. }
  38798. };
  38799. Animation.prototype.getRange = function (name) {
  38800. return this._ranges[name];
  38801. };
  38802. Animation.prototype.getKeys = function () {
  38803. return this._keys;
  38804. };
  38805. Animation.prototype.getHighestFrame = function () {
  38806. var ret = 0;
  38807. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  38808. if (ret < this._keys[key].frame) {
  38809. ret = this._keys[key].frame;
  38810. }
  38811. }
  38812. return ret;
  38813. };
  38814. Animation.prototype.getEasingFunction = function () {
  38815. return this._easingFunction;
  38816. };
  38817. Animation.prototype.setEasingFunction = function (easingFunction) {
  38818. this._easingFunction = easingFunction;
  38819. };
  38820. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  38821. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  38822. };
  38823. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  38824. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  38825. };
  38826. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  38827. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  38828. };
  38829. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  38830. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  38831. };
  38832. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  38833. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  38834. };
  38835. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  38836. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  38837. };
  38838. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  38839. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  38840. };
  38841. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  38842. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  38843. };
  38844. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  38845. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  38846. };
  38847. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  38848. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  38849. };
  38850. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  38851. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  38852. };
  38853. Animation.prototype.clone = function () {
  38854. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  38855. clone.enableBlending = this.enableBlending;
  38856. clone.blendingSpeed = this.blendingSpeed;
  38857. if (this._keys) {
  38858. clone.setKeys(this._keys);
  38859. }
  38860. if (this._ranges) {
  38861. clone._ranges = {};
  38862. for (var name in this._ranges) {
  38863. clone._ranges[name] = this._ranges[name].clone();
  38864. }
  38865. }
  38866. return clone;
  38867. };
  38868. Animation.prototype.setKeys = function (values) {
  38869. this._keys = values.slice(0);
  38870. };
  38871. Animation.prototype.serialize = function () {
  38872. var serializationObject = {};
  38873. serializationObject.name = this.name;
  38874. serializationObject.property = this.targetProperty;
  38875. serializationObject.framePerSecond = this.framePerSecond;
  38876. serializationObject.dataType = this.dataType;
  38877. serializationObject.loopBehavior = this.loopMode;
  38878. serializationObject.enableBlending = this.enableBlending;
  38879. serializationObject.blendingSpeed = this.blendingSpeed;
  38880. var dataType = this.dataType;
  38881. serializationObject.keys = [];
  38882. var keys = this.getKeys();
  38883. for (var index = 0; index < keys.length; index++) {
  38884. var animationKey = keys[index];
  38885. var key = {};
  38886. key.frame = animationKey.frame;
  38887. switch (dataType) {
  38888. case Animation.ANIMATIONTYPE_FLOAT:
  38889. key.values = [animationKey.value];
  38890. break;
  38891. case Animation.ANIMATIONTYPE_QUATERNION:
  38892. case Animation.ANIMATIONTYPE_MATRIX:
  38893. case Animation.ANIMATIONTYPE_VECTOR3:
  38894. case Animation.ANIMATIONTYPE_COLOR3:
  38895. key.values = animationKey.value.asArray();
  38896. break;
  38897. }
  38898. serializationObject.keys.push(key);
  38899. }
  38900. serializationObject.ranges = [];
  38901. for (var name in this._ranges) {
  38902. var range = {};
  38903. range.name = name;
  38904. range.from = this._ranges[name].from;
  38905. range.to = this._ranges[name].to;
  38906. serializationObject.ranges.push(range);
  38907. }
  38908. return serializationObject;
  38909. };
  38910. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  38911. get: function () {
  38912. return Animation._ANIMATIONTYPE_FLOAT;
  38913. },
  38914. enumerable: true,
  38915. configurable: true
  38916. });
  38917. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  38918. get: function () {
  38919. return Animation._ANIMATIONTYPE_VECTOR3;
  38920. },
  38921. enumerable: true,
  38922. configurable: true
  38923. });
  38924. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  38925. get: function () {
  38926. return Animation._ANIMATIONTYPE_VECTOR2;
  38927. },
  38928. enumerable: true,
  38929. configurable: true
  38930. });
  38931. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  38932. get: function () {
  38933. return Animation._ANIMATIONTYPE_SIZE;
  38934. },
  38935. enumerable: true,
  38936. configurable: true
  38937. });
  38938. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  38939. get: function () {
  38940. return Animation._ANIMATIONTYPE_QUATERNION;
  38941. },
  38942. enumerable: true,
  38943. configurable: true
  38944. });
  38945. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  38946. get: function () {
  38947. return Animation._ANIMATIONTYPE_MATRIX;
  38948. },
  38949. enumerable: true,
  38950. configurable: true
  38951. });
  38952. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  38953. get: function () {
  38954. return Animation._ANIMATIONTYPE_COLOR3;
  38955. },
  38956. enumerable: true,
  38957. configurable: true
  38958. });
  38959. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  38960. get: function () {
  38961. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  38962. },
  38963. enumerable: true,
  38964. configurable: true
  38965. });
  38966. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  38967. get: function () {
  38968. return Animation._ANIMATIONLOOPMODE_CYCLE;
  38969. },
  38970. enumerable: true,
  38971. configurable: true
  38972. });
  38973. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  38974. get: function () {
  38975. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  38976. },
  38977. enumerable: true,
  38978. configurable: true
  38979. });
  38980. Animation.Parse = function (parsedAnimation) {
  38981. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  38982. var dataType = parsedAnimation.dataType;
  38983. var keys = [];
  38984. var data;
  38985. var index;
  38986. if (parsedAnimation.enableBlending) {
  38987. animation.enableBlending = parsedAnimation.enableBlending;
  38988. }
  38989. if (parsedAnimation.blendingSpeed) {
  38990. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  38991. }
  38992. for (index = 0; index < parsedAnimation.keys.length; index++) {
  38993. var key = parsedAnimation.keys[index];
  38994. switch (dataType) {
  38995. case Animation.ANIMATIONTYPE_FLOAT:
  38996. data = key.values[0];
  38997. break;
  38998. case Animation.ANIMATIONTYPE_QUATERNION:
  38999. data = BABYLON.Quaternion.FromArray(key.values);
  39000. break;
  39001. case Animation.ANIMATIONTYPE_MATRIX:
  39002. data = BABYLON.Matrix.FromArray(key.values);
  39003. break;
  39004. case Animation.ANIMATIONTYPE_COLOR3:
  39005. data = BABYLON.Color3.FromArray(key.values);
  39006. break;
  39007. case Animation.ANIMATIONTYPE_VECTOR3:
  39008. default:
  39009. data = BABYLON.Vector3.FromArray(key.values);
  39010. break;
  39011. }
  39012. keys.push({
  39013. frame: key.frame,
  39014. value: data
  39015. });
  39016. }
  39017. animation.setKeys(keys);
  39018. if (parsedAnimation.ranges) {
  39019. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  39020. data = parsedAnimation.ranges[index];
  39021. animation.createRange(data.name, data.from, data.to);
  39022. }
  39023. }
  39024. return animation;
  39025. };
  39026. Animation.AppendSerializedAnimations = function (source, destination) {
  39027. if (source.animations) {
  39028. destination.animations = [];
  39029. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  39030. var animation = source.animations[animationIndex];
  39031. destination.animations.push(animation.serialize());
  39032. }
  39033. }
  39034. };
  39035. Animation.AllowMatricesInterpolation = false;
  39036. // Statics
  39037. Animation._ANIMATIONTYPE_FLOAT = 0;
  39038. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  39039. Animation._ANIMATIONTYPE_QUATERNION = 2;
  39040. Animation._ANIMATIONTYPE_MATRIX = 3;
  39041. Animation._ANIMATIONTYPE_COLOR3 = 4;
  39042. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  39043. Animation._ANIMATIONTYPE_SIZE = 6;
  39044. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  39045. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  39046. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  39047. return Animation;
  39048. }());
  39049. BABYLON.Animation = Animation;
  39050. })(BABYLON || (BABYLON = {}));
  39051. //# sourceMappingURL=babylon.animation.js.map
  39052. var BABYLON;
  39053. (function (BABYLON) {
  39054. var RuntimeAnimation = (function () {
  39055. function RuntimeAnimation(target, animation) {
  39056. this._offsetsCache = {};
  39057. this._highLimitsCache = {};
  39058. this._stopped = false;
  39059. this._blendingFactor = 0;
  39060. this._ratioOffset = 0;
  39061. this._animation = animation;
  39062. this._target = target;
  39063. animation._runtimeAnimations.push(this);
  39064. }
  39065. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  39066. get: function () {
  39067. return this._animation;
  39068. },
  39069. enumerable: true,
  39070. configurable: true
  39071. });
  39072. RuntimeAnimation.prototype.reset = function () {
  39073. this._offsetsCache = {};
  39074. this._highLimitsCache = {};
  39075. this.currentFrame = 0;
  39076. this._blendingFactor = 0;
  39077. this._originalBlendValue = null;
  39078. };
  39079. RuntimeAnimation.prototype.isStopped = function () {
  39080. return this._stopped;
  39081. };
  39082. RuntimeAnimation.prototype.dispose = function () {
  39083. var index = this._animation.runtimeAnimations.indexOf(this);
  39084. if (index > -1) {
  39085. this._animation.runtimeAnimations.splice(index, 1);
  39086. }
  39087. };
  39088. RuntimeAnimation.prototype._getKeyValue = function (value) {
  39089. if (typeof value === "function") {
  39090. return value();
  39091. }
  39092. return value;
  39093. };
  39094. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  39095. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  39096. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  39097. }
  39098. this.currentFrame = currentFrame;
  39099. var keys = this._animation.getKeys();
  39100. // Try to get a hash to find the right key
  39101. var startKeyIndex = Math.max(0, Math.min(keys.length - 1, Math.floor(keys.length * (currentFrame - keys[0].frame) / (keys[keys.length - 1].frame - keys[0].frame)) - 1));
  39102. if (keys[startKeyIndex].frame >= currentFrame) {
  39103. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  39104. startKeyIndex--;
  39105. }
  39106. }
  39107. for (var key = startKeyIndex; key < keys.length; key++) {
  39108. var endKey = keys[key + 1];
  39109. if (endKey.frame >= currentFrame) {
  39110. var startKey = keys[key];
  39111. var startValue = this._getKeyValue(startKey.value);
  39112. var endValue = this._getKeyValue(endKey.value);
  39113. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  39114. var frameDelta = endKey.frame - startKey.frame;
  39115. // gradient : percent of currentFrame between the frame inf and the frame sup
  39116. var gradient = (currentFrame - startKey.frame) / frameDelta;
  39117. // check for easingFunction and correction of gradient
  39118. var easingFunction = this._animation.getEasingFunction();
  39119. if (easingFunction != null) {
  39120. gradient = easingFunction.ease(gradient);
  39121. }
  39122. switch (this._animation.dataType) {
  39123. // Float
  39124. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  39125. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  39126. switch (loopMode) {
  39127. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39128. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39129. return floatValue;
  39130. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39131. return offsetValue * repeatCount + floatValue;
  39132. }
  39133. break;
  39134. // Quaternion
  39135. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  39136. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  39137. switch (loopMode) {
  39138. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39139. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39140. return quatValue;
  39141. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39142. return quatValue.add(offsetValue.scale(repeatCount));
  39143. }
  39144. return quatValue;
  39145. // Vector3
  39146. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  39147. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  39148. switch (loopMode) {
  39149. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39150. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39151. return vec3Value;
  39152. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39153. return vec3Value.add(offsetValue.scale(repeatCount));
  39154. }
  39155. // Vector2
  39156. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  39157. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  39158. switch (loopMode) {
  39159. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39160. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39161. return vec2Value;
  39162. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39163. return vec2Value.add(offsetValue.scale(repeatCount));
  39164. }
  39165. // Size
  39166. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  39167. switch (loopMode) {
  39168. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39169. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39170. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  39171. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39172. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  39173. }
  39174. // Color3
  39175. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  39176. switch (loopMode) {
  39177. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39178. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39179. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  39180. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39181. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  39182. }
  39183. // Matrix
  39184. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  39185. switch (loopMode) {
  39186. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  39187. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  39188. if (BABYLON.Animation.AllowMatricesInterpolation) {
  39189. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  39190. }
  39191. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  39192. return startValue;
  39193. }
  39194. default:
  39195. break;
  39196. }
  39197. break;
  39198. }
  39199. }
  39200. return this._getKeyValue(keys[keys.length - 1].value);
  39201. };
  39202. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  39203. if (blend === void 0) { blend = false; }
  39204. // Set value
  39205. var path;
  39206. var destination;
  39207. var targetPropertyPath = this._animation.targetPropertyPath;
  39208. if (targetPropertyPath.length > 1) {
  39209. var property = this._target[targetPropertyPath[0]];
  39210. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  39211. property = property[targetPropertyPath[index]];
  39212. }
  39213. path = targetPropertyPath[targetPropertyPath.length - 1];
  39214. destination = property;
  39215. }
  39216. else {
  39217. path = targetPropertyPath[0];
  39218. destination = this._target;
  39219. }
  39220. // Blending
  39221. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  39222. if (!this._originalBlendValue) {
  39223. if (destination[path].clone) {
  39224. this._originalBlendValue = destination[path].clone();
  39225. }
  39226. else {
  39227. this._originalBlendValue = destination[path];
  39228. }
  39229. }
  39230. if (this._originalBlendValue.prototype) {
  39231. if (this._originalBlendValue.prototype.Lerp) {
  39232. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  39233. }
  39234. else {
  39235. destination[path] = currentValue;
  39236. }
  39237. }
  39238. else if (this._originalBlendValue.m) {
  39239. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  39240. }
  39241. else {
  39242. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  39243. }
  39244. this._blendingFactor += this._animation.blendingSpeed;
  39245. }
  39246. else {
  39247. destination[path] = currentValue;
  39248. }
  39249. if (this._target.markAsDirty) {
  39250. this._target.markAsDirty(this._animation.targetProperty);
  39251. }
  39252. };
  39253. RuntimeAnimation.prototype.goToFrame = function (frame) {
  39254. var keys = this._animation.getKeys();
  39255. if (frame < keys[0].frame) {
  39256. frame = keys[0].frame;
  39257. }
  39258. else if (frame > keys[keys.length - 1].frame) {
  39259. frame = keys[keys.length - 1].frame;
  39260. }
  39261. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  39262. this.setValue(currentValue);
  39263. };
  39264. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  39265. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  39266. this._ratioOffset = this._previousRatio - newRatio;
  39267. };
  39268. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  39269. if (blend === void 0) { blend = false; }
  39270. var targetPropertyPath = this._animation.targetPropertyPath;
  39271. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  39272. this._stopped = true;
  39273. return false;
  39274. }
  39275. var returnValue = true;
  39276. var keys = this._animation.getKeys();
  39277. // Adding a start key at frame 0 if missing
  39278. if (keys[0].frame !== 0) {
  39279. var newKey = { frame: 0, value: keys[0].value };
  39280. keys.splice(0, 0, newKey);
  39281. }
  39282. // Check limits
  39283. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  39284. from = keys[0].frame;
  39285. }
  39286. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  39287. to = keys[keys.length - 1].frame;
  39288. }
  39289. //to and from cannot be the same key
  39290. if (from === to) {
  39291. if (from > keys[0].frame) {
  39292. from--;
  39293. }
  39294. else if (to < keys[keys.length - 1].frame) {
  39295. to++;
  39296. }
  39297. }
  39298. // Compute ratio
  39299. var range = to - from;
  39300. var offsetValue;
  39301. // ratio represents the frame delta between from and to
  39302. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  39303. var highLimitValue = 0;
  39304. this._previousDelay = delay;
  39305. this._previousRatio = ratio;
  39306. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  39307. returnValue = false;
  39308. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  39309. }
  39310. else {
  39311. // Get max value if required
  39312. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  39313. var keyOffset = to.toString() + from.toString();
  39314. if (!this._offsetsCache[keyOffset]) {
  39315. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  39316. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  39317. switch (this._animation.dataType) {
  39318. // Float
  39319. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  39320. this._offsetsCache[keyOffset] = toValue - fromValue;
  39321. break;
  39322. // Quaternion
  39323. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  39324. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  39325. break;
  39326. // Vector3
  39327. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  39328. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  39329. // Vector2
  39330. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  39331. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  39332. // Size
  39333. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  39334. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  39335. // Color3
  39336. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  39337. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  39338. default:
  39339. break;
  39340. }
  39341. this._highLimitsCache[keyOffset] = toValue;
  39342. }
  39343. highLimitValue = this._highLimitsCache[keyOffset];
  39344. offsetValue = this._offsetsCache[keyOffset];
  39345. }
  39346. }
  39347. if (offsetValue === undefined) {
  39348. switch (this._animation.dataType) {
  39349. // Float
  39350. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  39351. offsetValue = 0;
  39352. break;
  39353. // Quaternion
  39354. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  39355. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  39356. break;
  39357. // Vector3
  39358. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  39359. offsetValue = BABYLON.Vector3.Zero();
  39360. break;
  39361. // Vector2
  39362. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  39363. offsetValue = BABYLON.Vector2.Zero();
  39364. break;
  39365. // Size
  39366. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  39367. offsetValue = BABYLON.Size.Zero();
  39368. break;
  39369. // Color3
  39370. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  39371. offsetValue = BABYLON.Color3.Black();
  39372. }
  39373. }
  39374. // Compute value
  39375. var repeatCount = (ratio / range) >> 0;
  39376. var currentFrame = returnValue ? from + ratio % range : to;
  39377. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  39378. // Set value
  39379. this.setValue(currentValue);
  39380. // Check events
  39381. var events = this._animation.getEvents();
  39382. for (var index = 0; index < events.length; index++) {
  39383. // Make sure current frame has passed event frame and that event frame is within the current range
  39384. // Also, handle both forward and reverse animations
  39385. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  39386. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  39387. var event = events[index];
  39388. if (!event.isDone) {
  39389. // If event should be done only once, remove it.
  39390. if (event.onlyOnce) {
  39391. events.splice(index, 1);
  39392. index--;
  39393. }
  39394. event.isDone = true;
  39395. event.action();
  39396. } // Don't do anything if the event has already be done.
  39397. }
  39398. else if (events[index].isDone && !events[index].onlyOnce) {
  39399. // reset event, the animation is looping
  39400. events[index].isDone = false;
  39401. }
  39402. }
  39403. if (!returnValue) {
  39404. this._stopped = true;
  39405. }
  39406. return returnValue;
  39407. };
  39408. return RuntimeAnimation;
  39409. }());
  39410. BABYLON.RuntimeAnimation = RuntimeAnimation;
  39411. })(BABYLON || (BABYLON = {}));
  39412. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  39413. var BABYLON;
  39414. (function (BABYLON) {
  39415. var Animatable = (function () {
  39416. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  39417. if (fromFrame === void 0) { fromFrame = 0; }
  39418. if (toFrame === void 0) { toFrame = 100; }
  39419. if (loopAnimation === void 0) { loopAnimation = false; }
  39420. if (speedRatio === void 0) { speedRatio = 1.0; }
  39421. this.target = target;
  39422. this.fromFrame = fromFrame;
  39423. this.toFrame = toFrame;
  39424. this.loopAnimation = loopAnimation;
  39425. this.onAnimationEnd = onAnimationEnd;
  39426. this._localDelayOffset = null;
  39427. this._pausedDelay = null;
  39428. this._runtimeAnimations = new Array();
  39429. this._paused = false;
  39430. this._speedRatio = 1;
  39431. this.animationStarted = false;
  39432. if (animations) {
  39433. this.appendAnimations(target, animations);
  39434. }
  39435. this._speedRatio = speedRatio;
  39436. this._scene = scene;
  39437. scene._activeAnimatables.push(this);
  39438. }
  39439. Object.defineProperty(Animatable.prototype, "speedRatio", {
  39440. get: function () {
  39441. return this._speedRatio;
  39442. },
  39443. set: function (value) {
  39444. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  39445. var animation = this._runtimeAnimations[index];
  39446. animation._prepareForSpeedRatioChange(value);
  39447. }
  39448. this._speedRatio = value;
  39449. },
  39450. enumerable: true,
  39451. configurable: true
  39452. });
  39453. // Methods
  39454. Animatable.prototype.getAnimations = function () {
  39455. return this._runtimeAnimations;
  39456. };
  39457. Animatable.prototype.appendAnimations = function (target, animations) {
  39458. for (var index = 0; index < animations.length; index++) {
  39459. var animation = animations[index];
  39460. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  39461. }
  39462. };
  39463. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  39464. var runtimeAnimations = this._runtimeAnimations;
  39465. for (var index = 0; index < runtimeAnimations.length; index++) {
  39466. if (runtimeAnimations[index].animation.targetProperty === property) {
  39467. return runtimeAnimations[index].animation;
  39468. }
  39469. }
  39470. return null;
  39471. };
  39472. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  39473. var runtimeAnimations = this._runtimeAnimations;
  39474. for (var index = 0; index < runtimeAnimations.length; index++) {
  39475. if (runtimeAnimations[index].animation.targetProperty === property) {
  39476. return runtimeAnimations[index];
  39477. }
  39478. }
  39479. return null;
  39480. };
  39481. Animatable.prototype.reset = function () {
  39482. var runtimeAnimations = this._runtimeAnimations;
  39483. for (var index = 0; index < runtimeAnimations.length; index++) {
  39484. runtimeAnimations[index].reset();
  39485. }
  39486. this._localDelayOffset = null;
  39487. this._pausedDelay = null;
  39488. };
  39489. Animatable.prototype.enableBlending = function (blendingSpeed) {
  39490. var runtimeAnimations = this._runtimeAnimations;
  39491. for (var index = 0; index < runtimeAnimations.length; index++) {
  39492. runtimeAnimations[index].animation.enableBlending = true;
  39493. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  39494. }
  39495. };
  39496. Animatable.prototype.disableBlending = function () {
  39497. var runtimeAnimations = this._runtimeAnimations;
  39498. for (var index = 0; index < runtimeAnimations.length; index++) {
  39499. runtimeAnimations[index].animation.enableBlending = false;
  39500. }
  39501. };
  39502. Animatable.prototype.goToFrame = function (frame) {
  39503. var runtimeAnimations = this._runtimeAnimations;
  39504. if (runtimeAnimations[0]) {
  39505. var fps = runtimeAnimations[0].animation.framePerSecond;
  39506. var currentFrame = runtimeAnimations[0].currentFrame;
  39507. var adjustTime = frame - currentFrame;
  39508. var delay = adjustTime * 1000 / fps;
  39509. this._localDelayOffset -= delay;
  39510. }
  39511. for (var index = 0; index < runtimeAnimations.length; index++) {
  39512. runtimeAnimations[index].goToFrame(frame);
  39513. }
  39514. };
  39515. Animatable.prototype.pause = function () {
  39516. if (this._paused) {
  39517. return;
  39518. }
  39519. this._paused = true;
  39520. };
  39521. Animatable.prototype.restart = function () {
  39522. this._paused = false;
  39523. };
  39524. Animatable.prototype.stop = function (animationName) {
  39525. if (animationName) {
  39526. var idx = this._scene._activeAnimatables.indexOf(this);
  39527. if (idx > -1) {
  39528. var runtimeAnimations = this._runtimeAnimations;
  39529. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  39530. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  39531. continue;
  39532. }
  39533. runtimeAnimations[index].dispose();
  39534. runtimeAnimations.splice(index, 1);
  39535. }
  39536. if (runtimeAnimations.length == 0) {
  39537. this._scene._activeAnimatables.splice(idx, 1);
  39538. if (this.onAnimationEnd) {
  39539. this.onAnimationEnd();
  39540. }
  39541. }
  39542. }
  39543. }
  39544. else {
  39545. var index = this._scene._activeAnimatables.indexOf(this);
  39546. if (index > -1) {
  39547. this._scene._activeAnimatables.splice(index, 1);
  39548. var runtimeAnimations = this._runtimeAnimations;
  39549. for (var index = 0; index < runtimeAnimations.length; index++) {
  39550. runtimeAnimations[index].dispose();
  39551. }
  39552. if (this.onAnimationEnd) {
  39553. this.onAnimationEnd();
  39554. }
  39555. }
  39556. }
  39557. };
  39558. Animatable.prototype._animate = function (delay) {
  39559. if (this._paused) {
  39560. this.animationStarted = false;
  39561. if (this._pausedDelay === null) {
  39562. this._pausedDelay = delay;
  39563. }
  39564. return true;
  39565. }
  39566. if (this._localDelayOffset === null) {
  39567. this._localDelayOffset = delay;
  39568. }
  39569. else if (this._pausedDelay !== null) {
  39570. this._localDelayOffset += delay - this._pausedDelay;
  39571. this._pausedDelay = null;
  39572. }
  39573. // Animating
  39574. var running = false;
  39575. var runtimeAnimations = this._runtimeAnimations;
  39576. var index;
  39577. for (index = 0; index < runtimeAnimations.length; index++) {
  39578. var animation = runtimeAnimations[index];
  39579. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  39580. running = running || isRunning;
  39581. }
  39582. this.animationStarted = running;
  39583. if (!running) {
  39584. // Remove from active animatables
  39585. index = this._scene._activeAnimatables.indexOf(this);
  39586. this._scene._activeAnimatables.splice(index, 1);
  39587. // Dispose all runtime animations
  39588. for (index = 0; index < runtimeAnimations.length; index++) {
  39589. runtimeAnimations[index].dispose();
  39590. }
  39591. }
  39592. if (!running && this.onAnimationEnd) {
  39593. this.onAnimationEnd();
  39594. this.onAnimationEnd = null;
  39595. }
  39596. return running;
  39597. };
  39598. return Animatable;
  39599. }());
  39600. BABYLON.Animatable = Animatable;
  39601. })(BABYLON || (BABYLON = {}));
  39602. //# sourceMappingURL=babylon.animatable.js.map
  39603. var BABYLON;
  39604. (function (BABYLON) {
  39605. var EasingFunction = (function () {
  39606. function EasingFunction() {
  39607. // Properties
  39608. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  39609. }
  39610. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  39611. get: function () {
  39612. return EasingFunction._EASINGMODE_EASEIN;
  39613. },
  39614. enumerable: true,
  39615. configurable: true
  39616. });
  39617. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  39618. get: function () {
  39619. return EasingFunction._EASINGMODE_EASEOUT;
  39620. },
  39621. enumerable: true,
  39622. configurable: true
  39623. });
  39624. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  39625. get: function () {
  39626. return EasingFunction._EASINGMODE_EASEINOUT;
  39627. },
  39628. enumerable: true,
  39629. configurable: true
  39630. });
  39631. EasingFunction.prototype.setEasingMode = function (easingMode) {
  39632. var n = Math.min(Math.max(easingMode, 0), 2);
  39633. this._easingMode = n;
  39634. };
  39635. EasingFunction.prototype.getEasingMode = function () {
  39636. return this._easingMode;
  39637. };
  39638. EasingFunction.prototype.easeInCore = function (gradient) {
  39639. throw new Error('You must implement this method');
  39640. };
  39641. EasingFunction.prototype.ease = function (gradient) {
  39642. switch (this._easingMode) {
  39643. case EasingFunction.EASINGMODE_EASEIN:
  39644. return this.easeInCore(gradient);
  39645. case EasingFunction.EASINGMODE_EASEOUT:
  39646. return (1 - this.easeInCore(1 - gradient));
  39647. }
  39648. if (gradient >= 0.5) {
  39649. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  39650. }
  39651. return (this.easeInCore(gradient * 2) * 0.5);
  39652. };
  39653. //Statics
  39654. EasingFunction._EASINGMODE_EASEIN = 0;
  39655. EasingFunction._EASINGMODE_EASEOUT = 1;
  39656. EasingFunction._EASINGMODE_EASEINOUT = 2;
  39657. return EasingFunction;
  39658. }());
  39659. BABYLON.EasingFunction = EasingFunction;
  39660. var CircleEase = (function (_super) {
  39661. __extends(CircleEase, _super);
  39662. function CircleEase() {
  39663. return _super !== null && _super.apply(this, arguments) || this;
  39664. }
  39665. CircleEase.prototype.easeInCore = function (gradient) {
  39666. gradient = Math.max(0, Math.min(1, gradient));
  39667. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  39668. };
  39669. return CircleEase;
  39670. }(EasingFunction));
  39671. BABYLON.CircleEase = CircleEase;
  39672. var BackEase = (function (_super) {
  39673. __extends(BackEase, _super);
  39674. function BackEase(amplitude) {
  39675. if (amplitude === void 0) { amplitude = 1; }
  39676. var _this = _super.call(this) || this;
  39677. _this.amplitude = amplitude;
  39678. return _this;
  39679. }
  39680. BackEase.prototype.easeInCore = function (gradient) {
  39681. var num = Math.max(0, this.amplitude);
  39682. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  39683. };
  39684. return BackEase;
  39685. }(EasingFunction));
  39686. BABYLON.BackEase = BackEase;
  39687. var BounceEase = (function (_super) {
  39688. __extends(BounceEase, _super);
  39689. function BounceEase(bounces, bounciness) {
  39690. if (bounces === void 0) { bounces = 3; }
  39691. if (bounciness === void 0) { bounciness = 2; }
  39692. var _this = _super.call(this) || this;
  39693. _this.bounces = bounces;
  39694. _this.bounciness = bounciness;
  39695. return _this;
  39696. }
  39697. BounceEase.prototype.easeInCore = function (gradient) {
  39698. var y = Math.max(0.0, this.bounces);
  39699. var bounciness = this.bounciness;
  39700. if (bounciness <= 1.0) {
  39701. bounciness = 1.001;
  39702. }
  39703. var num9 = Math.pow(bounciness, y);
  39704. var num5 = 1.0 - bounciness;
  39705. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  39706. var num15 = gradient * num4;
  39707. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  39708. var num3 = Math.floor(num65);
  39709. var num13 = num3 + 1.0;
  39710. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  39711. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  39712. var num7 = (num8 + num12) * 0.5;
  39713. var num6 = gradient - num7;
  39714. var num2 = num7 - num8;
  39715. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  39716. };
  39717. return BounceEase;
  39718. }(EasingFunction));
  39719. BABYLON.BounceEase = BounceEase;
  39720. var CubicEase = (function (_super) {
  39721. __extends(CubicEase, _super);
  39722. function CubicEase() {
  39723. return _super !== null && _super.apply(this, arguments) || this;
  39724. }
  39725. CubicEase.prototype.easeInCore = function (gradient) {
  39726. return (gradient * gradient * gradient);
  39727. };
  39728. return CubicEase;
  39729. }(EasingFunction));
  39730. BABYLON.CubicEase = CubicEase;
  39731. var ElasticEase = (function (_super) {
  39732. __extends(ElasticEase, _super);
  39733. function ElasticEase(oscillations, springiness) {
  39734. if (oscillations === void 0) { oscillations = 3; }
  39735. if (springiness === void 0) { springiness = 3; }
  39736. var _this = _super.call(this) || this;
  39737. _this.oscillations = oscillations;
  39738. _this.springiness = springiness;
  39739. return _this;
  39740. }
  39741. ElasticEase.prototype.easeInCore = function (gradient) {
  39742. var num2;
  39743. var num3 = Math.max(0.0, this.oscillations);
  39744. var num = Math.max(0.0, this.springiness);
  39745. if (num == 0) {
  39746. num2 = gradient;
  39747. }
  39748. else {
  39749. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  39750. }
  39751. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  39752. };
  39753. return ElasticEase;
  39754. }(EasingFunction));
  39755. BABYLON.ElasticEase = ElasticEase;
  39756. var ExponentialEase = (function (_super) {
  39757. __extends(ExponentialEase, _super);
  39758. function ExponentialEase(exponent) {
  39759. if (exponent === void 0) { exponent = 2; }
  39760. var _this = _super.call(this) || this;
  39761. _this.exponent = exponent;
  39762. return _this;
  39763. }
  39764. ExponentialEase.prototype.easeInCore = function (gradient) {
  39765. if (this.exponent <= 0) {
  39766. return gradient;
  39767. }
  39768. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  39769. };
  39770. return ExponentialEase;
  39771. }(EasingFunction));
  39772. BABYLON.ExponentialEase = ExponentialEase;
  39773. var PowerEase = (function (_super) {
  39774. __extends(PowerEase, _super);
  39775. function PowerEase(power) {
  39776. if (power === void 0) { power = 2; }
  39777. var _this = _super.call(this) || this;
  39778. _this.power = power;
  39779. return _this;
  39780. }
  39781. PowerEase.prototype.easeInCore = function (gradient) {
  39782. var y = Math.max(0.0, this.power);
  39783. return Math.pow(gradient, y);
  39784. };
  39785. return PowerEase;
  39786. }(EasingFunction));
  39787. BABYLON.PowerEase = PowerEase;
  39788. var QuadraticEase = (function (_super) {
  39789. __extends(QuadraticEase, _super);
  39790. function QuadraticEase() {
  39791. return _super !== null && _super.apply(this, arguments) || this;
  39792. }
  39793. QuadraticEase.prototype.easeInCore = function (gradient) {
  39794. return (gradient * gradient);
  39795. };
  39796. return QuadraticEase;
  39797. }(EasingFunction));
  39798. BABYLON.QuadraticEase = QuadraticEase;
  39799. var QuarticEase = (function (_super) {
  39800. __extends(QuarticEase, _super);
  39801. function QuarticEase() {
  39802. return _super !== null && _super.apply(this, arguments) || this;
  39803. }
  39804. QuarticEase.prototype.easeInCore = function (gradient) {
  39805. return (gradient * gradient * gradient * gradient);
  39806. };
  39807. return QuarticEase;
  39808. }(EasingFunction));
  39809. BABYLON.QuarticEase = QuarticEase;
  39810. var QuinticEase = (function (_super) {
  39811. __extends(QuinticEase, _super);
  39812. function QuinticEase() {
  39813. return _super !== null && _super.apply(this, arguments) || this;
  39814. }
  39815. QuinticEase.prototype.easeInCore = function (gradient) {
  39816. return (gradient * gradient * gradient * gradient * gradient);
  39817. };
  39818. return QuinticEase;
  39819. }(EasingFunction));
  39820. BABYLON.QuinticEase = QuinticEase;
  39821. var SineEase = (function (_super) {
  39822. __extends(SineEase, _super);
  39823. function SineEase() {
  39824. return _super !== null && _super.apply(this, arguments) || this;
  39825. }
  39826. SineEase.prototype.easeInCore = function (gradient) {
  39827. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  39828. };
  39829. return SineEase;
  39830. }(EasingFunction));
  39831. BABYLON.SineEase = SineEase;
  39832. var BezierCurveEase = (function (_super) {
  39833. __extends(BezierCurveEase, _super);
  39834. function BezierCurveEase(x1, y1, x2, y2) {
  39835. if (x1 === void 0) { x1 = 0; }
  39836. if (y1 === void 0) { y1 = 0; }
  39837. if (x2 === void 0) { x2 = 1; }
  39838. if (y2 === void 0) { y2 = 1; }
  39839. var _this = _super.call(this) || this;
  39840. _this.x1 = x1;
  39841. _this.y1 = y1;
  39842. _this.x2 = x2;
  39843. _this.y2 = y2;
  39844. return _this;
  39845. }
  39846. BezierCurveEase.prototype.easeInCore = function (gradient) {
  39847. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  39848. };
  39849. return BezierCurveEase;
  39850. }(EasingFunction));
  39851. BABYLON.BezierCurveEase = BezierCurveEase;
  39852. })(BABYLON || (BABYLON = {}));
  39853. //# sourceMappingURL=babylon.easing.js.map
  39854. var BABYLON;
  39855. (function (BABYLON) {
  39856. var Condition = (function () {
  39857. function Condition(actionManager) {
  39858. this._actionManager = actionManager;
  39859. }
  39860. Condition.prototype.isValid = function () {
  39861. return true;
  39862. };
  39863. Condition.prototype._getProperty = function (propertyPath) {
  39864. return this._actionManager._getProperty(propertyPath);
  39865. };
  39866. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  39867. return this._actionManager._getEffectiveTarget(target, propertyPath);
  39868. };
  39869. Condition.prototype.serialize = function () {
  39870. };
  39871. Condition.prototype._serialize = function (serializedCondition) {
  39872. return {
  39873. type: 2,
  39874. children: [],
  39875. name: serializedCondition.name,
  39876. properties: serializedCondition.properties
  39877. };
  39878. };
  39879. return Condition;
  39880. }());
  39881. BABYLON.Condition = Condition;
  39882. var ValueCondition = (function (_super) {
  39883. __extends(ValueCondition, _super);
  39884. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  39885. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  39886. var _this = _super.call(this, actionManager) || this;
  39887. _this.propertyPath = propertyPath;
  39888. _this.value = value;
  39889. _this.operator = operator;
  39890. _this._target = target;
  39891. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  39892. _this._property = _this._getProperty(_this.propertyPath);
  39893. return _this;
  39894. }
  39895. Object.defineProperty(ValueCondition, "IsEqual", {
  39896. get: function () {
  39897. return ValueCondition._IsEqual;
  39898. },
  39899. enumerable: true,
  39900. configurable: true
  39901. });
  39902. Object.defineProperty(ValueCondition, "IsDifferent", {
  39903. get: function () {
  39904. return ValueCondition._IsDifferent;
  39905. },
  39906. enumerable: true,
  39907. configurable: true
  39908. });
  39909. Object.defineProperty(ValueCondition, "IsGreater", {
  39910. get: function () {
  39911. return ValueCondition._IsGreater;
  39912. },
  39913. enumerable: true,
  39914. configurable: true
  39915. });
  39916. Object.defineProperty(ValueCondition, "IsLesser", {
  39917. get: function () {
  39918. return ValueCondition._IsLesser;
  39919. },
  39920. enumerable: true,
  39921. configurable: true
  39922. });
  39923. // Methods
  39924. ValueCondition.prototype.isValid = function () {
  39925. switch (this.operator) {
  39926. case ValueCondition.IsGreater:
  39927. return this._effectiveTarget[this._property] > this.value;
  39928. case ValueCondition.IsLesser:
  39929. return this._effectiveTarget[this._property] < this.value;
  39930. case ValueCondition.IsEqual:
  39931. case ValueCondition.IsDifferent:
  39932. var check;
  39933. if (this.value.equals) {
  39934. check = this.value.equals(this._effectiveTarget[this._property]);
  39935. }
  39936. else {
  39937. check = this.value === this._effectiveTarget[this._property];
  39938. }
  39939. return this.operator === ValueCondition.IsEqual ? check : !check;
  39940. }
  39941. return false;
  39942. };
  39943. ValueCondition.prototype.serialize = function () {
  39944. return this._serialize({
  39945. name: "ValueCondition",
  39946. properties: [
  39947. BABYLON.Action._GetTargetProperty(this._target),
  39948. { name: "propertyPath", value: this.propertyPath },
  39949. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  39950. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  39951. ]
  39952. });
  39953. };
  39954. ValueCondition.GetOperatorName = function (operator) {
  39955. switch (operator) {
  39956. case ValueCondition._IsEqual: return "IsEqual";
  39957. case ValueCondition._IsDifferent: return "IsDifferent";
  39958. case ValueCondition._IsGreater: return "IsGreater";
  39959. case ValueCondition._IsLesser: return "IsLesser";
  39960. default: return "";
  39961. }
  39962. };
  39963. // Statics
  39964. ValueCondition._IsEqual = 0;
  39965. ValueCondition._IsDifferent = 1;
  39966. ValueCondition._IsGreater = 2;
  39967. ValueCondition._IsLesser = 3;
  39968. return ValueCondition;
  39969. }(Condition));
  39970. BABYLON.ValueCondition = ValueCondition;
  39971. var PredicateCondition = (function (_super) {
  39972. __extends(PredicateCondition, _super);
  39973. function PredicateCondition(actionManager, predicate) {
  39974. var _this = _super.call(this, actionManager) || this;
  39975. _this.predicate = predicate;
  39976. return _this;
  39977. }
  39978. PredicateCondition.prototype.isValid = function () {
  39979. return this.predicate();
  39980. };
  39981. return PredicateCondition;
  39982. }(Condition));
  39983. BABYLON.PredicateCondition = PredicateCondition;
  39984. var StateCondition = (function (_super) {
  39985. __extends(StateCondition, _super);
  39986. function StateCondition(actionManager, target, value) {
  39987. var _this = _super.call(this, actionManager) || this;
  39988. _this.value = value;
  39989. _this._target = target;
  39990. return _this;
  39991. }
  39992. // Methods
  39993. StateCondition.prototype.isValid = function () {
  39994. return this._target.state === this.value;
  39995. };
  39996. StateCondition.prototype.serialize = function () {
  39997. return this._serialize({
  39998. name: "StateCondition",
  39999. properties: [
  40000. BABYLON.Action._GetTargetProperty(this._target),
  40001. { name: "value", value: this.value }
  40002. ]
  40003. });
  40004. };
  40005. return StateCondition;
  40006. }(Condition));
  40007. BABYLON.StateCondition = StateCondition;
  40008. })(BABYLON || (BABYLON = {}));
  40009. //# sourceMappingURL=babylon.condition.js.map
  40010. var BABYLON;
  40011. (function (BABYLON) {
  40012. var Action = (function () {
  40013. function Action(triggerOptions, condition) {
  40014. this.triggerOptions = triggerOptions;
  40015. this.onBeforeExecuteObservable = new BABYLON.Observable();
  40016. if (triggerOptions.parameter) {
  40017. this.trigger = triggerOptions.trigger;
  40018. this._triggerParameter = triggerOptions.parameter;
  40019. }
  40020. else {
  40021. this.trigger = triggerOptions;
  40022. }
  40023. this._nextActiveAction = this;
  40024. this._condition = condition;
  40025. }
  40026. // Methods
  40027. Action.prototype._prepare = function () {
  40028. };
  40029. Action.prototype.getTriggerParameter = function () {
  40030. return this._triggerParameter;
  40031. };
  40032. Action.prototype._executeCurrent = function (evt) {
  40033. if (this._nextActiveAction._condition) {
  40034. var condition = this._nextActiveAction._condition;
  40035. var currentRenderId = this._actionManager.getScene().getRenderId();
  40036. // We cache the current evaluation for the current frame
  40037. if (condition._evaluationId === currentRenderId) {
  40038. if (!condition._currentResult) {
  40039. return;
  40040. }
  40041. }
  40042. else {
  40043. condition._evaluationId = currentRenderId;
  40044. if (!condition.isValid()) {
  40045. condition._currentResult = false;
  40046. return;
  40047. }
  40048. condition._currentResult = true;
  40049. }
  40050. }
  40051. this.onBeforeExecuteObservable.notifyObservers(this);
  40052. this._nextActiveAction.execute(evt);
  40053. this.skipToNextActiveAction();
  40054. };
  40055. Action.prototype.execute = function (evt) {
  40056. };
  40057. Action.prototype.skipToNextActiveAction = function () {
  40058. if (this._nextActiveAction._child) {
  40059. if (!this._nextActiveAction._child._actionManager) {
  40060. this._nextActiveAction._child._actionManager = this._actionManager;
  40061. }
  40062. this._nextActiveAction = this._nextActiveAction._child;
  40063. }
  40064. else {
  40065. this._nextActiveAction = this;
  40066. }
  40067. };
  40068. Action.prototype.then = function (action) {
  40069. this._child = action;
  40070. action._actionManager = this._actionManager;
  40071. action._prepare();
  40072. return action;
  40073. };
  40074. Action.prototype._getProperty = function (propertyPath) {
  40075. return this._actionManager._getProperty(propertyPath);
  40076. };
  40077. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  40078. return this._actionManager._getEffectiveTarget(target, propertyPath);
  40079. };
  40080. Action.prototype.serialize = function (parent) {
  40081. };
  40082. // Called by BABYLON.Action objects in serialize(...). Internal use
  40083. Action.prototype._serialize = function (serializedAction, parent) {
  40084. var serializationObject = {
  40085. type: 1,
  40086. children: [],
  40087. name: serializedAction.name,
  40088. properties: serializedAction.properties || []
  40089. };
  40090. // Serialize child
  40091. if (this._child) {
  40092. this._child.serialize(serializationObject);
  40093. }
  40094. // Check if "this" has a condition
  40095. if (this._condition) {
  40096. var serializedCondition = this._condition.serialize();
  40097. serializedCondition.children.push(serializationObject);
  40098. if (parent) {
  40099. parent.children.push(serializedCondition);
  40100. }
  40101. return serializedCondition;
  40102. }
  40103. if (parent) {
  40104. parent.children.push(serializationObject);
  40105. }
  40106. return serializationObject;
  40107. };
  40108. Action._SerializeValueAsString = function (value) {
  40109. if (typeof value === "number") {
  40110. return value.toString();
  40111. }
  40112. if (typeof value === "boolean") {
  40113. return value ? "true" : "false";
  40114. }
  40115. if (value instanceof BABYLON.Vector2) {
  40116. return value.x + ", " + value.y;
  40117. }
  40118. if (value instanceof BABYLON.Vector3) {
  40119. return value.x + ", " + value.y + ", " + value.z;
  40120. }
  40121. if (value instanceof BABYLON.Color3) {
  40122. return value.r + ", " + value.g + ", " + value.b;
  40123. }
  40124. if (value instanceof BABYLON.Color4) {
  40125. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  40126. }
  40127. return value; // string
  40128. };
  40129. Action._GetTargetProperty = function (target) {
  40130. return {
  40131. name: "target",
  40132. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  40133. : target instanceof BABYLON.Light ? "LightProperties"
  40134. : target instanceof BABYLON.Camera ? "CameraProperties"
  40135. : "SceneProperties",
  40136. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  40137. };
  40138. };
  40139. return Action;
  40140. }());
  40141. BABYLON.Action = Action;
  40142. })(BABYLON || (BABYLON = {}));
  40143. //# sourceMappingURL=babylon.action.js.map
  40144. var BABYLON;
  40145. (function (BABYLON) {
  40146. /**
  40147. * ActionEvent is the event beint sent when an action is triggered.
  40148. */
  40149. var ActionEvent = (function () {
  40150. /**
  40151. * @param source The mesh or sprite that triggered the action.
  40152. * @param pointerX The X mouse cursor position at the time of the event
  40153. * @param pointerY The Y mouse cursor position at the time of the event
  40154. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  40155. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  40156. */
  40157. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  40158. this.source = source;
  40159. this.pointerX = pointerX;
  40160. this.pointerY = pointerY;
  40161. this.meshUnderPointer = meshUnderPointer;
  40162. this.sourceEvent = sourceEvent;
  40163. this.additionalData = additionalData;
  40164. }
  40165. /**
  40166. * Helper function to auto-create an ActionEvent from a source mesh.
  40167. * @param source The source mesh that triggered the event
  40168. * @param evt {Event} The original (browser) event
  40169. */
  40170. ActionEvent.CreateNew = function (source, evt, additionalData) {
  40171. var scene = source.getScene();
  40172. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  40173. };
  40174. /**
  40175. * Helper function to auto-create an ActionEvent from a source mesh.
  40176. * @param source The source sprite that triggered the event
  40177. * @param scene Scene associated with the sprite
  40178. * @param evt {Event} The original (browser) event
  40179. */
  40180. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  40181. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  40182. };
  40183. /**
  40184. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  40185. * @param scene the scene where the event occurred
  40186. * @param evt {Event} The original (browser) event
  40187. */
  40188. ActionEvent.CreateNewFromScene = function (scene, evt) {
  40189. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  40190. };
  40191. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  40192. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  40193. };
  40194. return ActionEvent;
  40195. }());
  40196. BABYLON.ActionEvent = ActionEvent;
  40197. /**
  40198. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  40199. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  40200. */
  40201. var ActionManager = (function () {
  40202. function ActionManager(scene) {
  40203. // Members
  40204. this.actions = new Array();
  40205. this.hoverCursor = '';
  40206. this._scene = scene;
  40207. scene._actionManagers.push(this);
  40208. }
  40209. Object.defineProperty(ActionManager, "NothingTrigger", {
  40210. get: function () {
  40211. return ActionManager._NothingTrigger;
  40212. },
  40213. enumerable: true,
  40214. configurable: true
  40215. });
  40216. Object.defineProperty(ActionManager, "OnPickTrigger", {
  40217. get: function () {
  40218. return ActionManager._OnPickTrigger;
  40219. },
  40220. enumerable: true,
  40221. configurable: true
  40222. });
  40223. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  40224. get: function () {
  40225. return ActionManager._OnLeftPickTrigger;
  40226. },
  40227. enumerable: true,
  40228. configurable: true
  40229. });
  40230. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  40231. get: function () {
  40232. return ActionManager._OnRightPickTrigger;
  40233. },
  40234. enumerable: true,
  40235. configurable: true
  40236. });
  40237. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  40238. get: function () {
  40239. return ActionManager._OnCenterPickTrigger;
  40240. },
  40241. enumerable: true,
  40242. configurable: true
  40243. });
  40244. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  40245. get: function () {
  40246. return ActionManager._OnPickDownTrigger;
  40247. },
  40248. enumerable: true,
  40249. configurable: true
  40250. });
  40251. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  40252. get: function () {
  40253. return ActionManager._OnDoublePickTrigger;
  40254. },
  40255. enumerable: true,
  40256. configurable: true
  40257. });
  40258. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  40259. get: function () {
  40260. return ActionManager._OnPickUpTrigger;
  40261. },
  40262. enumerable: true,
  40263. configurable: true
  40264. });
  40265. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  40266. /// This trigger will only be raised if you also declared a OnPickDown
  40267. get: function () {
  40268. return ActionManager._OnPickOutTrigger;
  40269. },
  40270. enumerable: true,
  40271. configurable: true
  40272. });
  40273. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  40274. get: function () {
  40275. return ActionManager._OnLongPressTrigger;
  40276. },
  40277. enumerable: true,
  40278. configurable: true
  40279. });
  40280. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  40281. get: function () {
  40282. return ActionManager._OnPointerOverTrigger;
  40283. },
  40284. enumerable: true,
  40285. configurable: true
  40286. });
  40287. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  40288. get: function () {
  40289. return ActionManager._OnPointerOutTrigger;
  40290. },
  40291. enumerable: true,
  40292. configurable: true
  40293. });
  40294. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  40295. get: function () {
  40296. return ActionManager._OnEveryFrameTrigger;
  40297. },
  40298. enumerable: true,
  40299. configurable: true
  40300. });
  40301. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  40302. get: function () {
  40303. return ActionManager._OnIntersectionEnterTrigger;
  40304. },
  40305. enumerable: true,
  40306. configurable: true
  40307. });
  40308. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  40309. get: function () {
  40310. return ActionManager._OnIntersectionExitTrigger;
  40311. },
  40312. enumerable: true,
  40313. configurable: true
  40314. });
  40315. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  40316. get: function () {
  40317. return ActionManager._OnKeyDownTrigger;
  40318. },
  40319. enumerable: true,
  40320. configurable: true
  40321. });
  40322. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  40323. get: function () {
  40324. return ActionManager._OnKeyUpTrigger;
  40325. },
  40326. enumerable: true,
  40327. configurable: true
  40328. });
  40329. // Methods
  40330. ActionManager.prototype.dispose = function () {
  40331. var index = this._scene._actionManagers.indexOf(this);
  40332. for (var i = 0; i < this.actions.length; i++) {
  40333. var action = this.actions[i];
  40334. ActionManager.Triggers[action.trigger]--;
  40335. if (ActionManager.Triggers[action.trigger] === 0) {
  40336. delete ActionManager.Triggers[action.trigger];
  40337. }
  40338. }
  40339. if (index > -1) {
  40340. this._scene._actionManagers.splice(index, 1);
  40341. }
  40342. };
  40343. ActionManager.prototype.getScene = function () {
  40344. return this._scene;
  40345. };
  40346. /**
  40347. * Does this action manager handles actions of any of the given triggers
  40348. * @param {number[]} triggers - the triggers to be tested
  40349. * @return {boolean} whether one (or more) of the triggers is handeled
  40350. */
  40351. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  40352. for (var index = 0; index < this.actions.length; index++) {
  40353. var action = this.actions[index];
  40354. if (triggers.indexOf(action.trigger) > -1) {
  40355. return true;
  40356. }
  40357. }
  40358. return false;
  40359. };
  40360. /**
  40361. * Does this action manager handles actions of a given trigger
  40362. * @param {number} trigger - the trigger to be tested
  40363. * @return {boolean} whether the trigger is handeled
  40364. */
  40365. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  40366. for (var index = 0; index < this.actions.length; index++) {
  40367. var action = this.actions[index];
  40368. if (action.trigger === trigger) {
  40369. return true;
  40370. }
  40371. }
  40372. return false;
  40373. };
  40374. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  40375. /**
  40376. * Does this action manager has pointer triggers
  40377. * @return {boolean} whether or not it has pointer triggers
  40378. */
  40379. get: function () {
  40380. for (var index = 0; index < this.actions.length; index++) {
  40381. var action = this.actions[index];
  40382. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  40383. return true;
  40384. }
  40385. }
  40386. return false;
  40387. },
  40388. enumerable: true,
  40389. configurable: true
  40390. });
  40391. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  40392. /**
  40393. * Does this action manager has pick triggers
  40394. * @return {boolean} whether or not it has pick triggers
  40395. */
  40396. get: function () {
  40397. for (var index = 0; index < this.actions.length; index++) {
  40398. var action = this.actions[index];
  40399. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  40400. return true;
  40401. }
  40402. }
  40403. return false;
  40404. },
  40405. enumerable: true,
  40406. configurable: true
  40407. });
  40408. Object.defineProperty(ActionManager, "HasTriggers", {
  40409. /**
  40410. * Does exist one action manager with at least one trigger
  40411. * @return {boolean} whether or not it exists one action manager with one trigger
  40412. **/
  40413. get: function () {
  40414. for (var t in ActionManager.Triggers) {
  40415. if (ActionManager.Triggers.hasOwnProperty(t)) {
  40416. return true;
  40417. }
  40418. }
  40419. return false;
  40420. },
  40421. enumerable: true,
  40422. configurable: true
  40423. });
  40424. Object.defineProperty(ActionManager, "HasPickTriggers", {
  40425. /**
  40426. * Does exist one action manager with at least one pick trigger
  40427. * @return {boolean} whether or not it exists one action manager with one pick trigger
  40428. **/
  40429. get: function () {
  40430. for (var t in ActionManager.Triggers) {
  40431. if (ActionManager.Triggers.hasOwnProperty(t)) {
  40432. var t_int = parseInt(t);
  40433. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  40434. return true;
  40435. }
  40436. }
  40437. }
  40438. return false;
  40439. },
  40440. enumerable: true,
  40441. configurable: true
  40442. });
  40443. /**
  40444. * Does exist one action manager that handles actions of a given trigger
  40445. * @param {number} trigger - the trigger to be tested
  40446. * @return {boolean} whether the trigger is handeled by at least one action manager
  40447. **/
  40448. ActionManager.HasSpecificTrigger = function (trigger) {
  40449. for (var t in ActionManager.Triggers) {
  40450. if (ActionManager.Triggers.hasOwnProperty(t)) {
  40451. var t_int = parseInt(t);
  40452. if (t_int === trigger) {
  40453. return true;
  40454. }
  40455. }
  40456. }
  40457. return false;
  40458. };
  40459. /**
  40460. * Registers an action to this action manager
  40461. * @param {BABYLON.Action} action - the action to be registered
  40462. * @return {BABYLON.Action} the action amended (prepared) after registration
  40463. */
  40464. ActionManager.prototype.registerAction = function (action) {
  40465. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  40466. if (this.getScene().actionManager !== this) {
  40467. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  40468. return null;
  40469. }
  40470. }
  40471. this.actions.push(action);
  40472. if (ActionManager.Triggers[action.trigger]) {
  40473. ActionManager.Triggers[action.trigger]++;
  40474. }
  40475. else {
  40476. ActionManager.Triggers[action.trigger] = 1;
  40477. }
  40478. action._actionManager = this;
  40479. action._prepare();
  40480. return action;
  40481. };
  40482. /**
  40483. * Process a specific trigger
  40484. * @param {number} trigger - the trigger to process
  40485. * @param evt {BABYLON.ActionEvent} the event details to be processed
  40486. */
  40487. ActionManager.prototype.processTrigger = function (trigger, evt) {
  40488. for (var index = 0; index < this.actions.length; index++) {
  40489. var action = this.actions[index];
  40490. if (action.trigger === trigger) {
  40491. if (trigger === ActionManager.OnKeyUpTrigger
  40492. || trigger === ActionManager.OnKeyDownTrigger) {
  40493. var parameter = action.getTriggerParameter();
  40494. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  40495. if (!parameter.toLowerCase) {
  40496. continue;
  40497. }
  40498. var lowerCase = parameter.toLowerCase();
  40499. if (lowerCase !== evt.sourceEvent.key) {
  40500. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  40501. var actualkey = String.fromCharCode(unicode).toLowerCase();
  40502. if (actualkey !== lowerCase) {
  40503. continue;
  40504. }
  40505. }
  40506. }
  40507. }
  40508. action._executeCurrent(evt);
  40509. }
  40510. }
  40511. };
  40512. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  40513. var properties = propertyPath.split(".");
  40514. for (var index = 0; index < properties.length - 1; index++) {
  40515. target = target[properties[index]];
  40516. }
  40517. return target;
  40518. };
  40519. ActionManager.prototype._getProperty = function (propertyPath) {
  40520. var properties = propertyPath.split(".");
  40521. return properties[properties.length - 1];
  40522. };
  40523. ActionManager.prototype.serialize = function (name) {
  40524. var root = {
  40525. children: new Array(),
  40526. name: name,
  40527. type: 3,
  40528. properties: new Array() // Empty for root but required
  40529. };
  40530. for (var i = 0; i < this.actions.length; i++) {
  40531. var triggerObject = {
  40532. type: 0,
  40533. children: new Array(),
  40534. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  40535. properties: new Array()
  40536. };
  40537. var triggerOptions = this.actions[i].triggerOptions;
  40538. if (triggerOptions && typeof triggerOptions !== "number") {
  40539. if (triggerOptions.parameter instanceof BABYLON.Node) {
  40540. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  40541. }
  40542. else {
  40543. var parameter = {};
  40544. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  40545. if (triggerOptions.parameter.mesh) {
  40546. parameter._meshId = triggerOptions.parameter.mesh.id;
  40547. }
  40548. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  40549. }
  40550. }
  40551. // Serialize child action, recursively
  40552. this.actions[i].serialize(triggerObject);
  40553. // Add serialized trigger
  40554. root.children.push(triggerObject);
  40555. }
  40556. return root;
  40557. };
  40558. ActionManager.Parse = function (parsedActions, object, scene) {
  40559. var actionManager = new BABYLON.ActionManager(scene);
  40560. if (object === null)
  40561. scene.actionManager = actionManager;
  40562. else
  40563. object.actionManager = actionManager;
  40564. // instanciate a new object
  40565. var instanciate = function (name, params) {
  40566. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  40567. newInstance.constructor.apply(newInstance, params);
  40568. return newInstance;
  40569. };
  40570. var parseParameter = function (name, value, target, propertyPath) {
  40571. if (propertyPath === null) {
  40572. // String, boolean or float
  40573. var floatValue = parseFloat(value);
  40574. if (value === "true" || value === "false")
  40575. return value === "true";
  40576. else
  40577. return isNaN(floatValue) ? value : floatValue;
  40578. }
  40579. var effectiveTarget = propertyPath.split(".");
  40580. var values = value.split(",");
  40581. // Get effective Target
  40582. for (var i = 0; i < effectiveTarget.length; i++) {
  40583. target = target[effectiveTarget[i]];
  40584. }
  40585. // Return appropriate value with its type
  40586. if (typeof (target) === "boolean")
  40587. return values[0] === "true";
  40588. if (typeof (target) === "string")
  40589. return values[0];
  40590. // Parameters with multiple values such as Vector3 etc.
  40591. var split = new Array();
  40592. for (var i = 0; i < values.length; i++)
  40593. split.push(parseFloat(values[i]));
  40594. if (target instanceof BABYLON.Vector3)
  40595. return BABYLON.Vector3.FromArray(split);
  40596. if (target instanceof BABYLON.Vector4)
  40597. return BABYLON.Vector4.FromArray(split);
  40598. if (target instanceof BABYLON.Color3)
  40599. return BABYLON.Color3.FromArray(split);
  40600. if (target instanceof BABYLON.Color4)
  40601. return BABYLON.Color4.FromArray(split);
  40602. return parseFloat(values[0]);
  40603. };
  40604. // traverse graph per trigger
  40605. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  40606. if (combineArray === void 0) { combineArray = null; }
  40607. if (parsedAction.detached)
  40608. return;
  40609. var parameters = new Array();
  40610. var target = null;
  40611. var propertyPath = null;
  40612. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  40613. // Parameters
  40614. if (parsedAction.type === 2)
  40615. parameters.push(actionManager);
  40616. else
  40617. parameters.push(trigger);
  40618. if (combine) {
  40619. var actions = new Array();
  40620. for (var j = 0; j < parsedAction.combine.length; j++) {
  40621. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  40622. }
  40623. parameters.push(actions);
  40624. }
  40625. else {
  40626. for (var i = 0; i < parsedAction.properties.length; i++) {
  40627. var value = parsedAction.properties[i].value;
  40628. var name = parsedAction.properties[i].name;
  40629. var targetType = parsedAction.properties[i].targetType;
  40630. if (name === "target")
  40631. if (targetType !== null && targetType === "SceneProperties")
  40632. value = target = scene;
  40633. else
  40634. value = target = scene.getNodeByName(value);
  40635. else if (name === "parent")
  40636. value = scene.getNodeByName(value);
  40637. else if (name === "sound")
  40638. value = scene.getSoundByName(value);
  40639. else if (name !== "propertyPath") {
  40640. if (parsedAction.type === 2 && name === "operator")
  40641. value = BABYLON.ValueCondition[value];
  40642. else
  40643. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  40644. }
  40645. else {
  40646. propertyPath = value;
  40647. }
  40648. parameters.push(value);
  40649. }
  40650. }
  40651. if (combineArray === null) {
  40652. parameters.push(condition);
  40653. }
  40654. else {
  40655. parameters.push(null);
  40656. }
  40657. // If interpolate value action
  40658. if (parsedAction.name === "InterpolateValueAction") {
  40659. var param = parameters[parameters.length - 2];
  40660. parameters[parameters.length - 1] = param;
  40661. parameters[parameters.length - 2] = condition;
  40662. }
  40663. // Action or condition(s) and not CombineAction
  40664. var newAction = instanciate(parsedAction.name, parameters);
  40665. if (newAction instanceof BABYLON.Condition && condition !== null) {
  40666. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  40667. if (action)
  40668. action.then(nothing);
  40669. else
  40670. actionManager.registerAction(nothing);
  40671. action = nothing;
  40672. }
  40673. if (combineArray === null) {
  40674. if (newAction instanceof BABYLON.Condition) {
  40675. condition = newAction;
  40676. newAction = action;
  40677. }
  40678. else {
  40679. condition = null;
  40680. if (action)
  40681. action.then(newAction);
  40682. else
  40683. actionManager.registerAction(newAction);
  40684. }
  40685. }
  40686. else {
  40687. combineArray.push(newAction);
  40688. }
  40689. for (var i = 0; i < parsedAction.children.length; i++)
  40690. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  40691. };
  40692. // triggers
  40693. for (var i = 0; i < parsedActions.children.length; i++) {
  40694. var triggerParams;
  40695. var trigger = parsedActions.children[i];
  40696. if (trigger.properties.length > 0) {
  40697. var param = trigger.properties[0].value;
  40698. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  40699. if (value._meshId) {
  40700. value.mesh = scene.getMeshByID(value._meshId);
  40701. }
  40702. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  40703. }
  40704. else
  40705. triggerParams = ActionManager[trigger.name];
  40706. for (var j = 0; j < trigger.children.length; j++) {
  40707. if (!trigger.detached)
  40708. traverse(trigger.children[j], triggerParams, null, null);
  40709. }
  40710. }
  40711. };
  40712. ActionManager.GetTriggerName = function (trigger) {
  40713. switch (trigger) {
  40714. case 0: return "NothingTrigger";
  40715. case 1: return "OnPickTrigger";
  40716. case 2: return "OnLeftPickTrigger";
  40717. case 3: return "OnRightPickTrigger";
  40718. case 4: return "OnCenterPickTrigger";
  40719. case 5: return "OnPickDownTrigger";
  40720. case 6: return "OnPickUpTrigger";
  40721. case 7: return "OnLongPressTrigger";
  40722. case 8: return "OnPointerOverTrigger";
  40723. case 9: return "OnPointerOutTrigger";
  40724. case 10: return "OnEveryFrameTrigger";
  40725. case 11: return "OnIntersectionEnterTrigger";
  40726. case 12: return "OnIntersectionExitTrigger";
  40727. case 13: return "OnKeyDownTrigger";
  40728. case 14: return "OnKeyUpTrigger";
  40729. case 15: return "OnPickOutTrigger";
  40730. default: return "";
  40731. }
  40732. };
  40733. // Statics
  40734. ActionManager._NothingTrigger = 0;
  40735. ActionManager._OnPickTrigger = 1;
  40736. ActionManager._OnLeftPickTrigger = 2;
  40737. ActionManager._OnRightPickTrigger = 3;
  40738. ActionManager._OnCenterPickTrigger = 4;
  40739. ActionManager._OnPickDownTrigger = 5;
  40740. ActionManager._OnDoublePickTrigger = 6;
  40741. ActionManager._OnPickUpTrigger = 7;
  40742. ActionManager._OnLongPressTrigger = 8;
  40743. ActionManager._OnPointerOverTrigger = 9;
  40744. ActionManager._OnPointerOutTrigger = 10;
  40745. ActionManager._OnEveryFrameTrigger = 11;
  40746. ActionManager._OnIntersectionEnterTrigger = 12;
  40747. ActionManager._OnIntersectionExitTrigger = 13;
  40748. ActionManager._OnKeyDownTrigger = 14;
  40749. ActionManager._OnKeyUpTrigger = 15;
  40750. ActionManager._OnPickOutTrigger = 16;
  40751. ActionManager.Triggers = {};
  40752. return ActionManager;
  40753. }());
  40754. BABYLON.ActionManager = ActionManager;
  40755. })(BABYLON || (BABYLON = {}));
  40756. //# sourceMappingURL=babylon.actionManager.js.map
  40757. var BABYLON;
  40758. (function (BABYLON) {
  40759. var InterpolateValueAction = (function (_super) {
  40760. __extends(InterpolateValueAction, _super);
  40761. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  40762. if (duration === void 0) { duration = 1000; }
  40763. var _this = _super.call(this, triggerOptions, condition) || this;
  40764. _this.propertyPath = propertyPath;
  40765. _this.value = value;
  40766. _this.duration = duration;
  40767. _this.stopOtherAnimations = stopOtherAnimations;
  40768. _this.onInterpolationDone = onInterpolationDone;
  40769. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  40770. _this._target = _this._effectiveTarget = target;
  40771. return _this;
  40772. }
  40773. InterpolateValueAction.prototype._prepare = function () {
  40774. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40775. this._property = this._getProperty(this.propertyPath);
  40776. };
  40777. InterpolateValueAction.prototype.execute = function () {
  40778. var _this = this;
  40779. var scene = this._actionManager.getScene();
  40780. var keys = [
  40781. {
  40782. frame: 0,
  40783. value: this._effectiveTarget[this._property]
  40784. }, {
  40785. frame: 100,
  40786. value: this.value
  40787. }
  40788. ];
  40789. var dataType;
  40790. if (typeof this.value === "number") {
  40791. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  40792. }
  40793. else if (this.value instanceof BABYLON.Color3) {
  40794. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  40795. }
  40796. else if (this.value instanceof BABYLON.Vector3) {
  40797. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  40798. }
  40799. else if (this.value instanceof BABYLON.Matrix) {
  40800. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  40801. }
  40802. else if (this.value instanceof BABYLON.Quaternion) {
  40803. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  40804. }
  40805. else {
  40806. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  40807. return;
  40808. }
  40809. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  40810. animation.setKeys(keys);
  40811. if (this.stopOtherAnimations) {
  40812. scene.stopAnimation(this._effectiveTarget);
  40813. }
  40814. var wrapper = function () {
  40815. _this.onInterpolationDoneObservable.notifyObservers(_this);
  40816. if (_this.onInterpolationDone) {
  40817. _this.onInterpolationDone();
  40818. }
  40819. };
  40820. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  40821. };
  40822. InterpolateValueAction.prototype.serialize = function (parent) {
  40823. return _super.prototype._serialize.call(this, {
  40824. name: "InterpolateValueAction",
  40825. properties: [
  40826. BABYLON.Action._GetTargetProperty(this._target),
  40827. { name: "propertyPath", value: this.propertyPath },
  40828. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  40829. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  40830. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  40831. ]
  40832. }, parent);
  40833. };
  40834. return InterpolateValueAction;
  40835. }(BABYLON.Action));
  40836. BABYLON.InterpolateValueAction = InterpolateValueAction;
  40837. })(BABYLON || (BABYLON = {}));
  40838. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  40839. var BABYLON;
  40840. (function (BABYLON) {
  40841. var SwitchBooleanAction = (function (_super) {
  40842. __extends(SwitchBooleanAction, _super);
  40843. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  40844. var _this = _super.call(this, triggerOptions, condition) || this;
  40845. _this.propertyPath = propertyPath;
  40846. _this._target = _this._effectiveTarget = target;
  40847. return _this;
  40848. }
  40849. SwitchBooleanAction.prototype._prepare = function () {
  40850. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40851. this._property = this._getProperty(this.propertyPath);
  40852. };
  40853. SwitchBooleanAction.prototype.execute = function () {
  40854. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  40855. };
  40856. SwitchBooleanAction.prototype.serialize = function (parent) {
  40857. return _super.prototype._serialize.call(this, {
  40858. name: "SwitchBooleanAction",
  40859. properties: [
  40860. BABYLON.Action._GetTargetProperty(this._target),
  40861. { name: "propertyPath", value: this.propertyPath }
  40862. ]
  40863. }, parent);
  40864. };
  40865. return SwitchBooleanAction;
  40866. }(BABYLON.Action));
  40867. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  40868. var SetStateAction = (function (_super) {
  40869. __extends(SetStateAction, _super);
  40870. function SetStateAction(triggerOptions, target, value, condition) {
  40871. var _this = _super.call(this, triggerOptions, condition) || this;
  40872. _this.value = value;
  40873. _this._target = target;
  40874. return _this;
  40875. }
  40876. SetStateAction.prototype.execute = function () {
  40877. this._target.state = this.value;
  40878. };
  40879. SetStateAction.prototype.serialize = function (parent) {
  40880. return _super.prototype._serialize.call(this, {
  40881. name: "SetStateAction",
  40882. properties: [
  40883. BABYLON.Action._GetTargetProperty(this._target),
  40884. { name: "value", value: this.value }
  40885. ]
  40886. }, parent);
  40887. };
  40888. return SetStateAction;
  40889. }(BABYLON.Action));
  40890. BABYLON.SetStateAction = SetStateAction;
  40891. var SetValueAction = (function (_super) {
  40892. __extends(SetValueAction, _super);
  40893. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  40894. var _this = _super.call(this, triggerOptions, condition) || this;
  40895. _this.propertyPath = propertyPath;
  40896. _this.value = value;
  40897. _this._target = _this._effectiveTarget = target;
  40898. return _this;
  40899. }
  40900. SetValueAction.prototype._prepare = function () {
  40901. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40902. this._property = this._getProperty(this.propertyPath);
  40903. };
  40904. SetValueAction.prototype.execute = function () {
  40905. this._effectiveTarget[this._property] = this.value;
  40906. if (this._target.markAsDirty) {
  40907. this._target.markAsDirty(this._property);
  40908. }
  40909. };
  40910. SetValueAction.prototype.serialize = function (parent) {
  40911. return _super.prototype._serialize.call(this, {
  40912. name: "SetValueAction",
  40913. properties: [
  40914. BABYLON.Action._GetTargetProperty(this._target),
  40915. { name: "propertyPath", value: this.propertyPath },
  40916. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  40917. ]
  40918. }, parent);
  40919. };
  40920. return SetValueAction;
  40921. }(BABYLON.Action));
  40922. BABYLON.SetValueAction = SetValueAction;
  40923. var IncrementValueAction = (function (_super) {
  40924. __extends(IncrementValueAction, _super);
  40925. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  40926. var _this = _super.call(this, triggerOptions, condition) || this;
  40927. _this.propertyPath = propertyPath;
  40928. _this.value = value;
  40929. _this._target = _this._effectiveTarget = target;
  40930. return _this;
  40931. }
  40932. IncrementValueAction.prototype._prepare = function () {
  40933. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40934. this._property = this._getProperty(this.propertyPath);
  40935. if (typeof this._effectiveTarget[this._property] !== "number") {
  40936. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  40937. }
  40938. };
  40939. IncrementValueAction.prototype.execute = function () {
  40940. this._effectiveTarget[this._property] += this.value;
  40941. if (this._target.markAsDirty) {
  40942. this._target.markAsDirty(this._property);
  40943. }
  40944. };
  40945. IncrementValueAction.prototype.serialize = function (parent) {
  40946. return _super.prototype._serialize.call(this, {
  40947. name: "IncrementValueAction",
  40948. properties: [
  40949. BABYLON.Action._GetTargetProperty(this._target),
  40950. { name: "propertyPath", value: this.propertyPath },
  40951. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  40952. ]
  40953. }, parent);
  40954. };
  40955. return IncrementValueAction;
  40956. }(BABYLON.Action));
  40957. BABYLON.IncrementValueAction = IncrementValueAction;
  40958. var PlayAnimationAction = (function (_super) {
  40959. __extends(PlayAnimationAction, _super);
  40960. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  40961. var _this = _super.call(this, triggerOptions, condition) || this;
  40962. _this.from = from;
  40963. _this.to = to;
  40964. _this.loop = loop;
  40965. _this._target = target;
  40966. return _this;
  40967. }
  40968. PlayAnimationAction.prototype._prepare = function () {
  40969. };
  40970. PlayAnimationAction.prototype.execute = function () {
  40971. var scene = this._actionManager.getScene();
  40972. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  40973. };
  40974. PlayAnimationAction.prototype.serialize = function (parent) {
  40975. return _super.prototype._serialize.call(this, {
  40976. name: "PlayAnimationAction",
  40977. properties: [
  40978. BABYLON.Action._GetTargetProperty(this._target),
  40979. { name: "from", value: String(this.from) },
  40980. { name: "to", value: String(this.to) },
  40981. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  40982. ]
  40983. }, parent);
  40984. };
  40985. return PlayAnimationAction;
  40986. }(BABYLON.Action));
  40987. BABYLON.PlayAnimationAction = PlayAnimationAction;
  40988. var StopAnimationAction = (function (_super) {
  40989. __extends(StopAnimationAction, _super);
  40990. function StopAnimationAction(triggerOptions, target, condition) {
  40991. var _this = _super.call(this, triggerOptions, condition) || this;
  40992. _this._target = target;
  40993. return _this;
  40994. }
  40995. StopAnimationAction.prototype._prepare = function () {
  40996. };
  40997. StopAnimationAction.prototype.execute = function () {
  40998. var scene = this._actionManager.getScene();
  40999. scene.stopAnimation(this._target);
  41000. };
  41001. StopAnimationAction.prototype.serialize = function (parent) {
  41002. return _super.prototype._serialize.call(this, {
  41003. name: "StopAnimationAction",
  41004. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  41005. }, parent);
  41006. };
  41007. return StopAnimationAction;
  41008. }(BABYLON.Action));
  41009. BABYLON.StopAnimationAction = StopAnimationAction;
  41010. var DoNothingAction = (function (_super) {
  41011. __extends(DoNothingAction, _super);
  41012. function DoNothingAction(triggerOptions, condition) {
  41013. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  41014. return _super.call(this, triggerOptions, condition) || this;
  41015. }
  41016. DoNothingAction.prototype.execute = function () {
  41017. };
  41018. DoNothingAction.prototype.serialize = function (parent) {
  41019. return _super.prototype._serialize.call(this, {
  41020. name: "DoNothingAction",
  41021. properties: []
  41022. }, parent);
  41023. };
  41024. return DoNothingAction;
  41025. }(BABYLON.Action));
  41026. BABYLON.DoNothingAction = DoNothingAction;
  41027. var CombineAction = (function (_super) {
  41028. __extends(CombineAction, _super);
  41029. function CombineAction(triggerOptions, children, condition) {
  41030. var _this = _super.call(this, triggerOptions, condition) || this;
  41031. _this.children = children;
  41032. return _this;
  41033. }
  41034. CombineAction.prototype._prepare = function () {
  41035. for (var index = 0; index < this.children.length; index++) {
  41036. this.children[index]._actionManager = this._actionManager;
  41037. this.children[index]._prepare();
  41038. }
  41039. };
  41040. CombineAction.prototype.execute = function (evt) {
  41041. for (var index = 0; index < this.children.length; index++) {
  41042. this.children[index].execute(evt);
  41043. }
  41044. };
  41045. CombineAction.prototype.serialize = function (parent) {
  41046. var serializationObject = _super.prototype._serialize.call(this, {
  41047. name: "CombineAction",
  41048. properties: [],
  41049. combine: []
  41050. }, parent);
  41051. for (var i = 0; i < this.children.length; i++) {
  41052. serializationObject.combine.push(this.children[i].serialize(null));
  41053. }
  41054. return serializationObject;
  41055. };
  41056. return CombineAction;
  41057. }(BABYLON.Action));
  41058. BABYLON.CombineAction = CombineAction;
  41059. var ExecuteCodeAction = (function (_super) {
  41060. __extends(ExecuteCodeAction, _super);
  41061. function ExecuteCodeAction(triggerOptions, func, condition) {
  41062. var _this = _super.call(this, triggerOptions, condition) || this;
  41063. _this.func = func;
  41064. return _this;
  41065. }
  41066. ExecuteCodeAction.prototype.execute = function (evt) {
  41067. this.func(evt);
  41068. };
  41069. return ExecuteCodeAction;
  41070. }(BABYLON.Action));
  41071. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  41072. var SetParentAction = (function (_super) {
  41073. __extends(SetParentAction, _super);
  41074. function SetParentAction(triggerOptions, target, parent, condition) {
  41075. var _this = _super.call(this, triggerOptions, condition) || this;
  41076. _this._target = target;
  41077. _this._parent = parent;
  41078. return _this;
  41079. }
  41080. SetParentAction.prototype._prepare = function () {
  41081. };
  41082. SetParentAction.prototype.execute = function () {
  41083. if (this._target.parent === this._parent) {
  41084. return;
  41085. }
  41086. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  41087. invertParentWorldMatrix.invert();
  41088. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  41089. this._target.parent = this._parent;
  41090. };
  41091. SetParentAction.prototype.serialize = function (parent) {
  41092. return _super.prototype._serialize.call(this, {
  41093. name: "SetParentAction",
  41094. properties: [
  41095. BABYLON.Action._GetTargetProperty(this._target),
  41096. BABYLON.Action._GetTargetProperty(this._parent),
  41097. ]
  41098. }, parent);
  41099. };
  41100. return SetParentAction;
  41101. }(BABYLON.Action));
  41102. BABYLON.SetParentAction = SetParentAction;
  41103. var PlaySoundAction = (function (_super) {
  41104. __extends(PlaySoundAction, _super);
  41105. function PlaySoundAction(triggerOptions, sound, condition) {
  41106. var _this = _super.call(this, triggerOptions, condition) || this;
  41107. _this._sound = sound;
  41108. return _this;
  41109. }
  41110. PlaySoundAction.prototype._prepare = function () {
  41111. };
  41112. PlaySoundAction.prototype.execute = function () {
  41113. if (this._sound !== undefined)
  41114. this._sound.play();
  41115. };
  41116. PlaySoundAction.prototype.serialize = function (parent) {
  41117. return _super.prototype._serialize.call(this, {
  41118. name: "PlaySoundAction",
  41119. properties: [{ name: "sound", value: this._sound.name }]
  41120. }, parent);
  41121. };
  41122. return PlaySoundAction;
  41123. }(BABYLON.Action));
  41124. BABYLON.PlaySoundAction = PlaySoundAction;
  41125. var StopSoundAction = (function (_super) {
  41126. __extends(StopSoundAction, _super);
  41127. function StopSoundAction(triggerOptions, sound, condition) {
  41128. var _this = _super.call(this, triggerOptions, condition) || this;
  41129. _this._sound = sound;
  41130. return _this;
  41131. }
  41132. StopSoundAction.prototype._prepare = function () {
  41133. };
  41134. StopSoundAction.prototype.execute = function () {
  41135. if (this._sound !== undefined)
  41136. this._sound.stop();
  41137. };
  41138. StopSoundAction.prototype.serialize = function (parent) {
  41139. return _super.prototype._serialize.call(this, {
  41140. name: "StopSoundAction",
  41141. properties: [{ name: "sound", value: this._sound.name }]
  41142. }, parent);
  41143. };
  41144. return StopSoundAction;
  41145. }(BABYLON.Action));
  41146. BABYLON.StopSoundAction = StopSoundAction;
  41147. })(BABYLON || (BABYLON = {}));
  41148. //# sourceMappingURL=babylon.directActions.js.map
  41149. var BABYLON;
  41150. (function (BABYLON) {
  41151. var SpriteManager = (function () {
  41152. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  41153. if (epsilon === void 0) { epsilon = 0.01; }
  41154. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41155. this.name = name;
  41156. this.sprites = new Array();
  41157. this.renderingGroupId = 0;
  41158. this.layerMask = 0x0FFFFFFF;
  41159. this.fogEnabled = true;
  41160. this.isPickable = false;
  41161. /**
  41162. * An event triggered when the manager is disposed.
  41163. * @type {BABYLON.Observable}
  41164. */
  41165. this.onDisposeObservable = new BABYLON.Observable();
  41166. this._vertexBuffers = {};
  41167. this._capacity = capacity;
  41168. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  41169. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41170. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41171. if (cellSize.width && cellSize.height) {
  41172. this.cellWidth = cellSize.width;
  41173. this.cellHeight = cellSize.height;
  41174. }
  41175. else if (cellSize !== undefined) {
  41176. this.cellWidth = cellSize;
  41177. this.cellHeight = cellSize;
  41178. }
  41179. else {
  41180. return;
  41181. }
  41182. this._epsilon = epsilon;
  41183. this._scene = scene;
  41184. this._scene.spriteManagers.push(this);
  41185. var indices = [];
  41186. var index = 0;
  41187. for (var count = 0; count < capacity; count++) {
  41188. indices.push(index);
  41189. indices.push(index + 1);
  41190. indices.push(index + 2);
  41191. indices.push(index);
  41192. indices.push(index + 2);
  41193. indices.push(index + 3);
  41194. index += 4;
  41195. }
  41196. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  41197. // VBO
  41198. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  41199. this._vertexData = new Float32Array(capacity * 16 * 4);
  41200. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  41201. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  41202. var options = this._buffer.createVertexBuffer("options", 4, 4);
  41203. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  41204. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  41205. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  41206. this._vertexBuffers["options"] = options;
  41207. this._vertexBuffers["cellInfo"] = cellInfo;
  41208. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  41209. // Effects
  41210. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  41211. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  41212. }
  41213. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  41214. set: function (callback) {
  41215. if (this._onDisposeObserver) {
  41216. this.onDisposeObservable.remove(this._onDisposeObserver);
  41217. }
  41218. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  41219. },
  41220. enumerable: true,
  41221. configurable: true
  41222. });
  41223. Object.defineProperty(SpriteManager.prototype, "texture", {
  41224. get: function () {
  41225. return this._spriteTexture;
  41226. },
  41227. set: function (value) {
  41228. this._spriteTexture = value;
  41229. },
  41230. enumerable: true,
  41231. configurable: true
  41232. });
  41233. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  41234. var arrayOffset = index * 16;
  41235. if (offsetX === 0)
  41236. offsetX = this._epsilon;
  41237. else if (offsetX === 1)
  41238. offsetX = 1 - this._epsilon;
  41239. if (offsetY === 0)
  41240. offsetY = this._epsilon;
  41241. else if (offsetY === 1)
  41242. offsetY = 1 - this._epsilon;
  41243. this._vertexData[arrayOffset] = sprite.position.x;
  41244. this._vertexData[arrayOffset + 1] = sprite.position.y;
  41245. this._vertexData[arrayOffset + 2] = sprite.position.z;
  41246. this._vertexData[arrayOffset + 3] = sprite.angle;
  41247. this._vertexData[arrayOffset + 4] = sprite.width;
  41248. this._vertexData[arrayOffset + 5] = sprite.height;
  41249. this._vertexData[arrayOffset + 6] = offsetX;
  41250. this._vertexData[arrayOffset + 7] = offsetY;
  41251. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  41252. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  41253. var offset = (sprite.cellIndex / rowSize) >> 0;
  41254. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  41255. this._vertexData[arrayOffset + 11] = offset;
  41256. // Color
  41257. this._vertexData[arrayOffset + 12] = sprite.color.r;
  41258. this._vertexData[arrayOffset + 13] = sprite.color.g;
  41259. this._vertexData[arrayOffset + 14] = sprite.color.b;
  41260. this._vertexData[arrayOffset + 15] = sprite.color.a;
  41261. };
  41262. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  41263. var count = Math.min(this._capacity, this.sprites.length);
  41264. var min = BABYLON.Vector3.Zero();
  41265. var max = BABYLON.Vector3.Zero();
  41266. var distance = Number.MAX_VALUE;
  41267. var currentSprite;
  41268. var cameraSpacePosition = BABYLON.Vector3.Zero();
  41269. var cameraView = camera.getViewMatrix();
  41270. for (var index = 0; index < count; index++) {
  41271. var sprite = this.sprites[index];
  41272. if (!sprite) {
  41273. continue;
  41274. }
  41275. if (predicate) {
  41276. if (!predicate(sprite)) {
  41277. continue;
  41278. }
  41279. }
  41280. else if (!sprite.isPickable) {
  41281. continue;
  41282. }
  41283. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  41284. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  41285. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  41286. if (ray.intersectsBoxMinMax(min, max)) {
  41287. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  41288. if (distance > currentDistance) {
  41289. distance = currentDistance;
  41290. currentSprite = sprite;
  41291. if (fastCheck) {
  41292. break;
  41293. }
  41294. }
  41295. }
  41296. }
  41297. if (currentSprite) {
  41298. var result = new BABYLON.PickingInfo();
  41299. result.hit = true;
  41300. result.pickedSprite = currentSprite;
  41301. result.distance = distance;
  41302. return result;
  41303. }
  41304. return null;
  41305. };
  41306. SpriteManager.prototype.render = function () {
  41307. // Check
  41308. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  41309. return;
  41310. var engine = this._scene.getEngine();
  41311. var baseSize = this._spriteTexture.getBaseSize();
  41312. // Sprites
  41313. var deltaTime = engine.getDeltaTime();
  41314. var max = Math.min(this._capacity, this.sprites.length);
  41315. var rowSize = baseSize.width / this.cellWidth;
  41316. var offset = 0;
  41317. for (var index = 0; index < max; index++) {
  41318. var sprite = this.sprites[index];
  41319. if (!sprite) {
  41320. continue;
  41321. }
  41322. sprite._animate(deltaTime);
  41323. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  41324. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  41325. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  41326. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  41327. }
  41328. this._buffer.update(this._vertexData);
  41329. // Render
  41330. var effect = this._effectBase;
  41331. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  41332. effect = this._effectFog;
  41333. }
  41334. engine.enableEffect(effect);
  41335. var viewMatrix = this._scene.getViewMatrix();
  41336. effect.setTexture("diffuseSampler", this._spriteTexture);
  41337. effect.setMatrix("view", viewMatrix);
  41338. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  41339. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  41340. // Fog
  41341. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  41342. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  41343. effect.setColor3("vFogColor", this._scene.fogColor);
  41344. }
  41345. // VBOs
  41346. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  41347. // Draw order
  41348. engine.setDepthFunctionToLessOrEqual();
  41349. effect.setBool("alphaTest", true);
  41350. engine.setColorWrite(false);
  41351. engine.draw(true, 0, max * 6);
  41352. engine.setColorWrite(true);
  41353. effect.setBool("alphaTest", false);
  41354. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  41355. engine.draw(true, 0, max * 6);
  41356. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  41357. };
  41358. SpriteManager.prototype.dispose = function () {
  41359. if (this._buffer) {
  41360. this._buffer.dispose();
  41361. this._buffer = null;
  41362. }
  41363. if (this._indexBuffer) {
  41364. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  41365. this._indexBuffer = null;
  41366. }
  41367. if (this._spriteTexture) {
  41368. this._spriteTexture.dispose();
  41369. this._spriteTexture = null;
  41370. }
  41371. // Remove from scene
  41372. var index = this._scene.spriteManagers.indexOf(this);
  41373. this._scene.spriteManagers.splice(index, 1);
  41374. // Callback
  41375. this.onDisposeObservable.notifyObservers(this);
  41376. this.onDisposeObservable.clear();
  41377. };
  41378. return SpriteManager;
  41379. }());
  41380. BABYLON.SpriteManager = SpriteManager;
  41381. })(BABYLON || (BABYLON = {}));
  41382. //# sourceMappingURL=babylon.spriteManager.js.map
  41383. var BABYLON;
  41384. (function (BABYLON) {
  41385. var Sprite = (function () {
  41386. function Sprite(name, manager) {
  41387. this.name = name;
  41388. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  41389. this.width = 1.0;
  41390. this.height = 1.0;
  41391. this.angle = 0;
  41392. this.cellIndex = 0;
  41393. this.invertU = 0;
  41394. this.invertV = 0;
  41395. this.animations = new Array();
  41396. this.isPickable = false;
  41397. this._animationStarted = false;
  41398. this._loopAnimation = false;
  41399. this._fromIndex = 0;
  41400. this._toIndex = 0;
  41401. this._delay = 0;
  41402. this._direction = 1;
  41403. this._frameCount = 0;
  41404. this._time = 0;
  41405. this._manager = manager;
  41406. this._manager.sprites.push(this);
  41407. this.position = BABYLON.Vector3.Zero();
  41408. }
  41409. Object.defineProperty(Sprite.prototype, "size", {
  41410. get: function () {
  41411. return this.width;
  41412. },
  41413. set: function (value) {
  41414. this.width = value;
  41415. this.height = value;
  41416. },
  41417. enumerable: true,
  41418. configurable: true
  41419. });
  41420. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  41421. this._fromIndex = from;
  41422. this._toIndex = to;
  41423. this._loopAnimation = loop;
  41424. this._delay = delay;
  41425. this._animationStarted = true;
  41426. this._direction = from < to ? 1 : -1;
  41427. this.cellIndex = from;
  41428. this._time = 0;
  41429. this._onAnimationEnd = onAnimationEnd;
  41430. };
  41431. Sprite.prototype.stopAnimation = function () {
  41432. this._animationStarted = false;
  41433. };
  41434. Sprite.prototype._animate = function (deltaTime) {
  41435. if (!this._animationStarted)
  41436. return;
  41437. this._time += deltaTime;
  41438. if (this._time > this._delay) {
  41439. this._time = this._time % this._delay;
  41440. this.cellIndex += this._direction;
  41441. if (this.cellIndex > this._toIndex) {
  41442. if (this._loopAnimation) {
  41443. this.cellIndex = this._fromIndex;
  41444. }
  41445. else {
  41446. this.cellIndex = this._toIndex;
  41447. this._animationStarted = false;
  41448. if (this._onAnimationEnd) {
  41449. this._onAnimationEnd();
  41450. }
  41451. if (this.disposeWhenFinishedAnimating) {
  41452. this.dispose();
  41453. }
  41454. }
  41455. }
  41456. }
  41457. };
  41458. Sprite.prototype.dispose = function () {
  41459. for (var i = 0; i < this._manager.sprites.length; i++) {
  41460. if (this._manager.sprites[i] == this) {
  41461. this._manager.sprites.splice(i, 1);
  41462. }
  41463. }
  41464. };
  41465. return Sprite;
  41466. }());
  41467. BABYLON.Sprite = Sprite;
  41468. })(BABYLON || (BABYLON = {}));
  41469. //# sourceMappingURL=babylon.sprite.js.map
  41470. var BABYLON;
  41471. (function (BABYLON) {
  41472. var IntersectionInfo = (function () {
  41473. function IntersectionInfo(bu, bv, distance) {
  41474. this.bu = bu;
  41475. this.bv = bv;
  41476. this.distance = distance;
  41477. this.faceId = 0;
  41478. this.subMeshId = 0;
  41479. }
  41480. return IntersectionInfo;
  41481. }());
  41482. BABYLON.IntersectionInfo = IntersectionInfo;
  41483. var PickingInfo = (function () {
  41484. function PickingInfo() {
  41485. this.hit = false;
  41486. this.distance = 0;
  41487. this.pickedPoint = null;
  41488. this.pickedMesh = null;
  41489. this.bu = 0;
  41490. this.bv = 0;
  41491. this.faceId = -1;
  41492. this.subMeshId = 0;
  41493. this.pickedSprite = null;
  41494. }
  41495. // Methods
  41496. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  41497. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  41498. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  41499. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41500. return null;
  41501. }
  41502. var indices = this.pickedMesh.getIndices();
  41503. var result;
  41504. if (useVerticesNormals) {
  41505. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41506. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  41507. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  41508. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  41509. normal0 = normal0.scale(this.bu);
  41510. normal1 = normal1.scale(this.bv);
  41511. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  41512. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  41513. }
  41514. else {
  41515. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41516. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  41517. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  41518. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  41519. var p1p2 = vertex1.subtract(vertex2);
  41520. var p3p2 = vertex3.subtract(vertex2);
  41521. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  41522. }
  41523. if (useWorldCoordinates) {
  41524. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  41525. }
  41526. return BABYLON.Vector3.Normalize(result);
  41527. };
  41528. PickingInfo.prototype.getTextureCoordinates = function () {
  41529. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  41530. return null;
  41531. }
  41532. var indices = this.pickedMesh.getIndices();
  41533. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41534. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  41535. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  41536. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  41537. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  41538. uv1 = uv1.scale(this.bu);
  41539. uv2 = uv2.scale(this.bv);
  41540. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  41541. };
  41542. return PickingInfo;
  41543. }());
  41544. BABYLON.PickingInfo = PickingInfo;
  41545. })(BABYLON || (BABYLON = {}));
  41546. //# sourceMappingURL=babylon.pickingInfo.js.map
  41547. var BABYLON;
  41548. (function (BABYLON) {
  41549. var Ray = (function () {
  41550. function Ray(origin, direction, length) {
  41551. if (length === void 0) { length = Number.MAX_VALUE; }
  41552. this.origin = origin;
  41553. this.direction = direction;
  41554. this.length = length;
  41555. }
  41556. // Methods
  41557. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  41558. var d = 0.0;
  41559. var maxValue = Number.MAX_VALUE;
  41560. var inv;
  41561. var min;
  41562. var max;
  41563. var temp;
  41564. if (Math.abs(this.direction.x) < 0.0000001) {
  41565. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  41566. return false;
  41567. }
  41568. }
  41569. else {
  41570. inv = 1.0 / this.direction.x;
  41571. min = (minimum.x - this.origin.x) * inv;
  41572. max = (maximum.x - this.origin.x) * inv;
  41573. if (max === -Infinity) {
  41574. max = Infinity;
  41575. }
  41576. if (min > max) {
  41577. temp = min;
  41578. min = max;
  41579. max = temp;
  41580. }
  41581. d = Math.max(min, d);
  41582. maxValue = Math.min(max, maxValue);
  41583. if (d > maxValue) {
  41584. return false;
  41585. }
  41586. }
  41587. if (Math.abs(this.direction.y) < 0.0000001) {
  41588. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  41589. return false;
  41590. }
  41591. }
  41592. else {
  41593. inv = 1.0 / this.direction.y;
  41594. min = (minimum.y - this.origin.y) * inv;
  41595. max = (maximum.y - this.origin.y) * inv;
  41596. if (max === -Infinity) {
  41597. max = Infinity;
  41598. }
  41599. if (min > max) {
  41600. temp = min;
  41601. min = max;
  41602. max = temp;
  41603. }
  41604. d = Math.max(min, d);
  41605. maxValue = Math.min(max, maxValue);
  41606. if (d > maxValue) {
  41607. return false;
  41608. }
  41609. }
  41610. if (Math.abs(this.direction.z) < 0.0000001) {
  41611. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  41612. return false;
  41613. }
  41614. }
  41615. else {
  41616. inv = 1.0 / this.direction.z;
  41617. min = (minimum.z - this.origin.z) * inv;
  41618. max = (maximum.z - this.origin.z) * inv;
  41619. if (max === -Infinity) {
  41620. max = Infinity;
  41621. }
  41622. if (min > max) {
  41623. temp = min;
  41624. min = max;
  41625. max = temp;
  41626. }
  41627. d = Math.max(min, d);
  41628. maxValue = Math.min(max, maxValue);
  41629. if (d > maxValue) {
  41630. return false;
  41631. }
  41632. }
  41633. return true;
  41634. };
  41635. Ray.prototype.intersectsBox = function (box) {
  41636. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  41637. };
  41638. Ray.prototype.intersectsSphere = function (sphere) {
  41639. var x = sphere.center.x - this.origin.x;
  41640. var y = sphere.center.y - this.origin.y;
  41641. var z = sphere.center.z - this.origin.z;
  41642. var pyth = (x * x) + (y * y) + (z * z);
  41643. var rr = sphere.radius * sphere.radius;
  41644. if (pyth <= rr) {
  41645. return true;
  41646. }
  41647. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  41648. if (dot < 0.0) {
  41649. return false;
  41650. }
  41651. var temp = pyth - (dot * dot);
  41652. return temp <= rr;
  41653. };
  41654. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  41655. if (!this._edge1) {
  41656. this._edge1 = BABYLON.Vector3.Zero();
  41657. this._edge2 = BABYLON.Vector3.Zero();
  41658. this._pvec = BABYLON.Vector3.Zero();
  41659. this._tvec = BABYLON.Vector3.Zero();
  41660. this._qvec = BABYLON.Vector3.Zero();
  41661. }
  41662. vertex1.subtractToRef(vertex0, this._edge1);
  41663. vertex2.subtractToRef(vertex0, this._edge2);
  41664. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  41665. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  41666. if (det === 0) {
  41667. return null;
  41668. }
  41669. var invdet = 1 / det;
  41670. this.origin.subtractToRef(vertex0, this._tvec);
  41671. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  41672. if (bu < 0 || bu > 1.0) {
  41673. return null;
  41674. }
  41675. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  41676. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  41677. if (bv < 0 || bu + bv > 1.0) {
  41678. return null;
  41679. }
  41680. //check if the distance is longer than the predefined length.
  41681. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  41682. if (distance > this.length) {
  41683. return null;
  41684. }
  41685. return new BABYLON.IntersectionInfo(bu, bv, distance);
  41686. };
  41687. Ray.prototype.intersectsPlane = function (plane) {
  41688. var distance;
  41689. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  41690. if (Math.abs(result1) < 9.99999997475243E-07) {
  41691. return null;
  41692. }
  41693. else {
  41694. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  41695. distance = (-plane.d - result2) / result1;
  41696. if (distance < 0.0) {
  41697. if (distance < -9.99999997475243E-07) {
  41698. return null;
  41699. }
  41700. else {
  41701. return 0;
  41702. }
  41703. }
  41704. return distance;
  41705. }
  41706. };
  41707. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  41708. var tm = BABYLON.Tmp.Matrix[0];
  41709. mesh.getWorldMatrix().invertToRef(tm);
  41710. if (this._tmpRay) {
  41711. Ray.TransformToRef(this, tm, this._tmpRay);
  41712. }
  41713. else {
  41714. this._tmpRay = Ray.Transform(this, tm);
  41715. }
  41716. return mesh.intersects(this._tmpRay, fastCheck);
  41717. };
  41718. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  41719. if (results) {
  41720. results.length = 0;
  41721. }
  41722. else {
  41723. results = [];
  41724. }
  41725. for (var i = 0; i < meshes.length; i++) {
  41726. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  41727. if (pickInfo.hit) {
  41728. results.push(pickInfo);
  41729. }
  41730. }
  41731. results.sort(this._comparePickingInfo);
  41732. return results;
  41733. };
  41734. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  41735. if (pickingInfoA.distance < pickingInfoB.distance) {
  41736. return -1;
  41737. }
  41738. else if (pickingInfoA.distance > pickingInfoB.distance) {
  41739. return 1;
  41740. }
  41741. else {
  41742. return 0;
  41743. }
  41744. };
  41745. /**
  41746. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  41747. * @param sega the first point of the segment to test the intersection against
  41748. * @param segb the second point of the segment to test the intersection against
  41749. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  41750. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  41751. */
  41752. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  41753. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  41754. var u = segb.subtract(sega);
  41755. var v = rsegb.subtract(this.origin);
  41756. var w = sega.subtract(this.origin);
  41757. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  41758. var b = BABYLON.Vector3.Dot(u, v);
  41759. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  41760. var d = BABYLON.Vector3.Dot(u, w);
  41761. var e = BABYLON.Vector3.Dot(v, w);
  41762. var D = a * c - b * b; // always >= 0
  41763. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  41764. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  41765. // compute the line parameters of the two closest points
  41766. if (D < Ray.smallnum) {
  41767. sN = 0.0; // force using point P0 on segment S1
  41768. sD = 1.0; // to prevent possible division by 0.0 later
  41769. tN = e;
  41770. tD = c;
  41771. }
  41772. else {
  41773. sN = (b * e - c * d);
  41774. tN = (a * e - b * d);
  41775. if (sN < 0.0) {
  41776. sN = 0.0;
  41777. tN = e;
  41778. tD = c;
  41779. }
  41780. else if (sN > sD) {
  41781. sN = sD;
  41782. tN = e + b;
  41783. tD = c;
  41784. }
  41785. }
  41786. if (tN < 0.0) {
  41787. tN = 0.0;
  41788. // recompute sc for this edge
  41789. if (-d < 0.0) {
  41790. sN = 0.0;
  41791. }
  41792. else if (-d > a)
  41793. sN = sD;
  41794. else {
  41795. sN = -d;
  41796. sD = a;
  41797. }
  41798. }
  41799. else if (tN > tD) {
  41800. tN = tD;
  41801. // recompute sc for this edge
  41802. if ((-d + b) < 0.0) {
  41803. sN = 0;
  41804. }
  41805. else if ((-d + b) > a) {
  41806. sN = sD;
  41807. }
  41808. else {
  41809. sN = (-d + b);
  41810. sD = a;
  41811. }
  41812. }
  41813. // finally do the division to get sc and tc
  41814. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  41815. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  41816. // get the difference of the two closest points
  41817. var qtc = v.multiplyByFloats(tc, tc, tc);
  41818. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  41819. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  41820. if (isIntersected) {
  41821. return qtc.length();
  41822. }
  41823. return -1;
  41824. };
  41825. // Statics
  41826. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  41827. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  41828. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  41829. var direction = end.subtract(start);
  41830. direction.normalize();
  41831. return new Ray(start, direction);
  41832. };
  41833. /**
  41834. * 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
  41835. * transformed to the given world matrix.
  41836. * @param origin The origin point
  41837. * @param end The end point
  41838. * @param world a matrix to transform the ray to. Default is the identity matrix.
  41839. */
  41840. Ray.CreateNewFromTo = function (origin, end, world) {
  41841. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  41842. var direction = end.subtract(origin);
  41843. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  41844. direction.normalize();
  41845. return Ray.Transform(new Ray(origin, direction, length), world);
  41846. };
  41847. Ray.Transform = function (ray, matrix) {
  41848. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  41849. Ray.TransformToRef(ray, matrix, result);
  41850. return result;
  41851. };
  41852. Ray.TransformToRef = function (ray, matrix, result) {
  41853. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  41854. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  41855. result.length = ray.length;
  41856. var dir = result.direction;
  41857. var len = dir.length();
  41858. if (!(len === 0 || len === 1)) {
  41859. var num = 1.0 / len;
  41860. dir.x *= num;
  41861. dir.y *= num;
  41862. dir.z *= num;
  41863. result.length *= len;
  41864. }
  41865. };
  41866. Ray.smallnum = 0.00000001;
  41867. Ray.rayl = 10e8;
  41868. return Ray;
  41869. }());
  41870. BABYLON.Ray = Ray;
  41871. })(BABYLON || (BABYLON = {}));
  41872. //# sourceMappingURL=babylon.ray.js.map
  41873. var BABYLON;
  41874. (function (BABYLON) {
  41875. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  41876. if (boxMin.x > sphereCenter.x + sphereRadius)
  41877. return false;
  41878. if (sphereCenter.x - sphereRadius > boxMax.x)
  41879. return false;
  41880. if (boxMin.y > sphereCenter.y + sphereRadius)
  41881. return false;
  41882. if (sphereCenter.y - sphereRadius > boxMax.y)
  41883. return false;
  41884. if (boxMin.z > sphereCenter.z + sphereRadius)
  41885. return false;
  41886. if (sphereCenter.z - sphereRadius > boxMax.z)
  41887. return false;
  41888. return true;
  41889. };
  41890. var getLowestRoot = (function () {
  41891. var result = { root: 0, found: false };
  41892. return function (a, b, c, maxR) {
  41893. result.root = 0;
  41894. result.found = false;
  41895. var determinant = b * b - 4.0 * a * c;
  41896. if (determinant < 0)
  41897. return result;
  41898. var sqrtD = Math.sqrt(determinant);
  41899. var r1 = (-b - sqrtD) / (2.0 * a);
  41900. var r2 = (-b + sqrtD) / (2.0 * a);
  41901. if (r1 > r2) {
  41902. var temp = r2;
  41903. r2 = r1;
  41904. r1 = temp;
  41905. }
  41906. if (r1 > 0 && r1 < maxR) {
  41907. result.root = r1;
  41908. result.found = true;
  41909. return result;
  41910. }
  41911. if (r2 > 0 && r2 < maxR) {
  41912. result.root = r2;
  41913. result.found = true;
  41914. return result;
  41915. }
  41916. return result;
  41917. };
  41918. })();
  41919. var Collider = (function () {
  41920. function Collider() {
  41921. this.radius = BABYLON.Vector3.One();
  41922. this.retry = 0;
  41923. this.basePointWorld = BABYLON.Vector3.Zero();
  41924. this.velocityWorld = BABYLON.Vector3.Zero();
  41925. this.normalizedVelocity = BABYLON.Vector3.Zero();
  41926. this._collisionPoint = BABYLON.Vector3.Zero();
  41927. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  41928. this._tempVector = BABYLON.Vector3.Zero();
  41929. this._tempVector2 = BABYLON.Vector3.Zero();
  41930. this._tempVector3 = BABYLON.Vector3.Zero();
  41931. this._tempVector4 = BABYLON.Vector3.Zero();
  41932. this._edge = BABYLON.Vector3.Zero();
  41933. this._baseToVertex = BABYLON.Vector3.Zero();
  41934. this._destinationPoint = BABYLON.Vector3.Zero();
  41935. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  41936. this._displacementVector = BABYLON.Vector3.Zero();
  41937. this._collisionMask = -1;
  41938. }
  41939. Object.defineProperty(Collider.prototype, "collisionMask", {
  41940. get: function () {
  41941. return this._collisionMask;
  41942. },
  41943. set: function (mask) {
  41944. this._collisionMask = !isNaN(mask) ? mask : -1;
  41945. },
  41946. enumerable: true,
  41947. configurable: true
  41948. });
  41949. // Methods
  41950. Collider.prototype._initialize = function (source, dir, e) {
  41951. this.velocity = dir;
  41952. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  41953. this.basePoint = source;
  41954. source.multiplyToRef(this.radius, this.basePointWorld);
  41955. dir.multiplyToRef(this.radius, this.velocityWorld);
  41956. this.velocityWorldLength = this.velocityWorld.length();
  41957. this.epsilon = e;
  41958. this.collisionFound = false;
  41959. };
  41960. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  41961. pa.subtractToRef(point, this._tempVector);
  41962. pb.subtractToRef(point, this._tempVector2);
  41963. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  41964. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  41965. if (d < 0)
  41966. return false;
  41967. pc.subtractToRef(point, this._tempVector3);
  41968. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  41969. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  41970. if (d < 0)
  41971. return false;
  41972. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  41973. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  41974. return d >= 0;
  41975. };
  41976. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  41977. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  41978. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  41979. if (distance > this.velocityWorldLength + max + sphereRadius) {
  41980. return false;
  41981. }
  41982. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  41983. return false;
  41984. return true;
  41985. };
  41986. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  41987. var t0;
  41988. var embeddedInPlane = false;
  41989. //defensive programming, actually not needed.
  41990. if (!trianglePlaneArray) {
  41991. trianglePlaneArray = [];
  41992. }
  41993. if (!trianglePlaneArray[faceIndex]) {
  41994. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  41995. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  41996. }
  41997. var trianglePlane = trianglePlaneArray[faceIndex];
  41998. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  41999. return;
  42000. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  42001. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  42002. if (normalDotVelocity == 0) {
  42003. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  42004. return;
  42005. embeddedInPlane = true;
  42006. t0 = 0;
  42007. }
  42008. else {
  42009. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  42010. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  42011. if (t0 > t1) {
  42012. var temp = t1;
  42013. t1 = t0;
  42014. t0 = temp;
  42015. }
  42016. if (t0 > 1.0 || t1 < 0.0)
  42017. return;
  42018. if (t0 < 0)
  42019. t0 = 0;
  42020. if (t0 > 1.0)
  42021. t0 = 1.0;
  42022. }
  42023. this._collisionPoint.copyFromFloats(0, 0, 0);
  42024. var found = false;
  42025. var t = 1.0;
  42026. if (!embeddedInPlane) {
  42027. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  42028. this.velocity.scaleToRef(t0, this._tempVector);
  42029. this._planeIntersectionPoint.addInPlace(this._tempVector);
  42030. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  42031. found = true;
  42032. t = t0;
  42033. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  42034. }
  42035. }
  42036. if (!found) {
  42037. var velocitySquaredLength = this.velocity.lengthSquared();
  42038. var a = velocitySquaredLength;
  42039. this.basePoint.subtractToRef(p1, this._tempVector);
  42040. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  42041. var c = this._tempVector.lengthSquared() - 1.0;
  42042. var lowestRoot = getLowestRoot(a, b, c, t);
  42043. if (lowestRoot.found) {
  42044. t = lowestRoot.root;
  42045. found = true;
  42046. this._collisionPoint.copyFrom(p1);
  42047. }
  42048. this.basePoint.subtractToRef(p2, this._tempVector);
  42049. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  42050. c = this._tempVector.lengthSquared() - 1.0;
  42051. lowestRoot = getLowestRoot(a, b, c, t);
  42052. if (lowestRoot.found) {
  42053. t = lowestRoot.root;
  42054. found = true;
  42055. this._collisionPoint.copyFrom(p2);
  42056. }
  42057. this.basePoint.subtractToRef(p3, this._tempVector);
  42058. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  42059. c = this._tempVector.lengthSquared() - 1.0;
  42060. lowestRoot = getLowestRoot(a, b, c, t);
  42061. if (lowestRoot.found) {
  42062. t = lowestRoot.root;
  42063. found = true;
  42064. this._collisionPoint.copyFrom(p3);
  42065. }
  42066. p2.subtractToRef(p1, this._edge);
  42067. p1.subtractToRef(this.basePoint, this._baseToVertex);
  42068. var edgeSquaredLength = this._edge.lengthSquared();
  42069. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  42070. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  42071. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  42072. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  42073. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  42074. lowestRoot = getLowestRoot(a, b, c, t);
  42075. if (lowestRoot.found) {
  42076. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  42077. if (f >= 0.0 && f <= 1.0) {
  42078. t = lowestRoot.root;
  42079. found = true;
  42080. this._edge.scaleInPlace(f);
  42081. p1.addToRef(this._edge, this._collisionPoint);
  42082. }
  42083. }
  42084. p3.subtractToRef(p2, this._edge);
  42085. p2.subtractToRef(this.basePoint, this._baseToVertex);
  42086. edgeSquaredLength = this._edge.lengthSquared();
  42087. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  42088. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  42089. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  42090. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  42091. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  42092. lowestRoot = getLowestRoot(a, b, c, t);
  42093. if (lowestRoot.found) {
  42094. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  42095. if (f >= 0.0 && f <= 1.0) {
  42096. t = lowestRoot.root;
  42097. found = true;
  42098. this._edge.scaleInPlace(f);
  42099. p2.addToRef(this._edge, this._collisionPoint);
  42100. }
  42101. }
  42102. p1.subtractToRef(p3, this._edge);
  42103. p3.subtractToRef(this.basePoint, this._baseToVertex);
  42104. edgeSquaredLength = this._edge.lengthSquared();
  42105. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  42106. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  42107. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  42108. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  42109. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  42110. lowestRoot = getLowestRoot(a, b, c, t);
  42111. if (lowestRoot.found) {
  42112. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  42113. if (f >= 0.0 && f <= 1.0) {
  42114. t = lowestRoot.root;
  42115. found = true;
  42116. this._edge.scaleInPlace(f);
  42117. p3.addToRef(this._edge, this._collisionPoint);
  42118. }
  42119. }
  42120. }
  42121. if (found) {
  42122. var distToCollision = t * this.velocity.length();
  42123. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  42124. if (!this.intersectionPoint) {
  42125. this.intersectionPoint = this._collisionPoint.clone();
  42126. }
  42127. else {
  42128. this.intersectionPoint.copyFrom(this._collisionPoint);
  42129. }
  42130. this.nearestDistance = distToCollision;
  42131. this.collisionFound = true;
  42132. }
  42133. }
  42134. };
  42135. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  42136. for (var i = indexStart; i < indexEnd; i += 3) {
  42137. var p1 = pts[indices[i] - decal];
  42138. var p2 = pts[indices[i + 1] - decal];
  42139. var p3 = pts[indices[i + 2] - decal];
  42140. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  42141. }
  42142. };
  42143. Collider.prototype._getResponse = function (pos, vel) {
  42144. pos.addToRef(vel, this._destinationPoint);
  42145. vel.scaleInPlace((this.nearestDistance / vel.length()));
  42146. this.basePoint.addToRef(vel, pos);
  42147. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  42148. this._slidePlaneNormal.normalize();
  42149. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  42150. pos.addInPlace(this._displacementVector);
  42151. this.intersectionPoint.addInPlace(this._displacementVector);
  42152. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  42153. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  42154. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  42155. };
  42156. return Collider;
  42157. }());
  42158. BABYLON.Collider = Collider;
  42159. })(BABYLON || (BABYLON = {}));
  42160. //# sourceMappingURL=babylon.collider.js.map
  42161. var BABYLON;
  42162. (function (BABYLON) {
  42163. //WebWorker code will be inserted to this variable.
  42164. BABYLON.CollisionWorker = "";
  42165. var WorkerTaskType;
  42166. (function (WorkerTaskType) {
  42167. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  42168. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  42169. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  42170. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  42171. var WorkerReplyType;
  42172. (function (WorkerReplyType) {
  42173. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  42174. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  42175. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  42176. var CollisionCoordinatorWorker = (function () {
  42177. function CollisionCoordinatorWorker() {
  42178. var _this = this;
  42179. this._scaledPosition = BABYLON.Vector3.Zero();
  42180. this._scaledVelocity = BABYLON.Vector3.Zero();
  42181. this.onMeshUpdated = function (mesh) {
  42182. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  42183. };
  42184. this.onGeometryUpdated = function (geometry) {
  42185. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  42186. };
  42187. this._afterRender = function () {
  42188. if (!_this._init)
  42189. return;
  42190. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  42191. return;
  42192. }
  42193. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  42194. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  42195. if (_this._runningUpdated > 4) {
  42196. return;
  42197. }
  42198. ++_this._runningUpdated;
  42199. var payload = {
  42200. updatedMeshes: _this._addUpdateMeshesList,
  42201. updatedGeometries: _this._addUpdateGeometriesList,
  42202. removedGeometries: _this._toRemoveGeometryArray,
  42203. removedMeshes: _this._toRemoveMeshesArray
  42204. };
  42205. var message = {
  42206. payload: payload,
  42207. taskType: WorkerTaskType.UPDATE
  42208. };
  42209. var serializable = [];
  42210. for (var id in payload.updatedGeometries) {
  42211. if (payload.updatedGeometries.hasOwnProperty(id)) {
  42212. //prepare transferables
  42213. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  42214. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  42215. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  42216. }
  42217. }
  42218. _this._worker.postMessage(message, serializable);
  42219. _this._addUpdateMeshesList = {};
  42220. _this._addUpdateGeometriesList = {};
  42221. _this._toRemoveGeometryArray = [];
  42222. _this._toRemoveMeshesArray = [];
  42223. };
  42224. this._onMessageFromWorker = function (e) {
  42225. var returnData = e.data;
  42226. if (returnData.error != WorkerReplyType.SUCCESS) {
  42227. //TODO what errors can be returned from the worker?
  42228. BABYLON.Tools.Warn("error returned from worker!");
  42229. return;
  42230. }
  42231. switch (returnData.taskType) {
  42232. case WorkerTaskType.INIT:
  42233. _this._init = true;
  42234. //Update the worked with ALL of the scene's current state
  42235. _this._scene.meshes.forEach(function (mesh) {
  42236. _this.onMeshAdded(mesh);
  42237. });
  42238. _this._scene.getGeometries().forEach(function (geometry) {
  42239. _this.onGeometryAdded(geometry);
  42240. });
  42241. break;
  42242. case WorkerTaskType.UPDATE:
  42243. _this._runningUpdated--;
  42244. break;
  42245. case WorkerTaskType.COLLIDE:
  42246. _this._runningCollisionTask = false;
  42247. var returnPayload = returnData.payload;
  42248. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  42249. return;
  42250. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  42251. //cleanup
  42252. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  42253. break;
  42254. }
  42255. };
  42256. this._collisionsCallbackArray = [];
  42257. this._init = false;
  42258. this._runningUpdated = 0;
  42259. this._runningCollisionTask = false;
  42260. this._addUpdateMeshesList = {};
  42261. this._addUpdateGeometriesList = {};
  42262. this._toRemoveGeometryArray = [];
  42263. this._toRemoveMeshesArray = [];
  42264. }
  42265. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  42266. if (!this._init)
  42267. return;
  42268. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  42269. return;
  42270. position.divideToRef(collider.radius, this._scaledPosition);
  42271. displacement.divideToRef(collider.radius, this._scaledVelocity);
  42272. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  42273. var payload = {
  42274. collider: {
  42275. position: this._scaledPosition.asArray(),
  42276. velocity: this._scaledVelocity.asArray(),
  42277. radius: collider.radius.asArray()
  42278. },
  42279. collisionId: collisionIndex,
  42280. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  42281. maximumRetry: maximumRetry
  42282. };
  42283. var message = {
  42284. payload: payload,
  42285. taskType: WorkerTaskType.COLLIDE
  42286. };
  42287. this._worker.postMessage(message);
  42288. };
  42289. CollisionCoordinatorWorker.prototype.init = function (scene) {
  42290. this._scene = scene;
  42291. this._scene.registerAfterRender(this._afterRender);
  42292. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  42293. this._worker = new Worker(workerUrl);
  42294. this._worker.onmessage = this._onMessageFromWorker;
  42295. var message = {
  42296. payload: {},
  42297. taskType: WorkerTaskType.INIT
  42298. };
  42299. this._worker.postMessage(message);
  42300. };
  42301. CollisionCoordinatorWorker.prototype.destroy = function () {
  42302. this._scene.unregisterAfterRender(this._afterRender);
  42303. this._worker.terminate();
  42304. };
  42305. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  42306. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  42307. this.onMeshUpdated(mesh);
  42308. };
  42309. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  42310. this._toRemoveMeshesArray.push(mesh.uniqueId);
  42311. };
  42312. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  42313. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  42314. geometry.onGeometryUpdated = this.onGeometryUpdated;
  42315. this.onGeometryUpdated(geometry);
  42316. };
  42317. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  42318. this._toRemoveGeometryArray.push(geometry.id);
  42319. };
  42320. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  42321. var submeshes = [];
  42322. if (mesh.subMeshes) {
  42323. submeshes = mesh.subMeshes.map(function (sm, idx) {
  42324. return {
  42325. position: idx,
  42326. verticesStart: sm.verticesStart,
  42327. verticesCount: sm.verticesCount,
  42328. indexStart: sm.indexStart,
  42329. indexCount: sm.indexCount,
  42330. hasMaterial: !!sm.getMaterial(),
  42331. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  42332. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  42333. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  42334. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  42335. };
  42336. });
  42337. }
  42338. var geometryId = null;
  42339. if (mesh instanceof BABYLON.Mesh) {
  42340. geometryId = mesh.geometry ? mesh.geometry.id : null;
  42341. }
  42342. else if (mesh instanceof BABYLON.InstancedMesh) {
  42343. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  42344. }
  42345. return {
  42346. uniqueId: mesh.uniqueId,
  42347. id: mesh.id,
  42348. name: mesh.name,
  42349. geometryId: geometryId,
  42350. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  42351. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  42352. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  42353. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  42354. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  42355. subMeshes: submeshes,
  42356. checkCollisions: mesh.checkCollisions
  42357. };
  42358. };
  42359. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  42360. return {
  42361. id: geometry.id,
  42362. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  42363. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  42364. indices: new Uint32Array(geometry.getIndices() || []),
  42365. };
  42366. };
  42367. return CollisionCoordinatorWorker;
  42368. }());
  42369. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  42370. var CollisionCoordinatorLegacy = (function () {
  42371. function CollisionCoordinatorLegacy() {
  42372. this._scaledPosition = BABYLON.Vector3.Zero();
  42373. this._scaledVelocity = BABYLON.Vector3.Zero();
  42374. this._finalPosition = BABYLON.Vector3.Zero();
  42375. }
  42376. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  42377. position.divideToRef(collider.radius, this._scaledPosition);
  42378. displacement.divideToRef(collider.radius, this._scaledVelocity);
  42379. collider.collidedMesh = null;
  42380. collider.retry = 0;
  42381. collider.initialVelocity = this._scaledVelocity;
  42382. collider.initialPosition = this._scaledPosition;
  42383. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  42384. this._finalPosition.multiplyInPlace(collider.radius);
  42385. //run the callback
  42386. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  42387. };
  42388. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  42389. this._scene = scene;
  42390. };
  42391. CollisionCoordinatorLegacy.prototype.destroy = function () {
  42392. //Legacy need no destruction method.
  42393. };
  42394. //No update in legacy mode
  42395. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  42396. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  42397. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  42398. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  42399. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  42400. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  42401. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  42402. if (excludedMesh === void 0) { excludedMesh = null; }
  42403. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  42404. if (collider.retry >= maximumRetry) {
  42405. finalPosition.copyFrom(position);
  42406. return;
  42407. }
  42408. // Check if this is a mesh else camera or -1
  42409. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  42410. collider._initialize(position, velocity, closeDistance);
  42411. // Check all meshes
  42412. for (var index = 0; index < this._scene.meshes.length; index++) {
  42413. var mesh = this._scene.meshes[index];
  42414. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  42415. mesh._checkCollision(collider);
  42416. }
  42417. }
  42418. if (!collider.collisionFound) {
  42419. position.addToRef(velocity, finalPosition);
  42420. return;
  42421. }
  42422. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  42423. collider._getResponse(position, velocity);
  42424. }
  42425. if (velocity.length() <= closeDistance) {
  42426. finalPosition.copyFrom(position);
  42427. return;
  42428. }
  42429. collider.retry++;
  42430. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  42431. };
  42432. return CollisionCoordinatorLegacy;
  42433. }());
  42434. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  42435. })(BABYLON || (BABYLON = {}));
  42436. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  42437. var BABYLON;
  42438. (function (BABYLON) {
  42439. var Particle = (function () {
  42440. function Particle(particleSystem) {
  42441. this.particleSystem = particleSystem;
  42442. this.position = BABYLON.Vector3.Zero();
  42443. this.direction = BABYLON.Vector3.Zero();
  42444. this.color = new BABYLON.Color4(0, 0, 0, 0);
  42445. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  42446. this.lifeTime = 1.0;
  42447. this.age = 0;
  42448. this.size = 0;
  42449. this.angle = 0;
  42450. this.angularSpeed = 0;
  42451. this._currentFrameCounter = 0;
  42452. this.cellIndex = 0;
  42453. if (!this.particleSystem.isAnimationSheetEnabled) {
  42454. return;
  42455. }
  42456. this.cellIndex = this.particleSystem.startSpriteCellID;
  42457. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  42458. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  42459. }
  42460. else {
  42461. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  42462. }
  42463. }
  42464. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  42465. // (ageOffset / scaledUpdateSpeed) / available cells
  42466. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  42467. this._currentFrameCounter += scaledUpdateSpeed;
  42468. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  42469. this._currentFrameCounter = 0;
  42470. this.cellIndex++;
  42471. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  42472. this.cellIndex = this.particleSystem.endSpriteCellID;
  42473. }
  42474. }
  42475. };
  42476. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  42477. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  42478. this.cellIndex++;
  42479. this._currentFrameCounter = 0;
  42480. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  42481. if (this.particleSystem.spriteCellLoop) {
  42482. this.cellIndex = this.particleSystem.startSpriteCellID;
  42483. }
  42484. else {
  42485. this.cellIndex = this.particleSystem.endSpriteCellID;
  42486. }
  42487. }
  42488. }
  42489. else {
  42490. this._currentFrameCounter++;
  42491. }
  42492. };
  42493. Particle.prototype.copyTo = function (other) {
  42494. other.position.copyFrom(this.position);
  42495. other.direction.copyFrom(this.direction);
  42496. other.color.copyFrom(this.color);
  42497. other.colorStep.copyFrom(this.colorStep);
  42498. other.lifeTime = this.lifeTime;
  42499. other.age = this.age;
  42500. other.size = this.size;
  42501. other.angle = this.angle;
  42502. other.angularSpeed = this.angularSpeed;
  42503. other.particleSystem = this.particleSystem;
  42504. other.cellIndex = this.cellIndex;
  42505. };
  42506. return Particle;
  42507. }());
  42508. BABYLON.Particle = Particle;
  42509. })(BABYLON || (BABYLON = {}));
  42510. //# sourceMappingURL=babylon.particle.js.map
  42511. var BABYLON;
  42512. (function (BABYLON) {
  42513. var randomNumber = function (min, max) {
  42514. if (min === max) {
  42515. return (min);
  42516. }
  42517. var random = Math.random();
  42518. return ((random * (max - min)) + min);
  42519. };
  42520. var ParticleSystem = (function () {
  42521. // end of sheet animation
  42522. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  42523. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  42524. if (epsilon === void 0) { epsilon = 0.01; }
  42525. var _this = this;
  42526. this.name = name;
  42527. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  42528. // Members
  42529. this.animations = [];
  42530. this.renderingGroupId = 0;
  42531. this.emitter = null;
  42532. this.emitRate = 10;
  42533. this.manualEmitCount = -1;
  42534. this.updateSpeed = 0.01;
  42535. this.targetStopDuration = 0;
  42536. this.disposeOnStop = false;
  42537. this.minEmitPower = 1;
  42538. this.maxEmitPower = 1;
  42539. this.minLifeTime = 1;
  42540. this.maxLifeTime = 1;
  42541. this.minSize = 1;
  42542. this.maxSize = 1;
  42543. this.minAngularSpeed = 0;
  42544. this.maxAngularSpeed = 0;
  42545. this.layerMask = 0x0FFFFFFF;
  42546. this.customShader = null;
  42547. this.preventAutoStart = false;
  42548. /**
  42549. * An event triggered when the system is disposed.
  42550. * @type {BABYLON.Observable}
  42551. */
  42552. this.onDisposeObservable = new BABYLON.Observable();
  42553. this.onAnimationEnd = null;
  42554. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  42555. this.forceDepthWrite = false;
  42556. this.gravity = BABYLON.Vector3.Zero();
  42557. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  42558. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  42559. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  42560. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  42561. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  42562. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  42563. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  42564. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  42565. this.particles = new Array();
  42566. this._stockParticles = new Array();
  42567. this._newPartsExcess = 0;
  42568. this._vertexBuffers = {};
  42569. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  42570. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  42571. this._scaledDirection = BABYLON.Vector3.Zero();
  42572. this._scaledGravity = BABYLON.Vector3.Zero();
  42573. this._currentRenderId = -1;
  42574. this._started = false;
  42575. this._stopped = false;
  42576. this._actualFrame = 0;
  42577. // sheet animation
  42578. this.startSpriteCellID = 0;
  42579. this.endSpriteCellID = 0;
  42580. this.spriteCellLoop = true;
  42581. this.spriteCellChangeSpeed = 0;
  42582. this.spriteCellWidth = 0;
  42583. this.spriteCellHeight = 0;
  42584. this._vertexBufferSize = 11;
  42585. this.appendParticleVertexes = null;
  42586. this.id = name;
  42587. this._capacity = capacity;
  42588. this._epsilon = epsilon;
  42589. if (_isAnimationSheetEnabled) {
  42590. this._vertexBufferSize = 12;
  42591. }
  42592. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  42593. this._customEffect = customEffect;
  42594. scene.particleSystems.push(this);
  42595. this._createIndexBuffer();
  42596. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  42597. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  42598. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  42599. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  42600. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  42601. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  42602. if (this._isAnimationSheetEnabled) {
  42603. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  42604. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  42605. }
  42606. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  42607. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  42608. this._vertexBuffers["options"] = options;
  42609. // Default behaviors
  42610. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  42611. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  42612. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  42613. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  42614. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  42615. };
  42616. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  42617. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  42618. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  42619. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  42620. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  42621. };
  42622. this.updateFunction = function (particles) {
  42623. for (var index = 0; index < particles.length; index++) {
  42624. var particle = particles[index];
  42625. particle.age += _this._scaledUpdateSpeed;
  42626. if (particle.age >= particle.lifeTime) {
  42627. _this.recycleParticle(particle);
  42628. index--;
  42629. continue;
  42630. }
  42631. else {
  42632. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  42633. particle.color.addInPlace(_this._scaledColorStep);
  42634. if (particle.color.a < 0)
  42635. particle.color.a = 0;
  42636. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  42637. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  42638. particle.position.addInPlace(_this._scaledDirection);
  42639. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  42640. particle.direction.addInPlace(_this._scaledGravity);
  42641. if (_this._isAnimationSheetEnabled) {
  42642. particle.updateCellIndex(_this._scaledUpdateSpeed);
  42643. }
  42644. }
  42645. }
  42646. };
  42647. }
  42648. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  42649. set: function (callback) {
  42650. if (this._onDisposeObserver) {
  42651. this.onDisposeObservable.remove(this._onDisposeObserver);
  42652. }
  42653. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  42654. },
  42655. enumerable: true,
  42656. configurable: true
  42657. });
  42658. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  42659. get: function () {
  42660. return this._isAnimationSheetEnabled;
  42661. },
  42662. enumerable: true,
  42663. configurable: true
  42664. });
  42665. ParticleSystem.prototype._createIndexBuffer = function () {
  42666. var indices = [];
  42667. var index = 0;
  42668. for (var count = 0; count < this._capacity; count++) {
  42669. indices.push(index);
  42670. indices.push(index + 1);
  42671. indices.push(index + 2);
  42672. indices.push(index);
  42673. indices.push(index + 2);
  42674. indices.push(index + 3);
  42675. index += 4;
  42676. }
  42677. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  42678. };
  42679. ParticleSystem.prototype.recycleParticle = function (particle) {
  42680. var lastParticle = this.particles.pop();
  42681. if (lastParticle !== particle) {
  42682. lastParticle.copyTo(particle);
  42683. this._stockParticles.push(lastParticle);
  42684. }
  42685. };
  42686. ParticleSystem.prototype.getCapacity = function () {
  42687. return this._capacity;
  42688. };
  42689. ParticleSystem.prototype.isAlive = function () {
  42690. return this._alive;
  42691. };
  42692. ParticleSystem.prototype.isStarted = function () {
  42693. return this._started;
  42694. };
  42695. ParticleSystem.prototype.start = function () {
  42696. this._started = true;
  42697. this._stopped = false;
  42698. this._actualFrame = 0;
  42699. };
  42700. ParticleSystem.prototype.stop = function () {
  42701. this._stopped = true;
  42702. };
  42703. // animation sheet
  42704. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  42705. var offset = index * this._vertexBufferSize;
  42706. this._vertexData[offset] = particle.position.x;
  42707. this._vertexData[offset + 1] = particle.position.y;
  42708. this._vertexData[offset + 2] = particle.position.z;
  42709. this._vertexData[offset + 3] = particle.color.r;
  42710. this._vertexData[offset + 4] = particle.color.g;
  42711. this._vertexData[offset + 5] = particle.color.b;
  42712. this._vertexData[offset + 6] = particle.color.a;
  42713. this._vertexData[offset + 7] = particle.angle;
  42714. this._vertexData[offset + 8] = particle.size;
  42715. this._vertexData[offset + 9] = offsetX;
  42716. this._vertexData[offset + 10] = offsetY;
  42717. };
  42718. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  42719. if (offsetX === 0)
  42720. offsetX = this._epsilon;
  42721. else if (offsetX === 1)
  42722. offsetX = 1 - this._epsilon;
  42723. if (offsetY === 0)
  42724. offsetY = this._epsilon;
  42725. else if (offsetY === 1)
  42726. offsetY = 1 - this._epsilon;
  42727. var offset = index * this._vertexBufferSize;
  42728. this._vertexData[offset] = particle.position.x;
  42729. this._vertexData[offset + 1] = particle.position.y;
  42730. this._vertexData[offset + 2] = particle.position.z;
  42731. this._vertexData[offset + 3] = particle.color.r;
  42732. this._vertexData[offset + 4] = particle.color.g;
  42733. this._vertexData[offset + 5] = particle.color.b;
  42734. this._vertexData[offset + 6] = particle.color.a;
  42735. this._vertexData[offset + 7] = particle.angle;
  42736. this._vertexData[offset + 8] = particle.size;
  42737. this._vertexData[offset + 9] = offsetX;
  42738. this._vertexData[offset + 10] = offsetY;
  42739. this._vertexData[offset + 11] = particle.cellIndex;
  42740. };
  42741. ParticleSystem.prototype._update = function (newParticles) {
  42742. // Update current
  42743. this._alive = this.particles.length > 0;
  42744. this.updateFunction(this.particles);
  42745. // Add new ones
  42746. var worldMatrix;
  42747. if (this.emitter.position) {
  42748. var emitterMesh = this.emitter;
  42749. worldMatrix = emitterMesh.getWorldMatrix();
  42750. }
  42751. else {
  42752. var emitterPosition = this.emitter;
  42753. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  42754. }
  42755. var particle;
  42756. for (var index = 0; index < newParticles; index++) {
  42757. if (this.particles.length === this._capacity) {
  42758. break;
  42759. }
  42760. if (this._stockParticles.length !== 0) {
  42761. particle = this._stockParticles.pop();
  42762. particle.age = 0;
  42763. particle.cellIndex = this.startSpriteCellID;
  42764. }
  42765. else {
  42766. particle = new BABYLON.Particle(this);
  42767. }
  42768. this.particles.push(particle);
  42769. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  42770. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  42771. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  42772. particle.size = randomNumber(this.minSize, this.maxSize);
  42773. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  42774. this.startPositionFunction(worldMatrix, particle.position, particle);
  42775. var step = randomNumber(0, 1.0);
  42776. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  42777. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  42778. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  42779. }
  42780. };
  42781. ParticleSystem.prototype._getEffect = function () {
  42782. if (this._customEffect) {
  42783. return this._customEffect;
  42784. }
  42785. ;
  42786. var defines = [];
  42787. if (this._scene.clipPlane) {
  42788. defines.push("#define CLIPPLANE");
  42789. }
  42790. if (this._isAnimationSheetEnabled) {
  42791. defines.push("#define ANIMATESHEET");
  42792. }
  42793. // Effect
  42794. var join = defines.join("\n");
  42795. if (this._cachedDefines !== join) {
  42796. this._cachedDefines = join;
  42797. var attributesNamesOrOptions;
  42798. var effectCreationOption;
  42799. if (this._isAnimationSheetEnabled) {
  42800. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  42801. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  42802. }
  42803. else {
  42804. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  42805. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  42806. }
  42807. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  42808. }
  42809. return this._effect;
  42810. };
  42811. ParticleSystem.prototype.animate = function () {
  42812. if (!this._started)
  42813. return;
  42814. var effect = this._getEffect();
  42815. // Check
  42816. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  42817. return;
  42818. if (this._currentRenderId === this._scene.getRenderId()) {
  42819. return;
  42820. }
  42821. this._currentRenderId = this._scene.getRenderId();
  42822. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  42823. // determine the number of particles we need to create
  42824. var newParticles;
  42825. if (this.manualEmitCount > -1) {
  42826. newParticles = this.manualEmitCount;
  42827. this._newPartsExcess = 0;
  42828. this.manualEmitCount = 0;
  42829. }
  42830. else {
  42831. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  42832. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  42833. }
  42834. if (this._newPartsExcess > 1.0) {
  42835. newParticles += this._newPartsExcess >> 0;
  42836. this._newPartsExcess -= this._newPartsExcess >> 0;
  42837. }
  42838. this._alive = false;
  42839. if (!this._stopped) {
  42840. this._actualFrame += this._scaledUpdateSpeed;
  42841. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  42842. this.stop();
  42843. }
  42844. else {
  42845. newParticles = 0;
  42846. }
  42847. this._update(newParticles);
  42848. // Stopped?
  42849. if (this._stopped) {
  42850. if (!this._alive) {
  42851. this._started = false;
  42852. if (this.onAnimationEnd) {
  42853. this.onAnimationEnd();
  42854. }
  42855. if (this.disposeOnStop) {
  42856. this._scene._toBeDisposed.push(this);
  42857. }
  42858. }
  42859. }
  42860. // Animation sheet
  42861. if (this._isAnimationSheetEnabled) {
  42862. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  42863. }
  42864. else {
  42865. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  42866. }
  42867. // Update VBO
  42868. var offset = 0;
  42869. for (var index = 0; index < this.particles.length; index++) {
  42870. var particle = this.particles[index];
  42871. this.appendParticleVertexes(offset, particle);
  42872. offset += 4;
  42873. }
  42874. this._vertexBuffer.update(this._vertexData);
  42875. };
  42876. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  42877. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  42878. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  42879. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  42880. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  42881. };
  42882. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  42883. this._appendParticleVertex(offset++, particle, 0, 0);
  42884. this._appendParticleVertex(offset++, particle, 1, 0);
  42885. this._appendParticleVertex(offset++, particle, 1, 1);
  42886. this._appendParticleVertex(offset++, particle, 0, 1);
  42887. };
  42888. ParticleSystem.prototype.rebuild = function () {
  42889. this._createIndexBuffer();
  42890. this._vertexBuffer._rebuild();
  42891. };
  42892. ParticleSystem.prototype.render = function () {
  42893. var effect = this._getEffect();
  42894. // Check
  42895. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  42896. return 0;
  42897. var engine = this._scene.getEngine();
  42898. // Render
  42899. engine.enableEffect(effect);
  42900. engine.setState(false);
  42901. var viewMatrix = this._scene.getViewMatrix();
  42902. effect.setTexture("diffuseSampler", this.particleTexture);
  42903. effect.setMatrix("view", viewMatrix);
  42904. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  42905. if (this._isAnimationSheetEnabled) {
  42906. var baseSize = this.particleTexture.getBaseSize();
  42907. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  42908. }
  42909. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  42910. if (this._scene.clipPlane) {
  42911. var clipPlane = this._scene.clipPlane;
  42912. var invView = viewMatrix.clone();
  42913. invView.invert();
  42914. effect.setMatrix("invView", invView);
  42915. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42916. }
  42917. // VBOs
  42918. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  42919. // Draw order
  42920. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  42921. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  42922. }
  42923. else {
  42924. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42925. }
  42926. if (this.forceDepthWrite) {
  42927. engine.setDepthWrite(true);
  42928. }
  42929. engine.draw(true, 0, this.particles.length * 6);
  42930. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  42931. return this.particles.length;
  42932. };
  42933. ParticleSystem.prototype.dispose = function () {
  42934. if (this._vertexBuffer) {
  42935. this._vertexBuffer.dispose();
  42936. this._vertexBuffer = null;
  42937. }
  42938. if (this._indexBuffer) {
  42939. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  42940. this._indexBuffer = null;
  42941. }
  42942. if (this.particleTexture) {
  42943. this.particleTexture.dispose();
  42944. this.particleTexture = null;
  42945. }
  42946. // Remove from scene
  42947. var index = this._scene.particleSystems.indexOf(this);
  42948. if (index > -1) {
  42949. this._scene.particleSystems.splice(index, 1);
  42950. }
  42951. // Callback
  42952. this.onDisposeObservable.notifyObservers(this);
  42953. this.onDisposeObservable.clear();
  42954. };
  42955. // Clone
  42956. ParticleSystem.prototype.clone = function (name, newEmitter) {
  42957. var custom = null;
  42958. var program = null;
  42959. if (this.customShader != null) {
  42960. program = this.customShader;
  42961. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  42962. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  42963. }
  42964. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  42965. result.customShader = program;
  42966. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  42967. if (newEmitter === undefined) {
  42968. newEmitter = this.emitter;
  42969. }
  42970. result.emitter = newEmitter;
  42971. if (this.particleTexture) {
  42972. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  42973. }
  42974. if (!this.preventAutoStart) {
  42975. result.start();
  42976. }
  42977. return result;
  42978. };
  42979. ParticleSystem.prototype.serialize = function () {
  42980. var serializationObject = {};
  42981. serializationObject.name = this.name;
  42982. serializationObject.id = this.id;
  42983. // Emitter
  42984. if (this.emitter.position) {
  42985. var emitterMesh = this.emitter;
  42986. serializationObject.emitterId = emitterMesh.id;
  42987. }
  42988. else {
  42989. var emitterPosition = this.emitter;
  42990. serializationObject.emitter = emitterPosition.asArray();
  42991. }
  42992. serializationObject.capacity = this.getCapacity();
  42993. if (this.particleTexture) {
  42994. serializationObject.textureName = this.particleTexture.name;
  42995. }
  42996. // Animations
  42997. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  42998. // Particle system
  42999. serializationObject.minAngularSpeed = this.minAngularSpeed;
  43000. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  43001. serializationObject.minSize = this.minSize;
  43002. serializationObject.maxSize = this.maxSize;
  43003. serializationObject.minEmitPower = this.minEmitPower;
  43004. serializationObject.maxEmitPower = this.maxEmitPower;
  43005. serializationObject.minLifeTime = this.minLifeTime;
  43006. serializationObject.maxLifeTime = this.maxLifeTime;
  43007. serializationObject.emitRate = this.emitRate;
  43008. serializationObject.minEmitBox = this.minEmitBox.asArray();
  43009. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  43010. serializationObject.gravity = this.gravity.asArray();
  43011. serializationObject.direction1 = this.direction1.asArray();
  43012. serializationObject.direction2 = this.direction2.asArray();
  43013. serializationObject.color1 = this.color1.asArray();
  43014. serializationObject.color2 = this.color2.asArray();
  43015. serializationObject.colorDead = this.colorDead.asArray();
  43016. serializationObject.updateSpeed = this.updateSpeed;
  43017. serializationObject.targetStopDuration = this.targetStopDuration;
  43018. serializationObject.textureMask = this.textureMask.asArray();
  43019. serializationObject.blendMode = this.blendMode;
  43020. serializationObject.customShader = this.customShader;
  43021. serializationObject.preventAutoStart = this.preventAutoStart;
  43022. return serializationObject;
  43023. };
  43024. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  43025. var name = parsedParticleSystem.name;
  43026. var custom = null;
  43027. var program = null;
  43028. if (parsedParticleSystem.customShader) {
  43029. program = parsedParticleSystem.customShader;
  43030. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  43031. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  43032. }
  43033. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  43034. particleSystem.customShader = program;
  43035. if (parsedParticleSystem.id) {
  43036. particleSystem.id = parsedParticleSystem.id;
  43037. }
  43038. // Auto start
  43039. if (parsedParticleSystem.preventAutoStart) {
  43040. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  43041. }
  43042. // Texture
  43043. if (parsedParticleSystem.textureName) {
  43044. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  43045. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  43046. }
  43047. // Emitter
  43048. if (parsedParticleSystem.emitterId) {
  43049. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  43050. }
  43051. else {
  43052. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  43053. }
  43054. // Animations
  43055. if (parsedParticleSystem.animations) {
  43056. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  43057. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  43058. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  43059. }
  43060. }
  43061. if (parsedParticleSystem.autoAnimate) {
  43062. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  43063. }
  43064. // Particle system
  43065. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  43066. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  43067. particleSystem.minSize = parsedParticleSystem.minSize;
  43068. particleSystem.maxSize = parsedParticleSystem.maxSize;
  43069. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  43070. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  43071. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  43072. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  43073. particleSystem.emitRate = parsedParticleSystem.emitRate;
  43074. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  43075. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  43076. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  43077. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  43078. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  43079. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  43080. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  43081. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  43082. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  43083. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  43084. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  43085. particleSystem.blendMode = parsedParticleSystem.blendMode;
  43086. if (!particleSystem.preventAutoStart) {
  43087. particleSystem.start();
  43088. }
  43089. return particleSystem;
  43090. };
  43091. // Statics
  43092. ParticleSystem.BLENDMODE_ONEONE = 0;
  43093. ParticleSystem.BLENDMODE_STANDARD = 1;
  43094. return ParticleSystem;
  43095. }());
  43096. BABYLON.ParticleSystem = ParticleSystem;
  43097. })(BABYLON || (BABYLON = {}));
  43098. //# sourceMappingURL=babylon.particleSystem.js.map
  43099. var BABYLON;
  43100. (function (BABYLON) {
  43101. var SolidParticle = (function () {
  43102. /**
  43103. * Creates a Solid Particle object.
  43104. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  43105. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  43106. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  43107. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  43108. * `shapeId` (integer) is the model shape identifier in the SPS.
  43109. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  43110. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  43111. */
  43112. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  43113. this.idx = 0; // particle global index
  43114. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  43115. this.position = BABYLON.Vector3.Zero(); // position
  43116. this.rotation = BABYLON.Vector3.Zero(); // rotation
  43117. this.scaling = BABYLON.Vector3.One(); // scaling
  43118. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  43119. this.velocity = BABYLON.Vector3.Zero(); // velocity
  43120. this.alive = true; // alive
  43121. this.isVisible = true; // visibility
  43122. this._pos = 0; // index of this particle in the global "positions" array
  43123. this.shapeId = 0; // model shape id
  43124. this.idxInShape = 0; // index of the particle in its shape id
  43125. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  43126. this.idx = particleIndex;
  43127. this._pos = positionIndex;
  43128. this._model = model;
  43129. this.shapeId = shapeId;
  43130. this.idxInShape = idxInShape;
  43131. this._sps = sps;
  43132. if (modelBoundingInfo) {
  43133. this._modelBoundingInfo = modelBoundingInfo;
  43134. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  43135. }
  43136. }
  43137. Object.defineProperty(SolidParticle.prototype, "scale", {
  43138. /**
  43139. * legacy support, changed scale to scaling
  43140. */
  43141. get: function () {
  43142. return this.scaling;
  43143. },
  43144. set: function (scale) {
  43145. this.scaling = scale;
  43146. },
  43147. enumerable: true,
  43148. configurable: true
  43149. });
  43150. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  43151. /**
  43152. * legacy support, changed quaternion to rotationQuaternion
  43153. */
  43154. get: function () {
  43155. return this.rotationQuaternion;
  43156. },
  43157. set: function (q) {
  43158. this.rotationQuaternion = q;
  43159. },
  43160. enumerable: true,
  43161. configurable: true
  43162. });
  43163. /**
  43164. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  43165. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  43166. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  43167. */
  43168. SolidParticle.prototype.intersectsMesh = function (target) {
  43169. if (!this._boundingInfo || !target._boundingInfo) {
  43170. return false;
  43171. }
  43172. if (this._sps._bSphereOnly) {
  43173. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  43174. }
  43175. return this._boundingInfo.intersects(target._boundingInfo, false);
  43176. };
  43177. return SolidParticle;
  43178. }());
  43179. BABYLON.SolidParticle = SolidParticle;
  43180. var ModelShape = (function () {
  43181. /**
  43182. * 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.
  43183. * SPS internal tool, don't use it manually.
  43184. */
  43185. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  43186. this.shapeID = id;
  43187. this._shape = shape;
  43188. this._shapeUV = shapeUV;
  43189. this._positionFunction = posFunction;
  43190. this._vertexFunction = vtxFunction;
  43191. }
  43192. return ModelShape;
  43193. }());
  43194. BABYLON.ModelShape = ModelShape;
  43195. })(BABYLON || (BABYLON = {}));
  43196. //# sourceMappingURL=babylon.solidParticle.js.map
  43197. var BABYLON;
  43198. (function (BABYLON) {
  43199. /**
  43200. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  43201. */
  43202. var SolidParticleSystem = (function () {
  43203. /**
  43204. * Creates a SPS (Solid Particle System) object.
  43205. * `name` (String) is the SPS name, this will be the underlying mesh name.
  43206. * `scene` (Scene) is the scene in which the SPS is added.
  43207. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  43208. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  43209. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  43210. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  43211. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  43212. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  43213. */
  43214. function SolidParticleSystem(name, scene, options) {
  43215. // public members
  43216. /**
  43217. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  43218. * Example : var p = SPS.particles[i];
  43219. */
  43220. this.particles = new Array();
  43221. /**
  43222. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  43223. */
  43224. this.nbParticles = 0;
  43225. /**
  43226. * If the particles must ever face the camera (default false). Useful for planar particles.
  43227. */
  43228. this.billboard = false;
  43229. /**
  43230. * Recompute normals when adding a shape
  43231. */
  43232. this.recomputeNormals = true;
  43233. /**
  43234. * This a counter ofr your own usage. It's not set by any SPS functions.
  43235. */
  43236. this.counter = 0;
  43237. /**
  43238. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  43239. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  43240. */
  43241. this.vars = {};
  43242. this._positions = new Array();
  43243. this._indices = new Array();
  43244. this._normals = new Array();
  43245. this._colors = new Array();
  43246. this._uvs = new Array();
  43247. this._index = 0; // indices index
  43248. this._updatable = true;
  43249. this._pickable = false;
  43250. this._isVisibilityBoxLocked = false;
  43251. this._alwaysVisible = false;
  43252. this._shapeCounter = 0;
  43253. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  43254. this._color = new BABYLON.Color4(0, 0, 0, 0);
  43255. this._computeParticleColor = true;
  43256. this._computeParticleTexture = true;
  43257. this._computeParticleRotation = true;
  43258. this._computeParticleVertex = false;
  43259. this._computeBoundingBox = false;
  43260. this._cam_axisZ = BABYLON.Vector3.Zero();
  43261. this._cam_axisY = BABYLON.Vector3.Zero();
  43262. this._cam_axisX = BABYLON.Vector3.Zero();
  43263. this._axisX = BABYLON.Axis.X;
  43264. this._axisY = BABYLON.Axis.Y;
  43265. this._axisZ = BABYLON.Axis.Z;
  43266. this._camDir = BABYLON.Vector3.Zero();
  43267. this._rotMatrix = new BABYLON.Matrix();
  43268. this._invertMatrix = new BABYLON.Matrix();
  43269. this._rotated = BABYLON.Vector3.Zero();
  43270. this._quaternion = new BABYLON.Quaternion();
  43271. this._vertex = BABYLON.Vector3.Zero();
  43272. this._normal = BABYLON.Vector3.Zero();
  43273. this._yaw = 0.0;
  43274. this._pitch = 0.0;
  43275. this._roll = 0.0;
  43276. this._halfroll = 0.0;
  43277. this._halfpitch = 0.0;
  43278. this._halfyaw = 0.0;
  43279. this._sinRoll = 0.0;
  43280. this._cosRoll = 0.0;
  43281. this._sinPitch = 0.0;
  43282. this._cosPitch = 0.0;
  43283. this._sinYaw = 0.0;
  43284. this._cosYaw = 0.0;
  43285. this._mustUnrotateFixedNormals = false;
  43286. this._minimum = BABYLON.Tmp.Vector3[0];
  43287. this._maximum = BABYLON.Tmp.Vector3[1];
  43288. this._scale = BABYLON.Tmp.Vector3[2];
  43289. this._translation = BABYLON.Tmp.Vector3[3];
  43290. this._minBbox = BABYLON.Tmp.Vector3[4];
  43291. this._maxBbox = BABYLON.Tmp.Vector3[5];
  43292. this._particlesIntersect = false;
  43293. this._bSphereOnly = false;
  43294. this._bSphereRadiusFactor = 1.0;
  43295. this.name = name;
  43296. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  43297. this._camera = scene.activeCamera;
  43298. this._pickable = options ? options.isPickable : false;
  43299. this._particlesIntersect = options ? options.particleIntersection : false;
  43300. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  43301. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  43302. if (options && options.updatable) {
  43303. this._updatable = options.updatable;
  43304. }
  43305. else {
  43306. this._updatable = true;
  43307. }
  43308. if (this._pickable) {
  43309. this.pickedParticles = [];
  43310. }
  43311. }
  43312. /**
  43313. * Builds the SPS underlying mesh. Returns a standard Mesh.
  43314. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  43315. */
  43316. SolidParticleSystem.prototype.buildMesh = function () {
  43317. if (this.nbParticles === 0) {
  43318. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  43319. this.addShape(triangle, 1);
  43320. triangle.dispose();
  43321. }
  43322. this._positions32 = new Float32Array(this._positions);
  43323. this._uvs32 = new Float32Array(this._uvs);
  43324. this._colors32 = new Float32Array(this._colors);
  43325. if (this.recomputeNormals) {
  43326. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  43327. }
  43328. this._normals32 = new Float32Array(this._normals);
  43329. this._fixedNormal32 = new Float32Array(this._normals);
  43330. if (this._mustUnrotateFixedNormals) {
  43331. this._unrotateFixedNormals();
  43332. }
  43333. var vertexData = new BABYLON.VertexData();
  43334. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  43335. vertexData.indices = this._indices;
  43336. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  43337. if (this._uvs32) {
  43338. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  43339. ;
  43340. }
  43341. if (this._colors32) {
  43342. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  43343. }
  43344. var mesh = new BABYLON.Mesh(this.name, this._scene);
  43345. vertexData.applyToMesh(mesh, this._updatable);
  43346. this.mesh = mesh;
  43347. this.mesh.isPickable = this._pickable;
  43348. // free memory
  43349. this._positions = null;
  43350. this._normals = null;
  43351. this._uvs = null;
  43352. this._colors = null;
  43353. if (!this._updatable) {
  43354. this.particles.length = 0;
  43355. }
  43356. return mesh;
  43357. };
  43358. /**
  43359. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  43360. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  43361. * Thus the particles generated from `digest()` have their property `position` set yet.
  43362. * `mesh` ( Mesh ) is the mesh to be digested
  43363. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  43364. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  43365. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  43366. */
  43367. SolidParticleSystem.prototype.digest = function (mesh, options) {
  43368. var size = (options && options.facetNb) || 1;
  43369. var number = (options && options.number);
  43370. var delta = (options && options.delta) || 0;
  43371. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43372. var meshInd = mesh.getIndices();
  43373. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43374. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  43375. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43376. var f = 0; // facet counter
  43377. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  43378. // compute size from number
  43379. if (number) {
  43380. number = (number > totalFacets) ? totalFacets : number;
  43381. size = Math.round(totalFacets / number);
  43382. delta = 0;
  43383. }
  43384. else {
  43385. size = (size > totalFacets) ? totalFacets : size;
  43386. }
  43387. var facetPos = []; // submesh positions
  43388. var facetInd = []; // submesh indices
  43389. var facetUV = []; // submesh UV
  43390. var facetCol = []; // submesh colors
  43391. var barycenter = BABYLON.Tmp.Vector3[0];
  43392. var rand;
  43393. var sizeO = size;
  43394. while (f < totalFacets) {
  43395. size = sizeO + Math.floor((1 + delta) * Math.random());
  43396. if (f > totalFacets - size) {
  43397. size = totalFacets - f;
  43398. }
  43399. // reset temp arrays
  43400. facetPos.length = 0;
  43401. facetInd.length = 0;
  43402. facetUV.length = 0;
  43403. facetCol.length = 0;
  43404. // iterate over "size" facets
  43405. var fi = 0;
  43406. for (var j = f * 3; j < (f + size) * 3; j++) {
  43407. facetInd.push(fi);
  43408. var i = meshInd[j];
  43409. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  43410. if (meshUV) {
  43411. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  43412. }
  43413. if (meshCol) {
  43414. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  43415. }
  43416. fi++;
  43417. }
  43418. // create a model shape for each single particle
  43419. var idx = this.nbParticles;
  43420. var shape = this._posToShape(facetPos);
  43421. var shapeUV = this._uvsToShapeUV(facetUV);
  43422. // compute the barycenter of the shape
  43423. var v;
  43424. for (v = 0; v < shape.length; v++) {
  43425. barycenter.addInPlace(shape[v]);
  43426. }
  43427. barycenter.scaleInPlace(1 / shape.length);
  43428. // shift the shape from its barycenter to the origin
  43429. for (v = 0; v < shape.length; v++) {
  43430. shape[v].subtractInPlace(barycenter);
  43431. }
  43432. var bInfo;
  43433. if (this._particlesIntersect) {
  43434. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  43435. }
  43436. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  43437. // add the particle in the SPS
  43438. var currentPos = this._positions.length;
  43439. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  43440. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  43441. // initialize the particle position
  43442. this.particles[this.nbParticles].position.addInPlace(barycenter);
  43443. this._index += shape.length;
  43444. idx++;
  43445. this.nbParticles++;
  43446. this._shapeCounter++;
  43447. f += size;
  43448. }
  43449. return this;
  43450. };
  43451. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  43452. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  43453. var index = 0;
  43454. var idx = 0;
  43455. for (var p = 0; p < this.particles.length; p++) {
  43456. this._particle = this.particles[p];
  43457. this._shape = this._particle._model._shape;
  43458. if (this._particle.rotationQuaternion) {
  43459. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  43460. }
  43461. else {
  43462. this._yaw = this._particle.rotation.y;
  43463. this._pitch = this._particle.rotation.x;
  43464. this._roll = this._particle.rotation.z;
  43465. this._quaternionRotationYPR();
  43466. }
  43467. this._quaternionToRotationMatrix();
  43468. this._rotMatrix.invertToRef(this._invertMatrix);
  43469. for (var pt = 0; pt < this._shape.length; pt++) {
  43470. idx = index + pt * 3;
  43471. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  43472. this._fixedNormal32[idx] = this._normal.x;
  43473. this._fixedNormal32[idx + 1] = this._normal.y;
  43474. this._fixedNormal32[idx + 2] = this._normal.z;
  43475. }
  43476. index = idx + 3;
  43477. }
  43478. };
  43479. //reset copy
  43480. SolidParticleSystem.prototype._resetCopy = function () {
  43481. this._copy.position.x = 0;
  43482. this._copy.position.y = 0;
  43483. this._copy.position.z = 0;
  43484. this._copy.rotation.x = 0;
  43485. this._copy.rotation.y = 0;
  43486. this._copy.rotation.z = 0;
  43487. this._copy.rotationQuaternion = null;
  43488. this._copy.scaling.x = 1;
  43489. this._copy.scaling.y = 1;
  43490. this._copy.scaling.z = 1;
  43491. this._copy.uvs.x = 0;
  43492. this._copy.uvs.y = 0;
  43493. this._copy.uvs.z = 1;
  43494. this._copy.uvs.w = 1;
  43495. this._copy.color = null;
  43496. };
  43497. // _meshBuilder : inserts the shape model in the global SPS mesh
  43498. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  43499. var i;
  43500. var u = 0;
  43501. var c = 0;
  43502. var n = 0;
  43503. this._resetCopy();
  43504. if (options && options.positionFunction) {
  43505. options.positionFunction(this._copy, idx, idxInShape);
  43506. this._mustUnrotateFixedNormals = true;
  43507. }
  43508. if (this._copy.rotationQuaternion) {
  43509. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  43510. }
  43511. else {
  43512. this._yaw = this._copy.rotation.y;
  43513. this._pitch = this._copy.rotation.x;
  43514. this._roll = this._copy.rotation.z;
  43515. this._quaternionRotationYPR();
  43516. }
  43517. this._quaternionToRotationMatrix();
  43518. for (i = 0; i < shape.length; i++) {
  43519. this._vertex.x = shape[i].x;
  43520. this._vertex.y = shape[i].y;
  43521. this._vertex.z = shape[i].z;
  43522. if (options && options.vertexFunction) {
  43523. options.vertexFunction(this._copy, this._vertex, i);
  43524. }
  43525. this._vertex.x *= this._copy.scaling.x;
  43526. this._vertex.y *= this._copy.scaling.y;
  43527. this._vertex.z *= this._copy.scaling.z;
  43528. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  43529. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  43530. if (meshUV) {
  43531. 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);
  43532. u += 2;
  43533. }
  43534. if (this._copy.color) {
  43535. this._color = this._copy.color;
  43536. }
  43537. else if (meshCol && meshCol[c] !== undefined) {
  43538. this._color.r = meshCol[c];
  43539. this._color.g = meshCol[c + 1];
  43540. this._color.b = meshCol[c + 2];
  43541. this._color.a = meshCol[c + 3];
  43542. }
  43543. else {
  43544. this._color.r = 1;
  43545. this._color.g = 1;
  43546. this._color.b = 1;
  43547. this._color.a = 1;
  43548. }
  43549. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  43550. c += 4;
  43551. if (!this.recomputeNormals && meshNor) {
  43552. this._normal.x = meshNor[n];
  43553. this._normal.y = meshNor[n + 1];
  43554. this._normal.z = meshNor[n + 2];
  43555. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  43556. normals.push(this._normal.x, this._normal.y, this._normal.z);
  43557. n += 3;
  43558. }
  43559. }
  43560. for (i = 0; i < meshInd.length; i++) {
  43561. indices.push(p + meshInd[i]);
  43562. }
  43563. if (this._pickable) {
  43564. var nbfaces = meshInd.length / 3;
  43565. for (i = 0; i < nbfaces; i++) {
  43566. this.pickedParticles.push({ idx: idx, faceId: i });
  43567. }
  43568. }
  43569. return this._copy;
  43570. };
  43571. // returns a shape array from positions array
  43572. SolidParticleSystem.prototype._posToShape = function (positions) {
  43573. var shape = [];
  43574. for (var i = 0; i < positions.length; i += 3) {
  43575. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  43576. }
  43577. return shape;
  43578. };
  43579. // returns a shapeUV array from a Vector4 uvs
  43580. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  43581. var shapeUV = [];
  43582. if (uvs) {
  43583. for (var i = 0; i < uvs.length; i++)
  43584. shapeUV.push(uvs[i]);
  43585. }
  43586. return shapeUV;
  43587. };
  43588. // adds a new particle object in the particles array
  43589. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  43590. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  43591. this.particles.push(sp);
  43592. return sp;
  43593. };
  43594. /**
  43595. * Adds some particles to the SPS from the model shape. Returns the shape id.
  43596. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  43597. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  43598. * `nb` (positive integer) the number of particles to be created from this model
  43599. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  43600. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  43601. */
  43602. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  43603. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43604. var meshInd = mesh.getIndices();
  43605. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43606. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  43607. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43608. var bbInfo;
  43609. if (this._particlesIntersect) {
  43610. bbInfo = mesh.getBoundingInfo();
  43611. }
  43612. var shape = this._posToShape(meshPos);
  43613. var shapeUV = this._uvsToShapeUV(meshUV);
  43614. var posfunc = options ? options.positionFunction : null;
  43615. var vtxfunc = options ? options.vertexFunction : null;
  43616. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  43617. // particles
  43618. var sp;
  43619. var currentCopy;
  43620. var idx = this.nbParticles;
  43621. for (var i = 0; i < nb; i++) {
  43622. var currentPos = this._positions.length;
  43623. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  43624. if (this._updatable) {
  43625. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  43626. sp.position.copyFrom(currentCopy.position);
  43627. sp.rotation.copyFrom(currentCopy.rotation);
  43628. if (currentCopy.rotationQuaternion) {
  43629. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  43630. }
  43631. if (currentCopy.color) {
  43632. sp.color.copyFrom(currentCopy.color);
  43633. }
  43634. sp.scaling.copyFrom(currentCopy.scaling);
  43635. sp.uvs.copyFrom(currentCopy.uvs);
  43636. }
  43637. this._index += shape.length;
  43638. idx++;
  43639. }
  43640. this.nbParticles += nb;
  43641. this._shapeCounter++;
  43642. return this._shapeCounter - 1;
  43643. };
  43644. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  43645. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  43646. this._resetCopy();
  43647. if (particle._model._positionFunction) {
  43648. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  43649. }
  43650. if (this._copy.rotationQuaternion) {
  43651. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  43652. }
  43653. else {
  43654. this._yaw = this._copy.rotation.y;
  43655. this._pitch = this._copy.rotation.x;
  43656. this._roll = this._copy.rotation.z;
  43657. this._quaternionRotationYPR();
  43658. }
  43659. this._quaternionToRotationMatrix();
  43660. this._shape = particle._model._shape;
  43661. for (var pt = 0; pt < this._shape.length; pt++) {
  43662. this._vertex.x = this._shape[pt].x;
  43663. this._vertex.y = this._shape[pt].y;
  43664. this._vertex.z = this._shape[pt].z;
  43665. if (particle._model._vertexFunction) {
  43666. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  43667. }
  43668. this._vertex.x *= this._copy.scaling.x;
  43669. this._vertex.y *= this._copy.scaling.y;
  43670. this._vertex.z *= this._copy.scaling.z;
  43671. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  43672. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  43673. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  43674. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  43675. }
  43676. particle.position.x = 0.0;
  43677. particle.position.y = 0.0;
  43678. particle.position.z = 0.0;
  43679. particle.rotation.x = 0.0;
  43680. particle.rotation.y = 0.0;
  43681. particle.rotation.z = 0.0;
  43682. particle.rotationQuaternion = null;
  43683. particle.scaling.x = 1.0;
  43684. particle.scaling.y = 1.0;
  43685. particle.scaling.z = 1.0;
  43686. };
  43687. /**
  43688. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  43689. * Returns the SPS.
  43690. */
  43691. SolidParticleSystem.prototype.rebuildMesh = function () {
  43692. for (var p = 0; p < this.particles.length; p++) {
  43693. this._rebuildParticle(this.particles[p]);
  43694. }
  43695. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  43696. return this;
  43697. };
  43698. /**
  43699. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  43700. * This method calls `updateParticle()` for each particle of the SPS.
  43701. * For an animated SPS, it is usually called within the render loop.
  43702. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  43703. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  43704. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  43705. * Returns the SPS.
  43706. */
  43707. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  43708. if (start === void 0) { start = 0; }
  43709. if (end === void 0) { end = this.nbParticles - 1; }
  43710. if (update === void 0) { update = true; }
  43711. if (!this._updatable) {
  43712. return;
  43713. }
  43714. // custom beforeUpdate
  43715. this.beforeUpdateParticles(start, end, update);
  43716. this._cam_axisX.x = 1.0;
  43717. this._cam_axisX.y = 0.0;
  43718. this._cam_axisX.z = 0.0;
  43719. this._cam_axisY.x = 0.0;
  43720. this._cam_axisY.y = 1.0;
  43721. this._cam_axisY.z = 0.0;
  43722. this._cam_axisZ.x = 0.0;
  43723. this._cam_axisZ.y = 0.0;
  43724. this._cam_axisZ.z = 1.0;
  43725. // if the particles will always face the camera
  43726. if (this.billboard) {
  43727. this.mesh.computeWorldMatrix(true);
  43728. // compute the camera position and un-rotate it by the current mesh rotation
  43729. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  43730. this._quaternionToRotationMatrix();
  43731. this._rotMatrix.invertToRef(this._invertMatrix);
  43732. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  43733. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  43734. this._cam_axisZ.normalize();
  43735. // same for camera up vector extracted from the cam view matrix
  43736. var view = this._camera.getViewMatrix(true);
  43737. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  43738. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  43739. this._cam_axisY.normalize();
  43740. this._cam_axisX.normalize();
  43741. }
  43742. }
  43743. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  43744. var idx = 0; // current position index in the global array positions32
  43745. var index = 0; // position start index in the global array positions32 of the current particle
  43746. var colidx = 0; // current color index in the global array colors32
  43747. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  43748. var uvidx = 0; // current uv index in the global array uvs32
  43749. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  43750. var pt = 0; // current index in the particle model shape
  43751. if (this.mesh.isFacetDataEnabled) {
  43752. this._computeBoundingBox = true;
  43753. }
  43754. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  43755. if (this._computeBoundingBox) {
  43756. if (start == 0 && end == this.nbParticles - 1) {
  43757. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  43758. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  43759. }
  43760. else {
  43761. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  43762. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  43763. }
  43764. }
  43765. // particle loop
  43766. index = this.particles[start]._pos;
  43767. var vpos = (index / 3) | 0;
  43768. colorIndex = vpos * 4;
  43769. uvIndex = vpos * 2;
  43770. for (var p = start; p <= end; p++) {
  43771. this._particle = this.particles[p];
  43772. this._shape = this._particle._model._shape;
  43773. this._shapeUV = this._particle._model._shapeUV;
  43774. // call to custom user function to update the particle properties
  43775. this.updateParticle(this._particle);
  43776. // skip the computations for inactive or already invisible particles
  43777. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  43778. // increment indexes for the next particle
  43779. pt = this._shape.length;
  43780. index += pt * 3;
  43781. colorIndex += pt * 4;
  43782. uvIndex += pt * 2;
  43783. continue;
  43784. }
  43785. if (this._particle.isVisible) {
  43786. this._particle._stillInvisible = false; // un-mark permanent invisibility
  43787. // particle rotation matrix
  43788. if (this.billboard) {
  43789. this._particle.rotation.x = 0.0;
  43790. this._particle.rotation.y = 0.0;
  43791. }
  43792. if (this._computeParticleRotation || this.billboard) {
  43793. if (this._particle.rotationQuaternion) {
  43794. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  43795. }
  43796. else {
  43797. this._yaw = this._particle.rotation.y;
  43798. this._pitch = this._particle.rotation.x;
  43799. this._roll = this._particle.rotation.z;
  43800. this._quaternionRotationYPR();
  43801. }
  43802. this._quaternionToRotationMatrix();
  43803. }
  43804. // particle vertex loop
  43805. for (pt = 0; pt < this._shape.length; pt++) {
  43806. idx = index + pt * 3;
  43807. colidx = colorIndex + pt * 4;
  43808. uvidx = uvIndex + pt * 2;
  43809. this._vertex.x = this._shape[pt].x;
  43810. this._vertex.y = this._shape[pt].y;
  43811. this._vertex.z = this._shape[pt].z;
  43812. if (this._computeParticleVertex) {
  43813. this.updateParticleVertex(this._particle, this._vertex, pt);
  43814. }
  43815. // positions
  43816. this._vertex.x *= this._particle.scaling.x;
  43817. this._vertex.y *= this._particle.scaling.y;
  43818. this._vertex.z *= this._particle.scaling.z;
  43819. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  43820. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  43821. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  43822. 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;
  43823. 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;
  43824. 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;
  43825. if (this._computeBoundingBox) {
  43826. if (this._positions32[idx] < this._minimum.x) {
  43827. this._minimum.x = this._positions32[idx];
  43828. }
  43829. if (this._positions32[idx] > this._maximum.x) {
  43830. this._maximum.x = this._positions32[idx];
  43831. }
  43832. if (this._positions32[idx + 1] < this._minimum.y) {
  43833. this._minimum.y = this._positions32[idx + 1];
  43834. }
  43835. if (this._positions32[idx + 1] > this._maximum.y) {
  43836. this._maximum.y = this._positions32[idx + 1];
  43837. }
  43838. if (this._positions32[idx + 2] < this._minimum.z) {
  43839. this._minimum.z = this._positions32[idx + 2];
  43840. }
  43841. if (this._positions32[idx + 2] > this._maximum.z) {
  43842. this._maximum.z = this._positions32[idx + 2];
  43843. }
  43844. }
  43845. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  43846. if (!this._computeParticleVertex) {
  43847. this._normal.x = this._fixedNormal32[idx];
  43848. this._normal.y = this._fixedNormal32[idx + 1];
  43849. this._normal.z = this._fixedNormal32[idx + 2];
  43850. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  43851. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  43852. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  43853. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  43854. 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;
  43855. 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;
  43856. }
  43857. if (this._computeParticleColor) {
  43858. this._colors32[colidx] = this._particle.color.r;
  43859. this._colors32[colidx + 1] = this._particle.color.g;
  43860. this._colors32[colidx + 2] = this._particle.color.b;
  43861. this._colors32[colidx + 3] = this._particle.color.a;
  43862. }
  43863. if (this._computeParticleTexture) {
  43864. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  43865. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  43866. }
  43867. }
  43868. }
  43869. else {
  43870. this._particle._stillInvisible = true; // mark the particle as invisible
  43871. for (pt = 0; pt < this._shape.length; pt++) {
  43872. idx = index + pt * 3;
  43873. colidx = colorIndex + pt * 4;
  43874. uvidx = uvIndex + pt * 2;
  43875. this._positions32[idx] = 0.0;
  43876. this._positions32[idx + 1] = 0.0;
  43877. this._positions32[idx + 2] = 0.0;
  43878. this._normals32[idx] = 0.0;
  43879. this._normals32[idx + 1] = 0.0;
  43880. this._normals32[idx + 2] = 0.0;
  43881. if (this._computeParticleColor) {
  43882. this._colors32[colidx] = this._particle.color.r;
  43883. this._colors32[colidx + 1] = this._particle.color.g;
  43884. this._colors32[colidx + 2] = this._particle.color.b;
  43885. this._colors32[colidx + 3] = this._particle.color.a;
  43886. }
  43887. if (this._computeParticleTexture) {
  43888. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  43889. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  43890. }
  43891. }
  43892. }
  43893. // if the particle intersections must be computed : update the bbInfo
  43894. if (this._particlesIntersect) {
  43895. var bInfo = this._particle._boundingInfo;
  43896. var bBox = bInfo.boundingBox;
  43897. var bSphere = bInfo.boundingSphere;
  43898. if (!this._bSphereOnly) {
  43899. // place, scale and rotate the particle bbox within the SPS local system, then update it
  43900. for (var b = 0; b < bBox.vectors.length; b++) {
  43901. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  43902. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  43903. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  43904. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  43905. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  43906. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  43907. 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;
  43908. 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;
  43909. 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;
  43910. }
  43911. bBox._update(this.mesh._worldMatrix);
  43912. }
  43913. // place and scale the particle bouding sphere in the SPS local system, then update it
  43914. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  43915. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  43916. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  43917. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  43918. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  43919. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  43920. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  43921. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  43922. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  43923. 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));
  43924. bSphere._update(this.mesh._worldMatrix);
  43925. }
  43926. // increment indexes for the next particle
  43927. index = idx + 3;
  43928. colorIndex = colidx + 4;
  43929. uvIndex = uvidx + 2;
  43930. }
  43931. // if the VBO must be updated
  43932. if (update) {
  43933. if (this._computeParticleColor) {
  43934. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  43935. }
  43936. if (this._computeParticleTexture) {
  43937. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  43938. }
  43939. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  43940. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  43941. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  43942. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  43943. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  43944. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  43945. for (var i = 0; i < this._normals32.length; i++) {
  43946. this._fixedNormal32[i] = this._normals32[i];
  43947. }
  43948. }
  43949. if (!this.mesh.areNormalsFrozen) {
  43950. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  43951. }
  43952. }
  43953. }
  43954. if (this._computeBoundingBox) {
  43955. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  43956. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  43957. }
  43958. this.afterUpdateParticles(start, end, update);
  43959. return this;
  43960. };
  43961. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  43962. this._halfroll = this._roll * 0.5;
  43963. this._halfpitch = this._pitch * 0.5;
  43964. this._halfyaw = this._yaw * 0.5;
  43965. this._sinRoll = Math.sin(this._halfroll);
  43966. this._cosRoll = Math.cos(this._halfroll);
  43967. this._sinPitch = Math.sin(this._halfpitch);
  43968. this._cosPitch = Math.cos(this._halfpitch);
  43969. this._sinYaw = Math.sin(this._halfyaw);
  43970. this._cosYaw = Math.cos(this._halfyaw);
  43971. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  43972. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  43973. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  43974. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  43975. };
  43976. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  43977. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  43978. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  43979. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  43980. this._rotMatrix.m[3] = 0;
  43981. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  43982. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  43983. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  43984. this._rotMatrix.m[7] = 0;
  43985. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  43986. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  43987. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  43988. this._rotMatrix.m[11] = 0;
  43989. this._rotMatrix.m[12] = 0;
  43990. this._rotMatrix.m[13] = 0;
  43991. this._rotMatrix.m[14] = 0;
  43992. this._rotMatrix.m[15] = 1.0;
  43993. };
  43994. /**
  43995. * Disposes the SPS.
  43996. * Returns nothing.
  43997. */
  43998. SolidParticleSystem.prototype.dispose = function () {
  43999. this.mesh.dispose();
  44000. this.vars = null;
  44001. // drop references to internal big arrays for the GC
  44002. this._positions = null;
  44003. this._indices = null;
  44004. this._normals = null;
  44005. this._uvs = null;
  44006. this._colors = null;
  44007. this._positions32 = null;
  44008. this._normals32 = null;
  44009. this._fixedNormal32 = null;
  44010. this._uvs32 = null;
  44011. this._colors32 = null;
  44012. this.pickedParticles = null;
  44013. };
  44014. /**
  44015. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  44016. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  44017. * Returns the SPS.
  44018. */
  44019. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  44020. if (!this._isVisibilityBoxLocked) {
  44021. this.mesh.refreshBoundingInfo();
  44022. }
  44023. return this;
  44024. };
  44025. /**
  44026. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  44027. * @param size the size (float) of the visibility box
  44028. * note : this doesn't lock the SPS mesh bounding box.
  44029. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  44030. */
  44031. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  44032. var vis = size / 2;
  44033. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  44034. };
  44035. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  44036. // getter and setter
  44037. get: function () {
  44038. return this._alwaysVisible;
  44039. },
  44040. /**
  44041. * Sets the SPS as always visible or not
  44042. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  44043. */
  44044. set: function (val) {
  44045. this._alwaysVisible = val;
  44046. this.mesh.alwaysSelectAsActiveMesh = val;
  44047. },
  44048. enumerable: true,
  44049. configurable: true
  44050. });
  44051. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  44052. get: function () {
  44053. return this._isVisibilityBoxLocked;
  44054. },
  44055. /**
  44056. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  44057. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  44058. */
  44059. set: function (val) {
  44060. this._isVisibilityBoxLocked = val;
  44061. this.mesh.getBoundingInfo().isLocked = val;
  44062. },
  44063. enumerable: true,
  44064. configurable: true
  44065. });
  44066. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  44067. // getters
  44068. get: function () {
  44069. return this._computeParticleRotation;
  44070. },
  44071. // Optimizer setters
  44072. /**
  44073. * Tells to `setParticles()` to compute the particle rotations or not.
  44074. * Default value : true. The SPS is faster when it's set to false.
  44075. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  44076. */
  44077. set: function (val) {
  44078. this._computeParticleRotation = val;
  44079. },
  44080. enumerable: true,
  44081. configurable: true
  44082. });
  44083. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  44084. get: function () {
  44085. return this._computeParticleColor;
  44086. },
  44087. /**
  44088. * Tells to `setParticles()` to compute the particle colors or not.
  44089. * Default value : true. The SPS is faster when it's set to false.
  44090. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  44091. */
  44092. set: function (val) {
  44093. this._computeParticleColor = val;
  44094. },
  44095. enumerable: true,
  44096. configurable: true
  44097. });
  44098. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  44099. get: function () {
  44100. return this._computeParticleTexture;
  44101. },
  44102. /**
  44103. * Tells to `setParticles()` to compute the particle textures or not.
  44104. * Default value : true. The SPS is faster when it's set to false.
  44105. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  44106. */
  44107. set: function (val) {
  44108. this._computeParticleTexture = val;
  44109. },
  44110. enumerable: true,
  44111. configurable: true
  44112. });
  44113. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  44114. get: function () {
  44115. return this._computeParticleVertex;
  44116. },
  44117. /**
  44118. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  44119. * Default value : false. The SPS is faster when it's set to false.
  44120. * Note : the particle custom vertex positions aren't stored values.
  44121. */
  44122. set: function (val) {
  44123. this._computeParticleVertex = val;
  44124. },
  44125. enumerable: true,
  44126. configurable: true
  44127. });
  44128. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  44129. get: function () {
  44130. return this._computeBoundingBox;
  44131. },
  44132. /**
  44133. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  44134. */
  44135. set: function (val) {
  44136. this._computeBoundingBox = val;
  44137. },
  44138. enumerable: true,
  44139. configurable: true
  44140. });
  44141. // =======================================================================
  44142. // Particle behavior logic
  44143. // these following methods may be overwritten by the user to fit his needs
  44144. /**
  44145. * This function does nothing. It may be overwritten to set all the particle first values.
  44146. * The SPS doesn't call this function, you may have to call it by your own.
  44147. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  44148. */
  44149. SolidParticleSystem.prototype.initParticles = function () {
  44150. };
  44151. /**
  44152. * This function does nothing. It may be overwritten to recycle a particle.
  44153. * The SPS doesn't call this function, you may have to call it by your own.
  44154. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  44155. */
  44156. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  44157. return particle;
  44158. };
  44159. /**
  44160. * Updates a particle : this function should be overwritten by the user.
  44161. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  44162. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  44163. * ex : just set a particle position or velocity and recycle conditions
  44164. */
  44165. SolidParticleSystem.prototype.updateParticle = function (particle) {
  44166. return particle;
  44167. };
  44168. /**
  44169. * Updates a vertex of a particle : it can be overwritten by the user.
  44170. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  44171. * @param particle the current particle
  44172. * @param vertex the current index of the current particle
  44173. * @param pt the index of the current vertex in the particle shape
  44174. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  44175. * ex : just set a vertex particle position
  44176. */
  44177. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  44178. return vertex;
  44179. };
  44180. /**
  44181. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  44182. * This does nothing and may be overwritten by the user.
  44183. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  44184. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  44185. * @param update the boolean update value actually passed to setParticles()
  44186. */
  44187. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  44188. };
  44189. /**
  44190. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  44191. * This will be passed three parameters.
  44192. * This does nothing and may be overwritten by the user.
  44193. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  44194. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  44195. * @param update the boolean update value actually passed to setParticles()
  44196. */
  44197. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  44198. };
  44199. return SolidParticleSystem;
  44200. }());
  44201. BABYLON.SolidParticleSystem = SolidParticleSystem;
  44202. })(BABYLON || (BABYLON = {}));
  44203. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  44204. /// <reference path="babylon.mesh.ts" />
  44205. var BABYLON;
  44206. (function (BABYLON) {
  44207. var GroundMesh = (function (_super) {
  44208. __extends(GroundMesh, _super);
  44209. function GroundMesh(name, scene) {
  44210. var _this = _super.call(this, name, scene) || this;
  44211. _this.generateOctree = false;
  44212. _this._worldInverse = new BABYLON.Matrix();
  44213. return _this;
  44214. }
  44215. GroundMesh.prototype.getClassName = function () {
  44216. return "GroundMesh";
  44217. };
  44218. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  44219. get: function () {
  44220. return Math.min(this._subdivisionsX, this._subdivisionsY);
  44221. },
  44222. enumerable: true,
  44223. configurable: true
  44224. });
  44225. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  44226. get: function () {
  44227. return this._subdivisionsX;
  44228. },
  44229. enumerable: true,
  44230. configurable: true
  44231. });
  44232. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  44233. get: function () {
  44234. return this._subdivisionsY;
  44235. },
  44236. enumerable: true,
  44237. configurable: true
  44238. });
  44239. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  44240. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  44241. this._subdivisionsX = chunksCount;
  44242. this._subdivisionsY = chunksCount;
  44243. this.subdivide(chunksCount);
  44244. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  44245. };
  44246. /**
  44247. * Returns a height (y) value in the Worl system :
  44248. * the ground altitude at the coordinates (x, z) expressed in the World system.
  44249. * Returns the ground y position if (x, z) are outside the ground surface.
  44250. */
  44251. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  44252. var world = this.getWorldMatrix();
  44253. var invMat = BABYLON.Tmp.Matrix[5];
  44254. world.invertToRef(invMat);
  44255. var tmpVect = BABYLON.Tmp.Vector3[8];
  44256. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  44257. x = tmpVect.x;
  44258. z = tmpVect.z;
  44259. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  44260. return this.position.y;
  44261. }
  44262. if (!this._heightQuads || this._heightQuads.length == 0) {
  44263. this._initHeightQuads();
  44264. this._computeHeightQuads();
  44265. }
  44266. var facet = this._getFacetAt(x, z);
  44267. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  44268. // return y in the World system
  44269. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  44270. return tmpVect.y;
  44271. };
  44272. /**
  44273. * Returns a normalized vector (Vector3) orthogonal to the ground
  44274. * at the ground coordinates (x, z) expressed in the World system.
  44275. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  44276. */
  44277. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  44278. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  44279. this.getNormalAtCoordinatesToRef(x, z, normal);
  44280. return normal;
  44281. };
  44282. /**
  44283. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  44284. * at the ground coordinates (x, z) expressed in the World system.
  44285. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  44286. * Returns the GroundMesh.
  44287. */
  44288. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  44289. var world = this.getWorldMatrix();
  44290. var tmpMat = BABYLON.Tmp.Matrix[5];
  44291. world.invertToRef(tmpMat);
  44292. var tmpVect = BABYLON.Tmp.Vector3[8];
  44293. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  44294. x = tmpVect.x;
  44295. z = tmpVect.z;
  44296. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  44297. return this;
  44298. }
  44299. if (!this._heightQuads || this._heightQuads.length == 0) {
  44300. this._initHeightQuads();
  44301. this._computeHeightQuads();
  44302. }
  44303. var facet = this._getFacetAt(x, z);
  44304. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  44305. return this;
  44306. };
  44307. /**
  44308. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  44309. * if the ground has been updated.
  44310. * This can be used in the render loop.
  44311. * Returns the GroundMesh.
  44312. */
  44313. GroundMesh.prototype.updateCoordinateHeights = function () {
  44314. if (!this._heightQuads || this._heightQuads.length == 0) {
  44315. this._initHeightQuads();
  44316. }
  44317. this._computeHeightQuads();
  44318. return this;
  44319. };
  44320. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  44321. GroundMesh.prototype._getFacetAt = function (x, z) {
  44322. // retrieve col and row from x, z coordinates in the ground local system
  44323. var subdivisionsX = this._subdivisionsX;
  44324. var subdivisionsY = this._subdivisionsY;
  44325. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  44326. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  44327. var quad = this._heightQuads[row * this._subdivisionsX + col];
  44328. var facet;
  44329. if (z < quad.slope.x * x + quad.slope.y) {
  44330. facet = quad.facet1;
  44331. }
  44332. else {
  44333. facet = quad.facet2;
  44334. }
  44335. return facet;
  44336. };
  44337. // Creates and populates the heightMap array with "facet" elements :
  44338. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  44339. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  44340. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  44341. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  44342. // Returns the GroundMesh.
  44343. GroundMesh.prototype._initHeightQuads = function () {
  44344. var subdivisionsX = this._subdivisionsX;
  44345. var subdivisionsY = this._subdivisionsY;
  44346. this._heightQuads = new Array();
  44347. for (var row = 0; row < subdivisionsY; row++) {
  44348. for (var col = 0; col < subdivisionsX; col++) {
  44349. 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) };
  44350. this._heightQuads[row * subdivisionsX + col] = quad;
  44351. }
  44352. }
  44353. return this;
  44354. };
  44355. // Compute each quad element values and update the the heightMap array :
  44356. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  44357. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  44358. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  44359. // Returns the GroundMesh.
  44360. GroundMesh.prototype._computeHeightQuads = function () {
  44361. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44362. var v1 = BABYLON.Tmp.Vector3[3];
  44363. var v2 = BABYLON.Tmp.Vector3[2];
  44364. var v3 = BABYLON.Tmp.Vector3[1];
  44365. var v4 = BABYLON.Tmp.Vector3[0];
  44366. var v1v2 = BABYLON.Tmp.Vector3[4];
  44367. var v1v3 = BABYLON.Tmp.Vector3[5];
  44368. var v1v4 = BABYLON.Tmp.Vector3[6];
  44369. var norm1 = BABYLON.Tmp.Vector3[7];
  44370. var norm2 = BABYLON.Tmp.Vector3[8];
  44371. var i = 0;
  44372. var j = 0;
  44373. var k = 0;
  44374. var cd = 0; // 2D slope coefficient : z = cd * x + h
  44375. var h = 0;
  44376. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  44377. var d2 = 0;
  44378. var subdivisionsX = this._subdivisionsX;
  44379. var subdivisionsY = this._subdivisionsY;
  44380. for (var row = 0; row < subdivisionsY; row++) {
  44381. for (var col = 0; col < subdivisionsX; col++) {
  44382. i = col * 3;
  44383. j = row * (subdivisionsX + 1) * 3;
  44384. k = (row + 1) * (subdivisionsX + 1) * 3;
  44385. v1.x = positions[j + i];
  44386. v1.y = positions[j + i + 1];
  44387. v1.z = positions[j + i + 2];
  44388. v2.x = positions[j + i + 3];
  44389. v2.y = positions[j + i + 4];
  44390. v2.z = positions[j + i + 5];
  44391. v3.x = positions[k + i];
  44392. v3.y = positions[k + i + 1];
  44393. v3.z = positions[k + i + 2];
  44394. v4.x = positions[k + i + 3];
  44395. v4.y = positions[k + i + 4];
  44396. v4.z = positions[k + i + 5];
  44397. // 2D slope V1V4
  44398. cd = (v4.z - v1.z) / (v4.x - v1.x);
  44399. h = v1.z - cd * v1.x; // v1 belongs to the slope
  44400. // facet equations :
  44401. // we compute each facet normal vector
  44402. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  44403. // we compute the value d by applying the equation to v1 which belongs to the plane
  44404. // then we store the facet equation in a Vector4
  44405. v2.subtractToRef(v1, v1v2);
  44406. v3.subtractToRef(v1, v1v3);
  44407. v4.subtractToRef(v1, v1v4);
  44408. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  44409. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  44410. norm1.normalize();
  44411. norm2.normalize();
  44412. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  44413. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  44414. var quad = this._heightQuads[row * subdivisionsX + col];
  44415. quad.slope.copyFromFloats(cd, h);
  44416. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  44417. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  44418. }
  44419. }
  44420. return this;
  44421. };
  44422. GroundMesh.prototype.serialize = function (serializationObject) {
  44423. _super.prototype.serialize.call(this, serializationObject);
  44424. serializationObject.subdivisionsX = this._subdivisionsX;
  44425. serializationObject.subdivisionsY = this._subdivisionsY;
  44426. serializationObject.minX = this._minX;
  44427. serializationObject.maxX = this._maxX;
  44428. serializationObject.minZ = this._minZ;
  44429. serializationObject.maxZ = this._maxZ;
  44430. serializationObject.width = this._width;
  44431. serializationObject.height = this._height;
  44432. };
  44433. GroundMesh.Parse = function (parsedMesh, scene) {
  44434. var result = new GroundMesh(parsedMesh.name, scene);
  44435. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  44436. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  44437. result._minX = parsedMesh.minX;
  44438. result._maxX = parsedMesh.maxX;
  44439. result._minZ = parsedMesh.minZ;
  44440. result._maxZ = parsedMesh.maxZ;
  44441. result._width = parsedMesh.width;
  44442. result._height = parsedMesh.height;
  44443. return result;
  44444. };
  44445. return GroundMesh;
  44446. }(BABYLON.Mesh));
  44447. BABYLON.GroundMesh = GroundMesh;
  44448. })(BABYLON || (BABYLON = {}));
  44449. //# sourceMappingURL=babylon.groundMesh.js.map
  44450. var BABYLON;
  44451. (function (BABYLON) {
  44452. /**
  44453. * Creates an instance based on a source mesh.
  44454. */
  44455. var InstancedMesh = (function (_super) {
  44456. __extends(InstancedMesh, _super);
  44457. function InstancedMesh(name, source) {
  44458. var _this = _super.call(this, name, source.getScene()) || this;
  44459. source.instances.push(_this);
  44460. _this._sourceMesh = source;
  44461. _this.position.copyFrom(source.position);
  44462. _this.rotation.copyFrom(source.rotation);
  44463. _this.scaling.copyFrom(source.scaling);
  44464. if (source.rotationQuaternion) {
  44465. _this.rotationQuaternion = source.rotationQuaternion.clone();
  44466. }
  44467. _this.infiniteDistance = source.infiniteDistance;
  44468. _this.setPivotMatrix(source.getPivotMatrix());
  44469. _this.refreshBoundingInfo();
  44470. _this._syncSubMeshes();
  44471. return _this;
  44472. }
  44473. /**
  44474. * Returns the string "InstancedMesh".
  44475. */
  44476. InstancedMesh.prototype.getClassName = function () {
  44477. return "InstancedMesh";
  44478. };
  44479. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  44480. // Methods
  44481. get: function () {
  44482. return this._sourceMesh.receiveShadows;
  44483. },
  44484. enumerable: true,
  44485. configurable: true
  44486. });
  44487. Object.defineProperty(InstancedMesh.prototype, "material", {
  44488. get: function () {
  44489. return this._sourceMesh.material;
  44490. },
  44491. enumerable: true,
  44492. configurable: true
  44493. });
  44494. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  44495. get: function () {
  44496. return this._sourceMesh.visibility;
  44497. },
  44498. enumerable: true,
  44499. configurable: true
  44500. });
  44501. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  44502. get: function () {
  44503. return this._sourceMesh.skeleton;
  44504. },
  44505. enumerable: true,
  44506. configurable: true
  44507. });
  44508. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  44509. get: function () {
  44510. return this._sourceMesh.renderingGroupId;
  44511. },
  44512. enumerable: true,
  44513. configurable: true
  44514. });
  44515. /**
  44516. * Returns the total number of vertices (integer).
  44517. */
  44518. InstancedMesh.prototype.getTotalVertices = function () {
  44519. return this._sourceMesh.getTotalVertices();
  44520. };
  44521. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  44522. get: function () {
  44523. return this._sourceMesh;
  44524. },
  44525. enumerable: true,
  44526. configurable: true
  44527. });
  44528. /**
  44529. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  44530. */
  44531. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  44532. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  44533. };
  44534. /**
  44535. * Sets the vertex data of the mesh geometry for the requested `kind`.
  44536. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  44537. * The `data` are either a numeric array either a Float32Array.
  44538. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  44539. * 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).
  44540. * Note that a new underlying VertexBuffer object is created each call.
  44541. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  44542. *
  44543. * Possible `kind` values :
  44544. * - BABYLON.VertexBuffer.PositionKind
  44545. * - BABYLON.VertexBuffer.UVKind
  44546. * - BABYLON.VertexBuffer.UV2Kind
  44547. * - BABYLON.VertexBuffer.UV3Kind
  44548. * - BABYLON.VertexBuffer.UV4Kind
  44549. * - BABYLON.VertexBuffer.UV5Kind
  44550. * - BABYLON.VertexBuffer.UV6Kind
  44551. * - BABYLON.VertexBuffer.ColorKind
  44552. * - BABYLON.VertexBuffer.MatricesIndicesKind
  44553. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  44554. * - BABYLON.VertexBuffer.MatricesWeightsKind
  44555. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  44556. *
  44557. * Returns the Mesh.
  44558. */
  44559. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  44560. if (this.sourceMesh) {
  44561. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  44562. }
  44563. return this.sourceMesh;
  44564. };
  44565. /**
  44566. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  44567. * If the mesh has no geometry, it is simply returned as it is.
  44568. * The `data` are either a numeric array either a Float32Array.
  44569. * No new underlying VertexBuffer object is created.
  44570. * 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.
  44571. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  44572. *
  44573. * Possible `kind` values :
  44574. * - BABYLON.VertexBuffer.PositionKind
  44575. * - BABYLON.VertexBuffer.UVKind
  44576. * - BABYLON.VertexBuffer.UV2Kind
  44577. * - BABYLON.VertexBuffer.UV3Kind
  44578. * - BABYLON.VertexBuffer.UV4Kind
  44579. * - BABYLON.VertexBuffer.UV5Kind
  44580. * - BABYLON.VertexBuffer.UV6Kind
  44581. * - BABYLON.VertexBuffer.ColorKind
  44582. * - BABYLON.VertexBuffer.MatricesIndicesKind
  44583. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  44584. * - BABYLON.VertexBuffer.MatricesWeightsKind
  44585. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  44586. *
  44587. * Returns the Mesh.
  44588. */
  44589. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  44590. if (this.sourceMesh) {
  44591. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  44592. }
  44593. return this.sourceMesh;
  44594. };
  44595. /**
  44596. * Sets the mesh indices.
  44597. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  44598. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  44599. * This method creates a new index buffer each call.
  44600. * Returns the Mesh.
  44601. */
  44602. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  44603. if (this.sourceMesh) {
  44604. this.sourceMesh.setIndices(indices, totalVertices);
  44605. }
  44606. return this.sourceMesh;
  44607. };
  44608. /**
  44609. * Boolean : True if the mesh owns the requested kind of data.
  44610. */
  44611. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  44612. return this._sourceMesh.isVerticesDataPresent(kind);
  44613. };
  44614. /**
  44615. * Returns an array of indices (IndicesArray).
  44616. */
  44617. InstancedMesh.prototype.getIndices = function () {
  44618. return this._sourceMesh.getIndices();
  44619. };
  44620. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  44621. get: function () {
  44622. return this._sourceMesh._positions;
  44623. },
  44624. enumerable: true,
  44625. configurable: true
  44626. });
  44627. /**
  44628. * Sets a new updated BoundingInfo to the mesh.
  44629. * Returns the mesh.
  44630. */
  44631. InstancedMesh.prototype.refreshBoundingInfo = function () {
  44632. var meshBB = this._sourceMesh.getBoundingInfo();
  44633. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  44634. this._updateBoundingInfo();
  44635. return this;
  44636. };
  44637. InstancedMesh.prototype._preActivate = function () {
  44638. if (this._currentLOD) {
  44639. this._currentLOD._preActivate();
  44640. }
  44641. return this;
  44642. };
  44643. InstancedMesh.prototype._activate = function (renderId) {
  44644. if (this._currentLOD) {
  44645. this._currentLOD._registerInstanceForRenderId(this, renderId);
  44646. }
  44647. return this;
  44648. };
  44649. /**
  44650. * Returns the current associated LOD AbstractMesh.
  44651. */
  44652. InstancedMesh.prototype.getLOD = function (camera) {
  44653. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  44654. if (this._currentLOD === this.sourceMesh) {
  44655. return this;
  44656. }
  44657. return this._currentLOD;
  44658. };
  44659. InstancedMesh.prototype._syncSubMeshes = function () {
  44660. this.releaseSubMeshes();
  44661. if (this._sourceMesh.subMeshes) {
  44662. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  44663. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  44664. }
  44665. }
  44666. return this;
  44667. };
  44668. InstancedMesh.prototype._generatePointsArray = function () {
  44669. return this._sourceMesh._generatePointsArray();
  44670. };
  44671. /**
  44672. * Creates a new InstancedMesh from the current mesh.
  44673. * - name (string) : the cloned mesh name
  44674. * - newParent (optional Node) : the optional Node to parent the clone to.
  44675. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  44676. *
  44677. * Returns the clone.
  44678. */
  44679. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  44680. var result = this._sourceMesh.createInstance(name);
  44681. // Deep copy
  44682. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  44683. // Bounding info
  44684. this.refreshBoundingInfo();
  44685. // Parent
  44686. if (newParent) {
  44687. result.parent = newParent;
  44688. }
  44689. if (!doNotCloneChildren) {
  44690. // Children
  44691. for (var index = 0; index < this.getScene().meshes.length; index++) {
  44692. var mesh = this.getScene().meshes[index];
  44693. if (mesh.parent === this) {
  44694. mesh.clone(mesh.name, result);
  44695. }
  44696. }
  44697. }
  44698. result.computeWorldMatrix(true);
  44699. return result;
  44700. };
  44701. /**
  44702. * Disposes the InstancedMesh.
  44703. * Returns nothing.
  44704. */
  44705. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  44706. // Remove from mesh
  44707. var index = this._sourceMesh.instances.indexOf(this);
  44708. this._sourceMesh.instances.splice(index, 1);
  44709. _super.prototype.dispose.call(this, doNotRecurse);
  44710. };
  44711. return InstancedMesh;
  44712. }(BABYLON.AbstractMesh));
  44713. BABYLON.InstancedMesh = InstancedMesh;
  44714. })(BABYLON || (BABYLON = {}));
  44715. //# sourceMappingURL=babylon.instancedMesh.js.map
  44716. /// <reference path="babylon.mesh.ts" />
  44717. var BABYLON;
  44718. (function (BABYLON) {
  44719. var LinesMesh = (function (_super) {
  44720. __extends(LinesMesh, _super);
  44721. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  44722. if (parent === void 0) { parent = null; }
  44723. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  44724. _this.useVertexColor = useVertexColor;
  44725. _this.color = new BABYLON.Color3(1, 1, 1);
  44726. _this.alpha = 1;
  44727. if (source) {
  44728. _this.color = source.color.clone();
  44729. _this.alpha = source.alpha;
  44730. _this.useVertexColor = source.useVertexColor;
  44731. }
  44732. _this._intersectionThreshold = 0.1;
  44733. var options = {
  44734. attributes: [BABYLON.VertexBuffer.PositionKind],
  44735. uniforms: ["world", "viewProjection"],
  44736. needAlphaBlending: false,
  44737. };
  44738. if (!useVertexColor) {
  44739. options.uniforms.push("color");
  44740. options.needAlphaBlending = true;
  44741. }
  44742. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  44743. return _this;
  44744. }
  44745. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  44746. /**
  44747. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  44748. * This margin is expressed in world space coordinates, so its value may vary.
  44749. * Default value is 0.1
  44750. * @returns the intersection Threshold value.
  44751. */
  44752. get: function () {
  44753. return this._intersectionThreshold;
  44754. },
  44755. /**
  44756. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  44757. * This margin is expressed in world space coordinates, so its value may vary.
  44758. * @param value the new threshold to apply
  44759. */
  44760. set: function (value) {
  44761. if (this._intersectionThreshold === value) {
  44762. return;
  44763. }
  44764. this._intersectionThreshold = value;
  44765. if (this.geometry) {
  44766. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  44767. }
  44768. },
  44769. enumerable: true,
  44770. configurable: true
  44771. });
  44772. /**
  44773. * Returns the string "LineMesh"
  44774. */
  44775. LinesMesh.prototype.getClassName = function () {
  44776. return "LinesMesh";
  44777. };
  44778. Object.defineProperty(LinesMesh.prototype, "material", {
  44779. get: function () {
  44780. return this._colorShader;
  44781. },
  44782. enumerable: true,
  44783. configurable: true
  44784. });
  44785. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  44786. get: function () {
  44787. return false;
  44788. },
  44789. enumerable: true,
  44790. configurable: true
  44791. });
  44792. LinesMesh.prototype.createInstance = function (name) {
  44793. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  44794. return null;
  44795. };
  44796. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  44797. // VBOs
  44798. this._geometry._bind(this._colorShader.getEffect());
  44799. // Color
  44800. if (!this.useVertexColor) {
  44801. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  44802. }
  44803. return this;
  44804. };
  44805. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  44806. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  44807. return this;
  44808. }
  44809. var engine = this.getScene().getEngine();
  44810. // Draw order
  44811. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  44812. return this;
  44813. };
  44814. LinesMesh.prototype.dispose = function (doNotRecurse) {
  44815. this._colorShader.dispose();
  44816. _super.prototype.dispose.call(this, doNotRecurse);
  44817. };
  44818. /**
  44819. * Returns a new LineMesh object cloned from the current one.
  44820. */
  44821. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  44822. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  44823. };
  44824. return LinesMesh;
  44825. }(BABYLON.Mesh));
  44826. BABYLON.LinesMesh = LinesMesh;
  44827. })(BABYLON || (BABYLON = {}));
  44828. //# sourceMappingURL=babylon.linesMesh.js.map
  44829. var BABYLON;
  44830. (function (BABYLON) {
  44831. var ShaderMaterial = (function (_super) {
  44832. __extends(ShaderMaterial, _super);
  44833. function ShaderMaterial(name, scene, shaderPath, options) {
  44834. var _this = _super.call(this, name, scene) || this;
  44835. _this._textures = {};
  44836. _this._textureArrays = {};
  44837. _this._floats = {};
  44838. _this._floatsArrays = {};
  44839. _this._colors3 = {};
  44840. _this._colors3Arrays = {};
  44841. _this._colors4 = {};
  44842. _this._vectors2 = {};
  44843. _this._vectors3 = {};
  44844. _this._vectors4 = {};
  44845. _this._matrices = {};
  44846. _this._matrices3x3 = {};
  44847. _this._matrices2x2 = {};
  44848. _this._vectors3Arrays = {};
  44849. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  44850. _this._shaderPath = shaderPath;
  44851. options.needAlphaBlending = options.needAlphaBlending || false;
  44852. options.needAlphaTesting = options.needAlphaTesting || false;
  44853. options.attributes = options.attributes || ["position", "normal", "uv"];
  44854. options.uniforms = options.uniforms || ["worldViewProjection"];
  44855. options.uniformBuffers = options.uniformBuffers || [];
  44856. options.samplers = options.samplers || [];
  44857. options.defines = options.defines || [];
  44858. _this._options = options;
  44859. return _this;
  44860. }
  44861. ShaderMaterial.prototype.getClassName = function () {
  44862. return "ShaderMaterial";
  44863. };
  44864. ShaderMaterial.prototype.needAlphaBlending = function () {
  44865. return this._options.needAlphaBlending;
  44866. };
  44867. ShaderMaterial.prototype.needAlphaTesting = function () {
  44868. return this._options.needAlphaTesting;
  44869. };
  44870. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  44871. if (this._options.uniforms.indexOf(uniformName) === -1) {
  44872. this._options.uniforms.push(uniformName);
  44873. }
  44874. };
  44875. ShaderMaterial.prototype.setTexture = function (name, texture) {
  44876. if (this._options.samplers.indexOf(name) === -1) {
  44877. this._options.samplers.push(name);
  44878. }
  44879. this._textures[name] = texture;
  44880. return this;
  44881. };
  44882. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  44883. if (this._options.samplers.indexOf(name) === -1) {
  44884. this._options.samplers.push(name);
  44885. }
  44886. this._checkUniform(name);
  44887. this._textureArrays[name] = textures;
  44888. return this;
  44889. };
  44890. ShaderMaterial.prototype.setFloat = function (name, value) {
  44891. this._checkUniform(name);
  44892. this._floats[name] = value;
  44893. return this;
  44894. };
  44895. ShaderMaterial.prototype.setFloats = function (name, value) {
  44896. this._checkUniform(name);
  44897. this._floatsArrays[name] = value;
  44898. return this;
  44899. };
  44900. ShaderMaterial.prototype.setColor3 = function (name, value) {
  44901. this._checkUniform(name);
  44902. this._colors3[name] = value;
  44903. return this;
  44904. };
  44905. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  44906. this._checkUniform(name);
  44907. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  44908. color.toArray(arr, arr.length);
  44909. return arr;
  44910. }, []);
  44911. return this;
  44912. };
  44913. ShaderMaterial.prototype.setColor4 = function (name, value) {
  44914. this._checkUniform(name);
  44915. this._colors4[name] = value;
  44916. return this;
  44917. };
  44918. ShaderMaterial.prototype.setVector2 = function (name, value) {
  44919. this._checkUniform(name);
  44920. this._vectors2[name] = value;
  44921. return this;
  44922. };
  44923. ShaderMaterial.prototype.setVector3 = function (name, value) {
  44924. this._checkUniform(name);
  44925. this._vectors3[name] = value;
  44926. return this;
  44927. };
  44928. ShaderMaterial.prototype.setVector4 = function (name, value) {
  44929. this._checkUniform(name);
  44930. this._vectors4[name] = value;
  44931. return this;
  44932. };
  44933. ShaderMaterial.prototype.setMatrix = function (name, value) {
  44934. this._checkUniform(name);
  44935. this._matrices[name] = value;
  44936. return this;
  44937. };
  44938. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  44939. this._checkUniform(name);
  44940. this._matrices3x3[name] = value;
  44941. return this;
  44942. };
  44943. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  44944. this._checkUniform(name);
  44945. this._matrices2x2[name] = value;
  44946. return this;
  44947. };
  44948. ShaderMaterial.prototype.setArray3 = function (name, value) {
  44949. this._checkUniform(name);
  44950. this._vectors3Arrays[name] = value;
  44951. return this;
  44952. };
  44953. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  44954. if (!mesh) {
  44955. return true;
  44956. }
  44957. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  44958. return false;
  44959. }
  44960. return false;
  44961. };
  44962. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  44963. var scene = this.getScene();
  44964. var engine = scene.getEngine();
  44965. if (!this.checkReadyOnEveryCall) {
  44966. if (this._renderId === scene.getRenderId()) {
  44967. if (this._checkCache(scene, mesh, useInstances)) {
  44968. return true;
  44969. }
  44970. }
  44971. }
  44972. // Instances
  44973. var defines = [];
  44974. var attribs = [];
  44975. var fallbacks = new BABYLON.EffectFallbacks();
  44976. if (useInstances) {
  44977. defines.push("#define INSTANCES");
  44978. }
  44979. for (var index = 0; index < this._options.defines.length; index++) {
  44980. defines.push(this._options.defines[index]);
  44981. }
  44982. for (var index = 0; index < this._options.attributes.length; index++) {
  44983. attribs.push(this._options.attributes[index]);
  44984. }
  44985. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  44986. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44987. defines.push("#define VERTEXCOLOR");
  44988. }
  44989. // Bones
  44990. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  44991. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  44992. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  44993. if (mesh.numBoneInfluencers > 4) {
  44994. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  44995. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  44996. }
  44997. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  44998. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  44999. fallbacks.addCPUSkinningFallback(0, mesh);
  45000. if (this._options.uniforms.indexOf("mBones") === -1) {
  45001. this._options.uniforms.push("mBones");
  45002. }
  45003. }
  45004. else {
  45005. defines.push("#define NUM_BONE_INFLUENCERS 0");
  45006. }
  45007. // Textures
  45008. for (var name in this._textures) {
  45009. if (!this._textures[name].isReady()) {
  45010. return false;
  45011. }
  45012. }
  45013. // Alpha test
  45014. if (engine.getAlphaTesting()) {
  45015. defines.push("#define ALPHATEST");
  45016. }
  45017. var previousEffect = this._effect;
  45018. var join = defines.join("\n");
  45019. this._effect = engine.createEffect(this._shaderPath, {
  45020. attributes: attribs,
  45021. uniformsNames: this._options.uniforms,
  45022. uniformBuffersNames: this._options.uniformBuffers,
  45023. samplers: this._options.samplers,
  45024. defines: join,
  45025. fallbacks: fallbacks,
  45026. onCompiled: this.onCompiled,
  45027. onError: this.onError
  45028. }, engine);
  45029. if (!this._effect.isReady()) {
  45030. return false;
  45031. }
  45032. if (previousEffect !== this._effect) {
  45033. scene.resetCachedMaterial();
  45034. }
  45035. this._renderId = scene.getRenderId();
  45036. return true;
  45037. };
  45038. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  45039. var scene = this.getScene();
  45040. if (this._options.uniforms.indexOf("world") !== -1) {
  45041. this._effect.setMatrix("world", world);
  45042. }
  45043. if (this._options.uniforms.indexOf("worldView") !== -1) {
  45044. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  45045. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  45046. }
  45047. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  45048. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  45049. }
  45050. };
  45051. ShaderMaterial.prototype.bind = function (world, mesh) {
  45052. // Std values
  45053. this.bindOnlyWorldMatrix(world);
  45054. if (this.getScene().getCachedMaterial() !== this) {
  45055. if (this._options.uniforms.indexOf("view") !== -1) {
  45056. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  45057. }
  45058. if (this._options.uniforms.indexOf("projection") !== -1) {
  45059. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  45060. }
  45061. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  45062. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  45063. }
  45064. // Bones
  45065. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  45066. var name;
  45067. // Texture
  45068. for (name in this._textures) {
  45069. this._effect.setTexture(name, this._textures[name]);
  45070. }
  45071. // Texture arrays
  45072. for (name in this._textureArrays) {
  45073. this._effect.setTextureArray(name, this._textureArrays[name]);
  45074. }
  45075. // Float
  45076. for (name in this._floats) {
  45077. this._effect.setFloat(name, this._floats[name]);
  45078. }
  45079. // Float s
  45080. for (name in this._floatsArrays) {
  45081. this._effect.setArray(name, this._floatsArrays[name]);
  45082. }
  45083. // Color3
  45084. for (name in this._colors3) {
  45085. this._effect.setColor3(name, this._colors3[name]);
  45086. }
  45087. for (name in this._colors3Arrays) {
  45088. this._effect.setArray3(name, this._colors3Arrays[name]);
  45089. }
  45090. // Color4
  45091. for (name in this._colors4) {
  45092. var color = this._colors4[name];
  45093. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  45094. }
  45095. // Vector2
  45096. for (name in this._vectors2) {
  45097. this._effect.setVector2(name, this._vectors2[name]);
  45098. }
  45099. // Vector3
  45100. for (name in this._vectors3) {
  45101. this._effect.setVector3(name, this._vectors3[name]);
  45102. }
  45103. // Vector4
  45104. for (name in this._vectors4) {
  45105. this._effect.setVector4(name, this._vectors4[name]);
  45106. }
  45107. // Matrix
  45108. for (name in this._matrices) {
  45109. this._effect.setMatrix(name, this._matrices[name]);
  45110. }
  45111. // Matrix 3x3
  45112. for (name in this._matrices3x3) {
  45113. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  45114. }
  45115. // Matrix 2x2
  45116. for (name in this._matrices2x2) {
  45117. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  45118. }
  45119. // Vector3Array
  45120. for (name in this._vectors3Arrays) {
  45121. this._effect.setArray3(name, this._vectors3Arrays[name]);
  45122. }
  45123. }
  45124. this._afterBind(mesh);
  45125. };
  45126. ShaderMaterial.prototype.getActiveTextures = function () {
  45127. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45128. for (var name in this._textures) {
  45129. activeTextures.push(this._textures[name]);
  45130. }
  45131. for (var name in this._textureArrays) {
  45132. var array = this._textureArrays[name];
  45133. for (var index = 0; index < array.length; index++) {
  45134. activeTextures.push(array[index]);
  45135. }
  45136. }
  45137. return activeTextures;
  45138. };
  45139. ShaderMaterial.prototype.hasTexture = function (texture) {
  45140. if (_super.prototype.hasTexture.call(this, texture)) {
  45141. return true;
  45142. }
  45143. for (var name in this._textures) {
  45144. if (this._textures[name] === texture) {
  45145. return true;
  45146. }
  45147. }
  45148. for (var name in this._textureArrays) {
  45149. var array = this._textureArrays[name];
  45150. for (var index = 0; index < array.length; index++) {
  45151. if (array[index] === texture) {
  45152. return true;
  45153. }
  45154. }
  45155. }
  45156. return false;
  45157. };
  45158. ShaderMaterial.prototype.clone = function (name) {
  45159. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  45160. return newShaderMaterial;
  45161. };
  45162. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45163. if (forceDisposeTextures) {
  45164. var name;
  45165. for (name in this._textures) {
  45166. this._textures[name].dispose();
  45167. }
  45168. for (name in this._textureArrays) {
  45169. var array = this._textureArrays[name];
  45170. for (var index = 0; index < array.length; index++) {
  45171. array[index].dispose();
  45172. }
  45173. }
  45174. }
  45175. this._textures = {};
  45176. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45177. };
  45178. ShaderMaterial.prototype.serialize = function () {
  45179. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45180. serializationObject.customType = "BABYLON.ShaderMaterial";
  45181. serializationObject.options = this._options;
  45182. serializationObject.shaderPath = this._shaderPath;
  45183. var name;
  45184. // Texture
  45185. serializationObject.textures = {};
  45186. for (name in this._textures) {
  45187. serializationObject.textures[name] = this._textures[name].serialize();
  45188. }
  45189. // Texture arrays
  45190. serializationObject.textureArrays = {};
  45191. for (name in this._textureArrays) {
  45192. serializationObject.textureArrays[name] = [];
  45193. var array = this._textureArrays[name];
  45194. for (var index = 0; index < array.length; index++) {
  45195. serializationObject.textureArrays[name].push(array[index].serialize());
  45196. }
  45197. }
  45198. // Float
  45199. serializationObject.floats = {};
  45200. for (name in this._floats) {
  45201. serializationObject.floats[name] = this._floats[name];
  45202. }
  45203. // Float s
  45204. serializationObject.floatArrays = {};
  45205. for (name in this._floatsArrays) {
  45206. serializationObject.floatArrays[name] = this._floatsArrays[name];
  45207. }
  45208. // Color3
  45209. serializationObject.colors3 = {};
  45210. for (name in this._colors3) {
  45211. serializationObject.colors3[name] = this._colors3[name].asArray();
  45212. }
  45213. // Color3 array
  45214. serializationObject.colors3Arrays = {};
  45215. for (name in this._colors3Arrays) {
  45216. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  45217. }
  45218. // Color4
  45219. serializationObject.colors4 = {};
  45220. for (name in this._colors4) {
  45221. serializationObject.colors4[name] = this._colors4[name].asArray();
  45222. }
  45223. // Vector2
  45224. serializationObject.vectors2 = {};
  45225. for (name in this._vectors2) {
  45226. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  45227. }
  45228. // Vector3
  45229. serializationObject.vectors3 = {};
  45230. for (name in this._vectors3) {
  45231. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  45232. }
  45233. // Vector4
  45234. serializationObject.vectors4 = {};
  45235. for (name in this._vectors4) {
  45236. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  45237. }
  45238. // Matrix
  45239. serializationObject.matrices = {};
  45240. for (name in this._matrices) {
  45241. serializationObject.matrices[name] = this._matrices[name].asArray();
  45242. }
  45243. // Matrix 3x3
  45244. serializationObject.matrices3x3 = {};
  45245. for (name in this._matrices3x3) {
  45246. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  45247. }
  45248. // Matrix 2x2
  45249. serializationObject.matrices2x2 = {};
  45250. for (name in this._matrices2x2) {
  45251. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  45252. }
  45253. // Vector3Array
  45254. serializationObject.vectors3Arrays = {};
  45255. for (name in this._vectors3Arrays) {
  45256. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  45257. }
  45258. return serializationObject;
  45259. };
  45260. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  45261. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  45262. var name;
  45263. // Texture
  45264. for (name in source.textures) {
  45265. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  45266. }
  45267. // Texture arrays
  45268. for (name in source.textureArrays) {
  45269. var array = source.textureArrays[name];
  45270. var textureArray = new Array();
  45271. for (var index = 0; index < array.length; index++) {
  45272. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  45273. }
  45274. material.setTextureArray(name, textureArray);
  45275. }
  45276. // Float
  45277. for (name in source.floats) {
  45278. material.setFloat(name, source.floats[name]);
  45279. }
  45280. // Float s
  45281. for (name in source.floatsArrays) {
  45282. material.setFloats(name, source.floatsArrays[name]);
  45283. }
  45284. // Color3
  45285. for (name in source.colors3) {
  45286. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  45287. }
  45288. // Color3 arrays
  45289. for (name in source.colors3Arrays) {
  45290. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  45291. if (i % 3 === 0) {
  45292. arr.push([num]);
  45293. }
  45294. else {
  45295. arr[arr.length - 1].push(num);
  45296. }
  45297. return arr;
  45298. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  45299. material.setColor3Array(name, colors);
  45300. }
  45301. // Color4
  45302. for (name in source.colors4) {
  45303. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  45304. }
  45305. // Vector2
  45306. for (name in source.vectors2) {
  45307. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  45308. }
  45309. // Vector3
  45310. for (name in source.vectors3) {
  45311. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  45312. }
  45313. // Vector4
  45314. for (name in source.vectors4) {
  45315. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  45316. }
  45317. // Matrix
  45318. for (name in source.matrices) {
  45319. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  45320. }
  45321. // Matrix 3x3
  45322. for (name in source.matrices3x3) {
  45323. material.setMatrix3x3(name, source.matrices3x3[name]);
  45324. }
  45325. // Matrix 2x2
  45326. for (name in source.matrices2x2) {
  45327. material.setMatrix2x2(name, source.matrices2x2[name]);
  45328. }
  45329. // Vector3Array
  45330. for (name in source.vectors3Arrays) {
  45331. material.setArray3(name, source.vectors3Arrays[name]);
  45332. }
  45333. return material;
  45334. };
  45335. return ShaderMaterial;
  45336. }(BABYLON.Material));
  45337. BABYLON.ShaderMaterial = ShaderMaterial;
  45338. })(BABYLON || (BABYLON = {}));
  45339. //# sourceMappingURL=babylon.shaderMaterial.js.map
  45340. var BABYLON;
  45341. (function (BABYLON) {
  45342. var MeshBuilder = (function () {
  45343. function MeshBuilder() {
  45344. }
  45345. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  45346. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  45347. return BABYLON.Mesh.DOUBLESIDE;
  45348. }
  45349. if (orientation === undefined || orientation === null) {
  45350. return BABYLON.Mesh.FRONTSIDE;
  45351. }
  45352. return orientation;
  45353. };
  45354. /**
  45355. * Creates a box mesh.
  45356. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  45357. * The parameter `size` sets the size (float) of each box side (default 1).
  45358. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  45359. * 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).
  45360. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  45361. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45362. * 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).
  45363. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45364. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45365. */
  45366. MeshBuilder.CreateBox = function (name, options, scene) {
  45367. var box = new BABYLON.Mesh(name, scene);
  45368. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45369. box._originalBuilderSideOrientation = options.sideOrientation;
  45370. var vertexData = BABYLON.VertexData.CreateBox(options);
  45371. vertexData.applyToMesh(box, options.updatable);
  45372. return box;
  45373. };
  45374. /**
  45375. * Creates a sphere mesh.
  45376. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  45377. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  45378. * 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`).
  45379. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  45380. * 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
  45381. * 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).
  45382. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45383. * 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).
  45384. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45385. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45386. */
  45387. MeshBuilder.CreateSphere = function (name, options, scene) {
  45388. var sphere = new BABYLON.Mesh(name, scene);
  45389. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45390. sphere._originalBuilderSideOrientation = options.sideOrientation;
  45391. var vertexData = BABYLON.VertexData.CreateSphere(options);
  45392. vertexData.applyToMesh(sphere, options.updatable);
  45393. return sphere;
  45394. };
  45395. /**
  45396. * Creates a plane polygonal mesh. By default, this is a disc.
  45397. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  45398. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  45399. * 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.
  45400. * 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
  45401. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45402. * 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).
  45403. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45404. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45405. */
  45406. MeshBuilder.CreateDisc = function (name, options, scene) {
  45407. var disc = new BABYLON.Mesh(name, scene);
  45408. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45409. disc._originalBuilderSideOrientation = options.sideOrientation;
  45410. var vertexData = BABYLON.VertexData.CreateDisc(options);
  45411. vertexData.applyToMesh(disc, options.updatable);
  45412. return disc;
  45413. };
  45414. /**
  45415. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  45416. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  45417. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  45418. * 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`).
  45419. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  45420. * 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.
  45421. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45422. * 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).
  45423. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45424. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45425. */
  45426. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  45427. var sphere = new BABYLON.Mesh(name, scene);
  45428. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45429. sphere._originalBuilderSideOrientation = options.sideOrientation;
  45430. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  45431. vertexData.applyToMesh(sphere, options.updatable);
  45432. return sphere;
  45433. };
  45434. ;
  45435. /**
  45436. * Creates a ribbon mesh.
  45437. * 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.
  45438. *
  45439. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  45440. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  45441. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  45442. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  45443. * 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.
  45444. * 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.
  45445. * 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
  45446. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45447. * 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).
  45448. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45449. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  45450. * 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.
  45451. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  45452. * 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
  45453. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  45454. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  45455. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45456. */
  45457. MeshBuilder.CreateRibbon = function (name, options, scene) {
  45458. var pathArray = options.pathArray;
  45459. var closeArray = options.closeArray;
  45460. var closePath = options.closePath;
  45461. var offset = options.offset;
  45462. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45463. var instance = options.instance;
  45464. var updatable = options.updatable;
  45465. if (instance) {
  45466. // positionFunction : ribbon case
  45467. // only pathArray and sideOrientation parameters are taken into account for positions update
  45468. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  45469. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  45470. var positionFunction = function (positions) {
  45471. var minlg = pathArray[0].length;
  45472. var i = 0;
  45473. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  45474. for (var si = 1; si <= ns; si++) {
  45475. for (var p = 0; p < pathArray.length; p++) {
  45476. var path = pathArray[p];
  45477. var l = path.length;
  45478. minlg = (minlg < l) ? minlg : l;
  45479. var j = 0;
  45480. while (j < minlg) {
  45481. positions[i] = path[j].x;
  45482. positions[i + 1] = path[j].y;
  45483. positions[i + 2] = path[j].z;
  45484. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  45485. BABYLON.Tmp.Vector3[0].x = path[j].x;
  45486. }
  45487. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  45488. BABYLON.Tmp.Vector3[1].x = path[j].x;
  45489. }
  45490. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  45491. BABYLON.Tmp.Vector3[0].y = path[j].y;
  45492. }
  45493. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  45494. BABYLON.Tmp.Vector3[1].y = path[j].y;
  45495. }
  45496. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  45497. BABYLON.Tmp.Vector3[0].z = path[j].z;
  45498. }
  45499. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  45500. BABYLON.Tmp.Vector3[1].z = path[j].z;
  45501. }
  45502. j++;
  45503. i += 3;
  45504. }
  45505. if (instance._closePath) {
  45506. positions[i] = path[0].x;
  45507. positions[i + 1] = path[0].y;
  45508. positions[i + 2] = path[0].z;
  45509. i += 3;
  45510. }
  45511. }
  45512. }
  45513. };
  45514. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45515. positionFunction(positions);
  45516. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  45517. instance._boundingInfo.update(instance._worldMatrix);
  45518. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  45519. if (options.colors) {
  45520. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  45521. for (var c = 0; c < options.colors.length; c++) {
  45522. colors[c * 4] = options.colors[c].r;
  45523. colors[c * 4 + 1] = options.colors[c].g;
  45524. colors[c * 4 + 2] = options.colors[c].b;
  45525. colors[c * 4 + 3] = options.colors[c].a;
  45526. }
  45527. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  45528. }
  45529. if (options.uvs) {
  45530. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45531. for (var i = 0; i < options.uvs.length; i++) {
  45532. uvs[i * 2] = options.uvs[i].x;
  45533. uvs[i * 2 + 1] = options.uvs[i].y;
  45534. }
  45535. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  45536. }
  45537. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  45538. var indices = instance.getIndices();
  45539. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45540. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  45541. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  45542. if (instance._closePath) {
  45543. var indexFirst = 0;
  45544. var indexLast = 0;
  45545. for (var p = 0; p < pathArray.length; p++) {
  45546. indexFirst = instance._idx[p] * 3;
  45547. if (p + 1 < pathArray.length) {
  45548. indexLast = (instance._idx[p + 1] - 1) * 3;
  45549. }
  45550. else {
  45551. indexLast = normals.length - 3;
  45552. }
  45553. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  45554. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  45555. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  45556. normals[indexLast] = normals[indexFirst];
  45557. normals[indexLast + 1] = normals[indexFirst + 1];
  45558. normals[indexLast + 2] = normals[indexFirst + 2];
  45559. }
  45560. }
  45561. if (!(instance.areNormalsFrozen)) {
  45562. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  45563. }
  45564. }
  45565. return instance;
  45566. }
  45567. else {
  45568. var ribbon = new BABYLON.Mesh(name, scene);
  45569. ribbon._originalBuilderSideOrientation = sideOrientation;
  45570. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  45571. if (closePath) {
  45572. ribbon._idx = vertexData._idx;
  45573. }
  45574. ribbon._closePath = closePath;
  45575. ribbon._closeArray = closeArray;
  45576. vertexData.applyToMesh(ribbon, updatable);
  45577. return ribbon;
  45578. }
  45579. };
  45580. /**
  45581. * Creates a cylinder or a cone mesh.
  45582. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  45583. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  45584. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  45585. * 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.
  45586. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  45587. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  45588. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  45589. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  45590. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  45591. * 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).
  45592. * 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
  45593. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  45594. * 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
  45595. * 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.
  45596. * If `enclose` is false, a ring surface is one element.
  45597. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  45598. * 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
  45599. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45600. * 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).
  45601. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45602. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45603. */
  45604. MeshBuilder.CreateCylinder = function (name, options, scene) {
  45605. var cylinder = new BABYLON.Mesh(name, scene);
  45606. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45607. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  45608. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  45609. vertexData.applyToMesh(cylinder, options.updatable);
  45610. return cylinder;
  45611. };
  45612. /**
  45613. * Creates a torus mesh.
  45614. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  45615. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  45616. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  45617. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  45618. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45619. * 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).
  45620. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45621. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45622. */
  45623. MeshBuilder.CreateTorus = function (name, options, scene) {
  45624. var torus = new BABYLON.Mesh(name, scene);
  45625. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45626. torus._originalBuilderSideOrientation = options.sideOrientation;
  45627. var vertexData = BABYLON.VertexData.CreateTorus(options);
  45628. vertexData.applyToMesh(torus, options.updatable);
  45629. return torus;
  45630. };
  45631. /**
  45632. * Creates a torus knot mesh.
  45633. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  45634. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  45635. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  45636. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  45637. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  45638. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45639. * 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).
  45640. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45641. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45642. */
  45643. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  45644. var torusKnot = new BABYLON.Mesh(name, scene);
  45645. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45646. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  45647. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  45648. vertexData.applyToMesh(torusKnot, options.updatable);
  45649. return torusKnot;
  45650. };
  45651. /**
  45652. * Creates a line system mesh.
  45653. * A line system is a pool of many lines gathered in a single mesh.
  45654. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  45655. * 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.
  45656. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  45657. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  45658. * 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
  45659. * 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
  45660. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  45661. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45662. */
  45663. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  45664. var instance = options.instance;
  45665. var lines = options.lines;
  45666. if (instance) {
  45667. var positionFunction = function (positions) {
  45668. var i = 0;
  45669. for (var l = 0; l < lines.length; l++) {
  45670. var points = lines[l];
  45671. for (var p = 0; p < points.length; p++) {
  45672. positions[i] = points[p].x;
  45673. positions[i + 1] = points[p].y;
  45674. positions[i + 2] = points[p].z;
  45675. i += 3;
  45676. }
  45677. }
  45678. };
  45679. instance.updateMeshPositions(positionFunction, false);
  45680. return instance;
  45681. }
  45682. // line system creation
  45683. var lineSystem = new BABYLON.LinesMesh(name, scene);
  45684. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  45685. vertexData.applyToMesh(lineSystem, options.updatable);
  45686. return lineSystem;
  45687. };
  45688. /**
  45689. * Creates a line mesh.
  45690. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  45691. * 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.
  45692. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  45693. * The parameter `points` is an array successive Vector3.
  45694. * 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
  45695. * When updating an instance, remember that only point positions can change, not the number of points.
  45696. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45697. */
  45698. MeshBuilder.CreateLines = function (name, options, scene) {
  45699. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  45700. return lines;
  45701. };
  45702. /**
  45703. * Creates a dashed line mesh.
  45704. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  45705. * 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.
  45706. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  45707. * The parameter `points` is an array successive Vector3.
  45708. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  45709. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  45710. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  45711. * 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
  45712. * When updating an instance, remember that only point positions can change, not the number of points.
  45713. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45714. */
  45715. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  45716. var points = options.points;
  45717. var instance = options.instance;
  45718. var gapSize = options.gapSize || 1;
  45719. var dashSize = options.dashSize || 3;
  45720. if (instance) {
  45721. var positionFunction = function (positions) {
  45722. var curvect = BABYLON.Vector3.Zero();
  45723. var nbSeg = positions.length / 6;
  45724. var lg = 0;
  45725. var nb = 0;
  45726. var shft = 0;
  45727. var dashshft = 0;
  45728. var curshft = 0;
  45729. var p = 0;
  45730. var i = 0;
  45731. var j = 0;
  45732. for (i = 0; i < points.length - 1; i++) {
  45733. points[i + 1].subtractToRef(points[i], curvect);
  45734. lg += curvect.length();
  45735. }
  45736. shft = lg / nbSeg;
  45737. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  45738. for (i = 0; i < points.length - 1; i++) {
  45739. points[i + 1].subtractToRef(points[i], curvect);
  45740. nb = Math.floor(curvect.length() / shft);
  45741. curvect.normalize();
  45742. j = 0;
  45743. while (j < nb && p < positions.length) {
  45744. curshft = shft * j;
  45745. positions[p] = points[i].x + curshft * curvect.x;
  45746. positions[p + 1] = points[i].y + curshft * curvect.y;
  45747. positions[p + 2] = points[i].z + curshft * curvect.z;
  45748. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  45749. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  45750. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  45751. p += 6;
  45752. j++;
  45753. }
  45754. }
  45755. while (p < positions.length) {
  45756. positions[p] = points[i].x;
  45757. positions[p + 1] = points[i].y;
  45758. positions[p + 2] = points[i].z;
  45759. p += 3;
  45760. }
  45761. };
  45762. instance.updateMeshPositions(positionFunction, false);
  45763. return instance;
  45764. }
  45765. // dashed lines creation
  45766. var dashedLines = new BABYLON.LinesMesh(name, scene);
  45767. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  45768. vertexData.applyToMesh(dashedLines, options.updatable);
  45769. dashedLines.dashSize = dashSize;
  45770. dashedLines.gapSize = gapSize;
  45771. return dashedLines;
  45772. };
  45773. /**
  45774. * Creates an extruded shape mesh.
  45775. * 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.
  45776. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  45777. *
  45778. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  45779. * 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
  45780. * extruded along the Z axis.
  45781. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  45782. * 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.
  45783. * The parameter `scale` (float, default 1) is the value to scale the shape.
  45784. * 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
  45785. * 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
  45786. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  45787. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45788. * 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).
  45789. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45790. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  45791. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45792. */
  45793. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  45794. var path = options.path;
  45795. var shape = options.shape;
  45796. var scale = options.scale || 1;
  45797. var rotation = options.rotation || 0;
  45798. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  45799. var updatable = options.updatable;
  45800. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45801. var instance = options.instance;
  45802. var invertUV = options.invertUV || false;
  45803. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  45804. };
  45805. /**
  45806. * Creates an custom extruded shape mesh.
  45807. * 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.
  45808. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  45809. *
  45810. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  45811. * 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
  45812. * extruded along the Z axis.
  45813. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  45814. * 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
  45815. * and the distance of this point from the begining of the path :
  45816. * ```javascript
  45817. * var rotationFunction = function(i, distance) {
  45818. * // do things
  45819. * return rotationValue; }
  45820. * ```
  45821. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  45822. * 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
  45823. * and the distance of this point from the begining of the path :
  45824. * ```javascript
  45825. * var scaleFunction = function(i, distance) {
  45826. * // do things
  45827. * return scaleValue;}
  45828. * ```
  45829. * It must returns a float value that will be the scale value applied to the shape on each path point.
  45830. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  45831. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  45832. * 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
  45833. * 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
  45834. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  45835. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45836. * 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).
  45837. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45838. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  45839. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45840. */
  45841. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  45842. var path = options.path;
  45843. var shape = options.shape;
  45844. var scaleFunction = options.scaleFunction || (function () { return 1; });
  45845. var rotationFunction = options.rotationFunction || (function () { return 0; });
  45846. var ribbonCloseArray = options.ribbonCloseArray || false;
  45847. var ribbonClosePath = options.ribbonClosePath || false;
  45848. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  45849. var updatable = options.updatable;
  45850. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45851. var instance = options.instance;
  45852. var invertUV = options.invertUV || false;
  45853. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  45854. };
  45855. /**
  45856. * Creates lathe mesh.
  45857. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  45858. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  45859. *
  45860. * 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
  45861. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  45862. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  45863. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  45864. * 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.
  45865. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  45866. * 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
  45867. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45868. * 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).
  45869. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45870. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  45871. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45872. */
  45873. MeshBuilder.CreateLathe = function (name, options, scene) {
  45874. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  45875. var closed = (options.closed === undefined) ? true : options.closed;
  45876. var shape = options.shape;
  45877. var radius = options.radius || 1;
  45878. var tessellation = options.tessellation || 64;
  45879. var updatable = options.updatable;
  45880. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45881. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  45882. var pi2 = Math.PI * 2;
  45883. var paths = new Array();
  45884. var invertUV = options.invertUV || false;
  45885. var i = 0;
  45886. var p = 0;
  45887. var step = pi2 / tessellation * arc;
  45888. var rotated;
  45889. var path = new Array();
  45890. ;
  45891. for (i = 0; i <= tessellation; i++) {
  45892. var path = [];
  45893. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  45894. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  45895. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  45896. }
  45897. for (p = 0; p < shape.length; p++) {
  45898. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  45899. path.push(rotated);
  45900. }
  45901. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  45902. 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));
  45903. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  45904. }
  45905. paths.push(path);
  45906. }
  45907. // lathe ribbon
  45908. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  45909. return lathe;
  45910. };
  45911. /**
  45912. * Creates a plane mesh.
  45913. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  45914. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  45915. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  45916. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  45917. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  45918. * 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).
  45919. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  45920. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45921. */
  45922. MeshBuilder.CreatePlane = function (name, options, scene) {
  45923. var plane = new BABYLON.Mesh(name, scene);
  45924. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  45925. plane._originalBuilderSideOrientation = options.sideOrientation;
  45926. var vertexData = BABYLON.VertexData.CreatePlane(options);
  45927. vertexData.applyToMesh(plane, options.updatable);
  45928. if (options.sourcePlane) {
  45929. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  45930. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  45931. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  45932. plane.rotate(vectorProduct, product);
  45933. }
  45934. return plane;
  45935. };
  45936. /**
  45937. * Creates a ground mesh.
  45938. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  45939. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  45940. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  45941. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45942. */
  45943. MeshBuilder.CreateGround = function (name, options, scene) {
  45944. var ground = new BABYLON.GroundMesh(name, scene);
  45945. ground._setReady(false);
  45946. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  45947. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  45948. ground._width = options.width || 1;
  45949. ground._height = options.height || 1;
  45950. ground._maxX = ground._width / 2;
  45951. ground._maxZ = ground._height / 2;
  45952. ground._minX = -ground._maxX;
  45953. ground._minZ = -ground._maxZ;
  45954. var vertexData = BABYLON.VertexData.CreateGround(options);
  45955. vertexData.applyToMesh(ground, options.updatable);
  45956. ground._setReady(true);
  45957. return ground;
  45958. };
  45959. /**
  45960. * Creates a tiled ground mesh.
  45961. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  45962. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  45963. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  45964. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  45965. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  45966. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  45967. * numbers of subdivisions on the ground width and height of each tile.
  45968. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45969. */
  45970. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  45971. var tiledGround = new BABYLON.Mesh(name, scene);
  45972. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  45973. vertexData.applyToMesh(tiledGround, options.updatable);
  45974. return tiledGround;
  45975. };
  45976. /**
  45977. * Creates a ground mesh from a height map.
  45978. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  45979. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  45980. * The parameter `url` sets the URL of the height map image resource.
  45981. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  45982. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  45983. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  45984. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  45985. * 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.
  45986. * 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).
  45987. * This function is passed the newly built mesh :
  45988. * ```javascript
  45989. * function(mesh) { // do things
  45990. * return; }
  45991. * ```
  45992. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  45993. */
  45994. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  45995. var width = options.width || 10.0;
  45996. var height = options.height || 10.0;
  45997. var subdivisions = options.subdivisions || 1 | 0;
  45998. var minHeight = options.minHeight || 0.0;
  45999. var maxHeight = options.maxHeight || 1.0;
  46000. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  46001. var updatable = options.updatable;
  46002. var onReady = options.onReady;
  46003. var ground = new BABYLON.GroundMesh(name, scene);
  46004. ground._subdivisionsX = subdivisions;
  46005. ground._subdivisionsY = subdivisions;
  46006. ground._width = width;
  46007. ground._height = height;
  46008. ground._maxX = ground._width / 2.0;
  46009. ground._maxZ = ground._height / 2.0;
  46010. ground._minX = -ground._maxX;
  46011. ground._minZ = -ground._maxZ;
  46012. ground._setReady(false);
  46013. var onload = function (img) {
  46014. // Getting height map data
  46015. var canvas = document.createElement("canvas");
  46016. var context = canvas.getContext("2d");
  46017. var bufferWidth = img.width;
  46018. var bufferHeight = img.height;
  46019. canvas.width = bufferWidth;
  46020. canvas.height = bufferHeight;
  46021. context.drawImage(img, 0, 0);
  46022. // Create VertexData from map data
  46023. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  46024. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  46025. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  46026. width: width, height: height,
  46027. subdivisions: subdivisions,
  46028. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  46029. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  46030. });
  46031. vertexData.applyToMesh(ground, updatable);
  46032. ground._setReady(true);
  46033. //execute ready callback, if set
  46034. if (onReady) {
  46035. onReady(ground);
  46036. }
  46037. };
  46038. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  46039. return ground;
  46040. };
  46041. /**
  46042. * Creates a polygon mesh.
  46043. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  46044. * 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.
  46045. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46046. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46047. * 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).
  46048. * Remember you can only change the shape positions, not their number when updating a polygon.
  46049. */
  46050. MeshBuilder.CreatePolygon = function (name, options, scene) {
  46051. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  46052. var shape = options.shape;
  46053. var holes = options.holes || [];
  46054. var depth = options.depth || 0;
  46055. var contours = [];
  46056. var hole = [];
  46057. for (var i = 0; i < shape.length; i++) {
  46058. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  46059. }
  46060. var epsilon = 0.00000001;
  46061. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  46062. contours.pop();
  46063. }
  46064. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  46065. for (var hNb = 0; hNb < holes.length; hNb++) {
  46066. hole = [];
  46067. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  46068. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  46069. }
  46070. polygonTriangulation.addHole(hole);
  46071. }
  46072. var polygon = polygonTriangulation.build(options.updatable, depth);
  46073. polygon._originalBuilderSideOrientation = options.sideOrientation;
  46074. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  46075. vertexData.applyToMesh(polygon, options.updatable);
  46076. return polygon;
  46077. };
  46078. ;
  46079. /**
  46080. * Creates an extruded polygon mesh, with depth in the Y direction.
  46081. * 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).
  46082. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  46083. */
  46084. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  46085. return MeshBuilder.CreatePolygon(name, options, scene);
  46086. };
  46087. ;
  46088. /**
  46089. * Creates a tube mesh.
  46090. * 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.
  46091. *
  46092. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  46093. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  46094. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  46095. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  46096. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  46097. * 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.
  46098. * It must return a radius value (positive float) :
  46099. * ```javascript
  46100. * var radiusFunction = function(i, distance) {
  46101. * // do things
  46102. * return radius; }
  46103. * ```
  46104. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  46105. * 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
  46106. * 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
  46107. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46108. * 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).
  46109. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46110. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  46111. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46112. */
  46113. MeshBuilder.CreateTube = function (name, options, scene) {
  46114. var path = options.path;
  46115. var instance = options.instance;
  46116. var radius = 1.0;
  46117. if (instance) {
  46118. radius = instance.radius;
  46119. }
  46120. if (options.radius !== undefined) {
  46121. radius = options.radius;
  46122. }
  46123. ;
  46124. var tessellation = options.tessellation || 64 | 0;
  46125. var radiusFunction = options.radiusFunction;
  46126. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  46127. var invertUV = options.invertUV || false;
  46128. var updatable = options.updatable;
  46129. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  46130. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  46131. // tube geometry
  46132. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  46133. var tangents = path3D.getTangents();
  46134. var normals = path3D.getNormals();
  46135. var distances = path3D.getDistances();
  46136. var pi2 = Math.PI * 2;
  46137. var step = pi2 / tessellation * arc;
  46138. var returnRadius = function () { return radius; };
  46139. var radiusFunctionFinal = radiusFunction || returnRadius;
  46140. var circlePath;
  46141. var rad;
  46142. var normal;
  46143. var rotated;
  46144. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  46145. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  46146. for (var i = 0; i < path.length; i++) {
  46147. rad = radiusFunctionFinal(i, distances[i]); // current radius
  46148. circlePath = Array(); // current circle array
  46149. normal = normals[i]; // current normal
  46150. for (var t = 0; t < tessellation; t++) {
  46151. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  46152. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  46153. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  46154. rotated.scaleInPlace(rad).addInPlace(path[i]);
  46155. circlePath[t] = rotated;
  46156. }
  46157. circlePaths[index] = circlePath;
  46158. index++;
  46159. }
  46160. // cap
  46161. var capPath = function (nbPoints, pathIndex) {
  46162. var pointCap = Array();
  46163. for (var i = 0; i < nbPoints; i++) {
  46164. pointCap.push(path[pathIndex]);
  46165. }
  46166. return pointCap;
  46167. };
  46168. switch (cap) {
  46169. case BABYLON.Mesh.NO_CAP:
  46170. break;
  46171. case BABYLON.Mesh.CAP_START:
  46172. circlePaths[0] = capPath(tessellation, 0);
  46173. circlePaths[1] = circlePaths[2].slice(0);
  46174. break;
  46175. case BABYLON.Mesh.CAP_END:
  46176. circlePaths[index] = circlePaths[index - 1].slice(0);
  46177. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  46178. break;
  46179. case BABYLON.Mesh.CAP_ALL:
  46180. circlePaths[0] = capPath(tessellation, 0);
  46181. circlePaths[1] = circlePaths[2].slice(0);
  46182. circlePaths[index] = circlePaths[index - 1].slice(0);
  46183. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  46184. break;
  46185. default:
  46186. break;
  46187. }
  46188. return circlePaths;
  46189. };
  46190. var path3D;
  46191. var pathArray;
  46192. if (instance) {
  46193. var arc = options.arc || instance.arc;
  46194. path3D = (instance.path3D).update(path);
  46195. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  46196. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  46197. instance.path3D = path3D;
  46198. instance.pathArray = pathArray;
  46199. instance.arc = arc;
  46200. instance.radius = radius;
  46201. return instance;
  46202. }
  46203. // tube creation
  46204. path3D = new BABYLON.Path3D(path);
  46205. var newPathArray = new Array();
  46206. cap = (cap < 0 || cap > 3) ? 0 : cap;
  46207. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  46208. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  46209. tube.pathArray = pathArray;
  46210. tube.path3D = path3D;
  46211. tube.tessellation = tessellation;
  46212. tube.cap = cap;
  46213. tube.arc = options.arc;
  46214. tube.radius = radius;
  46215. return tube;
  46216. };
  46217. /**
  46218. * Creates a polyhedron mesh.
  46219. *
  46220. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  46221. * 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
  46222. * to choose the wanted type.
  46223. * The parameter `size` (positive float, default 1) sets the polygon size.
  46224. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  46225. * 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`.
  46226. * 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
  46227. * 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)`).
  46228. * 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
  46229. * 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.
  46230. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  46231. * 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).
  46232. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  46233. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  46234. */
  46235. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  46236. var polyhedron = new BABYLON.Mesh(name, scene);
  46237. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  46238. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  46239. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  46240. vertexData.applyToMesh(polyhedron, options.updatable);
  46241. return polyhedron;
  46242. };
  46243. /**
  46244. * Creates a decal mesh.
  46245. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  46246. * 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.
  46247. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  46248. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  46249. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  46250. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  46251. */
  46252. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  46253. var indices = sourceMesh.getIndices();
  46254. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46255. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46256. var position = options.position || BABYLON.Vector3.Zero();
  46257. var normal = options.normal || BABYLON.Vector3.Up();
  46258. var size = options.size || BABYLON.Vector3.One();
  46259. var angle = options.angle || 0;
  46260. // Getting correct rotation
  46261. if (!normal) {
  46262. var target = new BABYLON.Vector3(0, 0, 1);
  46263. var camera = sourceMesh.getScene().activeCamera;
  46264. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  46265. normal = camera.globalPosition.subtract(cameraWorldTarget);
  46266. }
  46267. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  46268. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  46269. var pitch = Math.atan2(normal.y, len);
  46270. // Matrix
  46271. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  46272. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  46273. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  46274. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  46275. var vertexData = new BABYLON.VertexData();
  46276. vertexData.indices = [];
  46277. vertexData.positions = [];
  46278. vertexData.normals = [];
  46279. vertexData.uvs = [];
  46280. var currentVertexDataIndex = 0;
  46281. var extractDecalVector3 = function (indexId) {
  46282. var vertexId = indices[indexId];
  46283. var result = new BABYLON.PositionNormalVertex();
  46284. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  46285. // Send vector to decal local world
  46286. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  46287. // Get normal
  46288. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  46289. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  46290. return result;
  46291. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  46292. var clip = function (vertices, axis) {
  46293. if (vertices.length === 0) {
  46294. return vertices;
  46295. }
  46296. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  46297. var clipVertices = function (v0, v1) {
  46298. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  46299. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  46300. };
  46301. var result = new Array();
  46302. for (var index = 0; index < vertices.length; index += 3) {
  46303. var v1Out;
  46304. var v2Out;
  46305. var v3Out;
  46306. var total = 0;
  46307. var nV1, nV2, nV3, nV4;
  46308. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  46309. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  46310. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  46311. v1Out = d1 > 0;
  46312. v2Out = d2 > 0;
  46313. v3Out = d3 > 0;
  46314. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  46315. switch (total) {
  46316. case 0:
  46317. result.push(vertices[index]);
  46318. result.push(vertices[index + 1]);
  46319. result.push(vertices[index + 2]);
  46320. break;
  46321. case 1:
  46322. if (v1Out) {
  46323. nV1 = vertices[index + 1];
  46324. nV2 = vertices[index + 2];
  46325. nV3 = clipVertices(vertices[index], nV1);
  46326. nV4 = clipVertices(vertices[index], nV2);
  46327. }
  46328. if (v2Out) {
  46329. nV1 = vertices[index];
  46330. nV2 = vertices[index + 2];
  46331. nV3 = clipVertices(vertices[index + 1], nV1);
  46332. nV4 = clipVertices(vertices[index + 1], nV2);
  46333. result.push(nV3);
  46334. result.push(nV2.clone());
  46335. result.push(nV1.clone());
  46336. result.push(nV2.clone());
  46337. result.push(nV3.clone());
  46338. result.push(nV4);
  46339. break;
  46340. }
  46341. if (v3Out) {
  46342. nV1 = vertices[index];
  46343. nV2 = vertices[index + 1];
  46344. nV3 = clipVertices(vertices[index + 2], nV1);
  46345. nV4 = clipVertices(vertices[index + 2], nV2);
  46346. }
  46347. result.push(nV1.clone());
  46348. result.push(nV2.clone());
  46349. result.push(nV3);
  46350. result.push(nV4);
  46351. result.push(nV3.clone());
  46352. result.push(nV2.clone());
  46353. break;
  46354. case 2:
  46355. if (!v1Out) {
  46356. nV1 = vertices[index].clone();
  46357. nV2 = clipVertices(nV1, vertices[index + 1]);
  46358. nV3 = clipVertices(nV1, vertices[index + 2]);
  46359. result.push(nV1);
  46360. result.push(nV2);
  46361. result.push(nV3);
  46362. }
  46363. if (!v2Out) {
  46364. nV1 = vertices[index + 1].clone();
  46365. nV2 = clipVertices(nV1, vertices[index + 2]);
  46366. nV3 = clipVertices(nV1, vertices[index]);
  46367. result.push(nV1);
  46368. result.push(nV2);
  46369. result.push(nV3);
  46370. }
  46371. if (!v3Out) {
  46372. nV1 = vertices[index + 2].clone();
  46373. nV2 = clipVertices(nV1, vertices[index]);
  46374. nV3 = clipVertices(nV1, vertices[index + 1]);
  46375. result.push(nV1);
  46376. result.push(nV2);
  46377. result.push(nV3);
  46378. }
  46379. break;
  46380. case 3:
  46381. break;
  46382. }
  46383. }
  46384. return result;
  46385. };
  46386. for (var index = 0; index < indices.length; index += 3) {
  46387. var faceVertices = new Array();
  46388. faceVertices.push(extractDecalVector3(index));
  46389. faceVertices.push(extractDecalVector3(index + 1));
  46390. faceVertices.push(extractDecalVector3(index + 2));
  46391. // Clip
  46392. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  46393. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  46394. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  46395. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  46396. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  46397. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  46398. if (faceVertices.length === 0) {
  46399. continue;
  46400. }
  46401. // Add UVs and get back to world
  46402. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  46403. var vertex = faceVertices[vIndex];
  46404. //TODO check for Int32Array | Uint32Array | Uint16Array
  46405. vertexData.indices.push(currentVertexDataIndex);
  46406. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  46407. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  46408. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  46409. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  46410. currentVertexDataIndex++;
  46411. }
  46412. }
  46413. // Return mesh
  46414. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  46415. vertexData.applyToMesh(decal);
  46416. decal.position = position.clone();
  46417. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  46418. return decal;
  46419. };
  46420. // Privates
  46421. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  46422. // extrusion geometry
  46423. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  46424. var tangents = path3D.getTangents();
  46425. var normals = path3D.getNormals();
  46426. var binormals = path3D.getBinormals();
  46427. var distances = path3D.getDistances();
  46428. var angle = 0;
  46429. var returnScale = function () { return scale; };
  46430. var returnRotation = function () { return rotation; };
  46431. var rotate = custom ? rotateFunction : returnRotation;
  46432. var scl = custom ? scaleFunction : returnScale;
  46433. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  46434. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  46435. for (var i = 0; i < curve.length; i++) {
  46436. var shapePath = new Array();
  46437. var angleStep = rotate(i, distances[i]);
  46438. var scaleRatio = scl(i, distances[i]);
  46439. for (var p = 0; p < shape.length; p++) {
  46440. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  46441. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  46442. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  46443. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  46444. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  46445. shapePath[p] = rotated;
  46446. }
  46447. shapePaths[index] = shapePath;
  46448. angle += angleStep;
  46449. index++;
  46450. }
  46451. // cap
  46452. var capPath = function (shapePath) {
  46453. var pointCap = Array();
  46454. var barycenter = BABYLON.Vector3.Zero();
  46455. var i;
  46456. for (i = 0; i < shapePath.length; i++) {
  46457. barycenter.addInPlace(shapePath[i]);
  46458. }
  46459. barycenter.scaleInPlace(1.0 / shapePath.length);
  46460. for (i = 0; i < shapePath.length; i++) {
  46461. pointCap.push(barycenter);
  46462. }
  46463. return pointCap;
  46464. };
  46465. switch (cap) {
  46466. case BABYLON.Mesh.NO_CAP:
  46467. break;
  46468. case BABYLON.Mesh.CAP_START:
  46469. shapePaths[0] = capPath(shapePaths[2]);
  46470. shapePaths[1] = shapePaths[2];
  46471. break;
  46472. case BABYLON.Mesh.CAP_END:
  46473. shapePaths[index] = shapePaths[index - 1];
  46474. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  46475. break;
  46476. case BABYLON.Mesh.CAP_ALL:
  46477. shapePaths[0] = capPath(shapePaths[2]);
  46478. shapePaths[1] = shapePaths[2];
  46479. shapePaths[index] = shapePaths[index - 1];
  46480. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  46481. break;
  46482. default:
  46483. break;
  46484. }
  46485. return shapePaths;
  46486. };
  46487. var path3D;
  46488. var pathArray;
  46489. if (instance) {
  46490. path3D = (instance.path3D).update(curve);
  46491. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  46492. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  46493. return instance;
  46494. }
  46495. // extruded shape creation
  46496. path3D = new BABYLON.Path3D(curve);
  46497. var newShapePaths = new Array();
  46498. cap = (cap < 0 || cap > 3) ? 0 : cap;
  46499. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  46500. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  46501. extrudedGeneric.pathArray = pathArray;
  46502. extrudedGeneric.path3D = path3D;
  46503. extrudedGeneric.cap = cap;
  46504. return extrudedGeneric;
  46505. };
  46506. return MeshBuilder;
  46507. }());
  46508. BABYLON.MeshBuilder = MeshBuilder;
  46509. })(BABYLON || (BABYLON = {}));
  46510. //# sourceMappingURL=babylon.meshBuilder.js.map
  46511. var BABYLON;
  46512. (function (BABYLON) {
  46513. var AudioEngine = (function () {
  46514. function AudioEngine() {
  46515. this._audioContext = null;
  46516. this._audioContextInitialized = false;
  46517. this.canUseWebAudio = false;
  46518. this.WarnedWebAudioUnsupported = false;
  46519. this.unlocked = false;
  46520. this.isMP3supported = false;
  46521. this.isOGGsupported = false;
  46522. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  46523. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  46524. this.canUseWebAudio = true;
  46525. }
  46526. var audioElem = document.createElement('audio');
  46527. try {
  46528. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  46529. this.isMP3supported = true;
  46530. }
  46531. }
  46532. catch (e) {
  46533. // protect error during capability check.
  46534. }
  46535. try {
  46536. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  46537. this.isOGGsupported = true;
  46538. }
  46539. }
  46540. catch (e) {
  46541. // protect error during capability check.
  46542. }
  46543. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  46544. this._unlockiOSaudio();
  46545. }
  46546. else {
  46547. this.unlocked = true;
  46548. }
  46549. }
  46550. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  46551. get: function () {
  46552. if (!this._audioContextInitialized) {
  46553. this._initializeAudioContext();
  46554. }
  46555. return this._audioContext;
  46556. },
  46557. enumerable: true,
  46558. configurable: true
  46559. });
  46560. AudioEngine.prototype._unlockiOSaudio = function () {
  46561. var _this = this;
  46562. var unlockaudio = function () {
  46563. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  46564. var source = _this.audioContext.createBufferSource();
  46565. source.buffer = buffer;
  46566. source.connect(_this.audioContext.destination);
  46567. source.start(0);
  46568. setTimeout(function () {
  46569. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  46570. _this.unlocked = true;
  46571. window.removeEventListener('touchend', unlockaudio, false);
  46572. if (_this.onAudioUnlocked) {
  46573. _this.onAudioUnlocked();
  46574. }
  46575. }
  46576. }, 0);
  46577. };
  46578. window.addEventListener('touchend', unlockaudio, false);
  46579. };
  46580. AudioEngine.prototype._initializeAudioContext = function () {
  46581. try {
  46582. if (this.canUseWebAudio) {
  46583. this._audioContext = new AudioContext();
  46584. // create a global volume gain node
  46585. this.masterGain = this._audioContext.createGain();
  46586. this.masterGain.gain.value = 1;
  46587. this.masterGain.connect(this._audioContext.destination);
  46588. this._audioContextInitialized = true;
  46589. }
  46590. }
  46591. catch (e) {
  46592. this.canUseWebAudio = false;
  46593. BABYLON.Tools.Error("Web Audio: " + e.message);
  46594. }
  46595. };
  46596. AudioEngine.prototype.dispose = function () {
  46597. if (this.canUseWebAudio && this._audioContextInitialized) {
  46598. if (this._connectedAnalyser) {
  46599. this._connectedAnalyser.stopDebugCanvas();
  46600. this._connectedAnalyser.dispose();
  46601. this.masterGain.disconnect();
  46602. this.masterGain.connect(this._audioContext.destination);
  46603. this._connectedAnalyser = null;
  46604. }
  46605. this.masterGain.gain.value = 1;
  46606. }
  46607. this.WarnedWebAudioUnsupported = false;
  46608. };
  46609. AudioEngine.prototype.getGlobalVolume = function () {
  46610. if (this.canUseWebAudio && this._audioContextInitialized) {
  46611. return this.masterGain.gain.value;
  46612. }
  46613. else {
  46614. return -1;
  46615. }
  46616. };
  46617. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  46618. if (this.canUseWebAudio && this._audioContextInitialized) {
  46619. this.masterGain.gain.value = newVolume;
  46620. }
  46621. };
  46622. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  46623. if (this._connectedAnalyser) {
  46624. this._connectedAnalyser.stopDebugCanvas();
  46625. }
  46626. if (this.canUseWebAudio && this._audioContextInitialized) {
  46627. this._connectedAnalyser = analyser;
  46628. this.masterGain.disconnect();
  46629. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  46630. }
  46631. };
  46632. return AudioEngine;
  46633. }());
  46634. BABYLON.AudioEngine = AudioEngine;
  46635. })(BABYLON || (BABYLON = {}));
  46636. //# sourceMappingURL=babylon.audioEngine.js.map
  46637. var BABYLON;
  46638. (function (BABYLON) {
  46639. var Sound = (function () {
  46640. /**
  46641. * Create a sound and attach it to a scene
  46642. * @param name Name of your sound
  46643. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  46644. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  46645. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  46646. */
  46647. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  46648. var _this = this;
  46649. this.autoplay = false;
  46650. this.loop = false;
  46651. this.useCustomAttenuation = false;
  46652. this.spatialSound = false;
  46653. this.refDistance = 1;
  46654. this.rolloffFactor = 1;
  46655. this.maxDistance = 100;
  46656. this.distanceModel = "linear";
  46657. this._panningModel = "equalpower";
  46658. this._playbackRate = 1;
  46659. this._streaming = false;
  46660. this._startTime = 0;
  46661. this._startOffset = 0;
  46662. this._position = BABYLON.Vector3.Zero();
  46663. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  46664. this._volume = 1;
  46665. this._isLoaded = false;
  46666. this._isReadyToPlay = false;
  46667. this.isPlaying = false;
  46668. this.isPaused = false;
  46669. this._isDirectional = false;
  46670. // Used if you'd like to create a directional sound.
  46671. // If not set, the sound will be omnidirectional
  46672. this._coneInnerAngle = 360;
  46673. this._coneOuterAngle = 360;
  46674. this._coneOuterGain = 0;
  46675. this._isOutputConnected = false;
  46676. this._urlType = "Unknown";
  46677. this.name = name;
  46678. this._scene = scene;
  46679. this._readyToPlayCallback = readyToPlayCallback;
  46680. // Default custom attenuation function is a linear attenuation
  46681. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  46682. if (currentDistance < maxDistance) {
  46683. return currentVolume * (1 - currentDistance / maxDistance);
  46684. }
  46685. else {
  46686. return 0;
  46687. }
  46688. };
  46689. if (options) {
  46690. this.autoplay = options.autoplay || false;
  46691. this.loop = options.loop || false;
  46692. // if volume === 0, we need another way to check this option
  46693. if (options.volume !== undefined) {
  46694. this._volume = options.volume;
  46695. }
  46696. this.spatialSound = options.spatialSound || false;
  46697. this.maxDistance = options.maxDistance || 100;
  46698. this.useCustomAttenuation = options.useCustomAttenuation || false;
  46699. this.rolloffFactor = options.rolloffFactor || 1;
  46700. this.refDistance = options.refDistance || 1;
  46701. this.distanceModel = options.distanceModel || "linear";
  46702. this._playbackRate = options.playbackRate || 1;
  46703. this._streaming = options.streaming || false;
  46704. }
  46705. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  46706. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  46707. this._soundGain.gain.value = this._volume;
  46708. this._inputAudioNode = this._soundGain;
  46709. this._ouputAudioNode = this._soundGain;
  46710. if (this.spatialSound) {
  46711. this._createSpatialParameters();
  46712. }
  46713. this._scene.mainSoundTrack.AddSound(this);
  46714. var validParameter = true;
  46715. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  46716. if (urlOrArrayBuffer) {
  46717. if (typeof (urlOrArrayBuffer) === "string")
  46718. this._urlType = "String";
  46719. if (Array.isArray(urlOrArrayBuffer))
  46720. this._urlType = "Array";
  46721. if (urlOrArrayBuffer instanceof ArrayBuffer)
  46722. this._urlType = "ArrayBuffer";
  46723. var urls = [];
  46724. var codecSupportedFound = false;
  46725. switch (this._urlType) {
  46726. case "ArrayBuffer":
  46727. if (urlOrArrayBuffer.byteLength > 0) {
  46728. codecSupportedFound = true;
  46729. this._soundLoaded(urlOrArrayBuffer);
  46730. }
  46731. break;
  46732. case "String":
  46733. urls.push(urlOrArrayBuffer);
  46734. case "Array":
  46735. if (urls.length === 0)
  46736. urls = urlOrArrayBuffer;
  46737. // If we found a supported format, we load it immediately and stop the loop
  46738. for (var i = 0; i < urls.length; i++) {
  46739. var url = urls[i];
  46740. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  46741. codecSupportedFound = true;
  46742. }
  46743. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  46744. codecSupportedFound = true;
  46745. }
  46746. if (url.indexOf(".wav", url.length - 4) !== -1) {
  46747. codecSupportedFound = true;
  46748. }
  46749. if (url.indexOf("blob:") !== -1) {
  46750. codecSupportedFound = true;
  46751. }
  46752. if (codecSupportedFound) {
  46753. // Loading sound using XHR2
  46754. if (!this._streaming) {
  46755. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  46756. }
  46757. else {
  46758. this._htmlAudioElement = new Audio(url);
  46759. this._htmlAudioElement.controls = false;
  46760. this._htmlAudioElement.loop = this.loop;
  46761. this._htmlAudioElement.crossOrigin = "anonymous";
  46762. this._htmlAudioElement.preload = "auto";
  46763. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  46764. _this._isReadyToPlay = true;
  46765. if (_this.autoplay) {
  46766. _this.play();
  46767. }
  46768. if (_this._readyToPlayCallback) {
  46769. _this._readyToPlayCallback();
  46770. }
  46771. });
  46772. document.body.appendChild(this._htmlAudioElement);
  46773. }
  46774. break;
  46775. }
  46776. }
  46777. break;
  46778. default:
  46779. validParameter = false;
  46780. break;
  46781. }
  46782. if (!validParameter) {
  46783. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  46784. }
  46785. else {
  46786. if (!codecSupportedFound) {
  46787. this._isReadyToPlay = true;
  46788. // Simulating a ready to play event to avoid breaking code path
  46789. if (this._readyToPlayCallback) {
  46790. window.setTimeout(function () {
  46791. _this._readyToPlayCallback();
  46792. }, 1000);
  46793. }
  46794. }
  46795. }
  46796. }
  46797. }
  46798. else {
  46799. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  46800. this._scene.mainSoundTrack.AddSound(this);
  46801. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  46802. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  46803. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  46804. }
  46805. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  46806. if (this._readyToPlayCallback) {
  46807. window.setTimeout(function () {
  46808. _this._readyToPlayCallback();
  46809. }, 1000);
  46810. }
  46811. }
  46812. }
  46813. Sound.prototype.dispose = function () {
  46814. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  46815. if (this.isPlaying) {
  46816. this.stop();
  46817. }
  46818. this._isReadyToPlay = false;
  46819. if (this.soundTrackId === -1) {
  46820. this._scene.mainSoundTrack.RemoveSound(this);
  46821. }
  46822. else {
  46823. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  46824. }
  46825. if (this._soundGain) {
  46826. this._soundGain.disconnect();
  46827. this._soundGain = null;
  46828. }
  46829. if (this._soundPanner) {
  46830. this._soundPanner.disconnect();
  46831. this._soundPanner = null;
  46832. }
  46833. if (this._soundSource) {
  46834. this._soundSource.disconnect();
  46835. this._soundSource = null;
  46836. }
  46837. this._audioBuffer = null;
  46838. if (this._htmlAudioElement) {
  46839. this._htmlAudioElement.pause();
  46840. this._htmlAudioElement.src = "";
  46841. document.body.removeChild(this._htmlAudioElement);
  46842. }
  46843. if (this._connectedMesh) {
  46844. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  46845. this._connectedMesh = null;
  46846. }
  46847. }
  46848. };
  46849. Sound.prototype.isReady = function () {
  46850. return this._isReadyToPlay;
  46851. };
  46852. Sound.prototype._soundLoaded = function (audioData) {
  46853. var _this = this;
  46854. this._isLoaded = true;
  46855. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  46856. _this._audioBuffer = buffer;
  46857. _this._isReadyToPlay = true;
  46858. if (_this.autoplay) {
  46859. _this.play();
  46860. }
  46861. if (_this._readyToPlayCallback) {
  46862. _this._readyToPlayCallback();
  46863. }
  46864. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  46865. };
  46866. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  46867. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  46868. this._audioBuffer = audioBuffer;
  46869. this._isReadyToPlay = true;
  46870. }
  46871. };
  46872. Sound.prototype.updateOptions = function (options) {
  46873. if (options) {
  46874. this.loop = options.loop || this.loop;
  46875. this.maxDistance = options.maxDistance || this.maxDistance;
  46876. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  46877. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  46878. this.refDistance = options.refDistance || this.refDistance;
  46879. this.distanceModel = options.distanceModel || this.distanceModel;
  46880. this._playbackRate = options.playbackRate || this._playbackRate;
  46881. this._updateSpatialParameters();
  46882. if (this.isPlaying) {
  46883. if (this._streaming) {
  46884. this._htmlAudioElement.playbackRate = this._playbackRate;
  46885. }
  46886. else {
  46887. this._soundSource.playbackRate.value = this._playbackRate;
  46888. }
  46889. }
  46890. }
  46891. };
  46892. Sound.prototype._createSpatialParameters = function () {
  46893. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  46894. if (this._scene.headphone) {
  46895. this._panningModel = "HRTF";
  46896. }
  46897. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  46898. this._updateSpatialParameters();
  46899. this._soundPanner.connect(this._ouputAudioNode);
  46900. this._inputAudioNode = this._soundPanner;
  46901. }
  46902. };
  46903. Sound.prototype._updateSpatialParameters = function () {
  46904. if (this.spatialSound) {
  46905. if (this.useCustomAttenuation) {
  46906. // Tricks to disable in a way embedded Web Audio attenuation
  46907. this._soundPanner.distanceModel = "linear";
  46908. this._soundPanner.maxDistance = Number.MAX_VALUE;
  46909. this._soundPanner.refDistance = 1;
  46910. this._soundPanner.rolloffFactor = 1;
  46911. this._soundPanner.panningModel = this._panningModel;
  46912. }
  46913. else {
  46914. this._soundPanner.distanceModel = this.distanceModel;
  46915. this._soundPanner.maxDistance = this.maxDistance;
  46916. this._soundPanner.refDistance = this.refDistance;
  46917. this._soundPanner.rolloffFactor = this.rolloffFactor;
  46918. this._soundPanner.panningModel = this._panningModel;
  46919. }
  46920. }
  46921. };
  46922. Sound.prototype.switchPanningModelToHRTF = function () {
  46923. this._panningModel = "HRTF";
  46924. this._switchPanningModel();
  46925. };
  46926. Sound.prototype.switchPanningModelToEqualPower = function () {
  46927. this._panningModel = "equalpower";
  46928. this._switchPanningModel();
  46929. };
  46930. Sound.prototype._switchPanningModel = function () {
  46931. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  46932. this._soundPanner.panningModel = this._panningModel;
  46933. }
  46934. };
  46935. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  46936. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  46937. if (this._isOutputConnected) {
  46938. this._ouputAudioNode.disconnect();
  46939. }
  46940. this._ouputAudioNode.connect(soundTrackAudioNode);
  46941. this._isOutputConnected = true;
  46942. }
  46943. };
  46944. /**
  46945. * Transform this sound into a directional source
  46946. * @param coneInnerAngle Size of the inner cone in degree
  46947. * @param coneOuterAngle Size of the outer cone in degree
  46948. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  46949. */
  46950. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  46951. if (coneOuterAngle < coneInnerAngle) {
  46952. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  46953. return;
  46954. }
  46955. this._coneInnerAngle = coneInnerAngle;
  46956. this._coneOuterAngle = coneOuterAngle;
  46957. this._coneOuterGain = coneOuterGain;
  46958. this._isDirectional = true;
  46959. if (this.isPlaying && this.loop) {
  46960. this.stop();
  46961. this.play();
  46962. }
  46963. };
  46964. Sound.prototype.setPosition = function (newPosition) {
  46965. this._position = newPosition;
  46966. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  46967. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  46968. }
  46969. };
  46970. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  46971. this._localDirection = newLocalDirection;
  46972. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  46973. this._updateDirection();
  46974. }
  46975. };
  46976. Sound.prototype._updateDirection = function () {
  46977. var mat = this._connectedMesh.getWorldMatrix();
  46978. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  46979. direction.normalize();
  46980. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  46981. };
  46982. Sound.prototype.updateDistanceFromListener = function () {
  46983. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  46984. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  46985. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  46986. }
  46987. };
  46988. Sound.prototype.setAttenuationFunction = function (callback) {
  46989. this._customAttenuationFunction = callback;
  46990. };
  46991. /**
  46992. * Play the sound
  46993. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  46994. * @param offset (optional) Start the sound setting it at a specific time
  46995. */
  46996. Sound.prototype.play = function (time, offset) {
  46997. var _this = this;
  46998. if (this._isReadyToPlay && this._scene.audioEnabled) {
  46999. try {
  47000. if (this._startOffset < 0) {
  47001. time = -this._startOffset;
  47002. this._startOffset = 0;
  47003. }
  47004. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  47005. if (!this._soundSource || !this._streamingSource) {
  47006. if (this.spatialSound) {
  47007. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  47008. if (this._isDirectional) {
  47009. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  47010. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  47011. this._soundPanner.coneOuterGain = this._coneOuterGain;
  47012. if (this._connectedMesh) {
  47013. this._updateDirection();
  47014. }
  47015. else {
  47016. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  47017. }
  47018. }
  47019. }
  47020. }
  47021. if (this._streaming) {
  47022. if (!this._streamingSource) {
  47023. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  47024. this._htmlAudioElement.onended = function () { _this._onended(); };
  47025. this._htmlAudioElement.playbackRate = this._playbackRate;
  47026. }
  47027. this._streamingSource.disconnect();
  47028. this._streamingSource.connect(this._inputAudioNode);
  47029. this._htmlAudioElement.play();
  47030. }
  47031. else {
  47032. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  47033. this._soundSource.buffer = this._audioBuffer;
  47034. this._soundSource.connect(this._inputAudioNode);
  47035. this._soundSource.loop = this.loop;
  47036. this._soundSource.playbackRate.value = this._playbackRate;
  47037. this._soundSource.onended = function () { _this._onended(); };
  47038. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  47039. }
  47040. this._startTime = startTime;
  47041. this.isPlaying = true;
  47042. this.isPaused = false;
  47043. }
  47044. catch (ex) {
  47045. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  47046. }
  47047. }
  47048. };
  47049. Sound.prototype._onended = function () {
  47050. this.isPlaying = false;
  47051. if (this.onended) {
  47052. this.onended();
  47053. }
  47054. };
  47055. /**
  47056. * Stop the sound
  47057. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  47058. */
  47059. Sound.prototype.stop = function (time) {
  47060. if (this.isPlaying) {
  47061. if (this._streaming) {
  47062. this._htmlAudioElement.pause();
  47063. // Test needed for Firefox or it will generate an Invalid State Error
  47064. if (this._htmlAudioElement.currentTime > 0) {
  47065. this._htmlAudioElement.currentTime = 0;
  47066. }
  47067. }
  47068. else {
  47069. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  47070. this._soundSource.stop(stopTime);
  47071. this._soundSource.onended = null;
  47072. if (!this.isPaused) {
  47073. this._startOffset = 0;
  47074. }
  47075. }
  47076. this.isPlaying = false;
  47077. }
  47078. };
  47079. Sound.prototype.pause = function () {
  47080. if (this.isPlaying) {
  47081. this.isPaused = true;
  47082. if (this._streaming) {
  47083. this._htmlAudioElement.pause();
  47084. }
  47085. else {
  47086. this.stop(0);
  47087. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  47088. }
  47089. }
  47090. };
  47091. Sound.prototype.setVolume = function (newVolume, time) {
  47092. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47093. if (time) {
  47094. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  47095. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  47096. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  47097. }
  47098. else {
  47099. this._soundGain.gain.value = newVolume;
  47100. }
  47101. }
  47102. this._volume = newVolume;
  47103. };
  47104. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  47105. this._playbackRate = newPlaybackRate;
  47106. if (this.isPlaying) {
  47107. if (this._streaming) {
  47108. this._htmlAudioElement.playbackRate = this._playbackRate;
  47109. }
  47110. else {
  47111. this._soundSource.playbackRate.value = this._playbackRate;
  47112. }
  47113. }
  47114. };
  47115. Sound.prototype.getVolume = function () {
  47116. return this._volume;
  47117. };
  47118. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  47119. var _this = this;
  47120. if (this._connectedMesh) {
  47121. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  47122. this._registerFunc = null;
  47123. }
  47124. this._connectedMesh = meshToConnectTo;
  47125. if (!this.spatialSound) {
  47126. this.spatialSound = true;
  47127. this._createSpatialParameters();
  47128. if (this.isPlaying && this.loop) {
  47129. this.stop();
  47130. this.play();
  47131. }
  47132. }
  47133. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  47134. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  47135. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  47136. };
  47137. Sound.prototype.detachFromMesh = function () {
  47138. if (this._connectedMesh) {
  47139. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  47140. this._registerFunc = null;
  47141. this._connectedMesh = null;
  47142. }
  47143. };
  47144. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  47145. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  47146. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  47147. this._updateDirection();
  47148. }
  47149. };
  47150. Sound.prototype.clone = function () {
  47151. var _this = this;
  47152. if (!this._streaming) {
  47153. var setBufferAndRun = function () {
  47154. if (_this._isReadyToPlay) {
  47155. clonedSound._audioBuffer = _this.getAudioBuffer();
  47156. clonedSound._isReadyToPlay = true;
  47157. if (clonedSound.autoplay) {
  47158. clonedSound.play();
  47159. }
  47160. }
  47161. else {
  47162. window.setTimeout(setBufferAndRun, 300);
  47163. }
  47164. };
  47165. var currentOptions = {
  47166. autoplay: this.autoplay, loop: this.loop,
  47167. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  47168. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  47169. refDistance: this.refDistance, distanceModel: this.distanceModel
  47170. };
  47171. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  47172. if (this.useCustomAttenuation) {
  47173. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  47174. }
  47175. clonedSound.setPosition(this._position);
  47176. clonedSound.setPlaybackRate(this._playbackRate);
  47177. setBufferAndRun();
  47178. return clonedSound;
  47179. }
  47180. else {
  47181. return null;
  47182. }
  47183. };
  47184. Sound.prototype.getAudioBuffer = function () {
  47185. return this._audioBuffer;
  47186. };
  47187. Sound.prototype.serialize = function () {
  47188. var serializationObject = {
  47189. name: this.name,
  47190. url: this.name,
  47191. autoplay: this.autoplay,
  47192. loop: this.loop,
  47193. volume: this._volume,
  47194. spatialSound: this.spatialSound,
  47195. maxDistance: this.maxDistance,
  47196. rolloffFactor: this.rolloffFactor,
  47197. refDistance: this.refDistance,
  47198. distanceModel: this.distanceModel,
  47199. playbackRate: this._playbackRate,
  47200. panningModel: this._panningModel,
  47201. soundTrackId: this.soundTrackId
  47202. };
  47203. if (this.spatialSound) {
  47204. if (this._connectedMesh)
  47205. serializationObject.connectedMeshId = this._connectedMesh.id;
  47206. serializationObject.position = this._position.asArray();
  47207. serializationObject.refDistance = this.refDistance;
  47208. serializationObject.distanceModel = this.distanceModel;
  47209. serializationObject.isDirectional = this._isDirectional;
  47210. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  47211. serializationObject.coneInnerAngle = this._coneInnerAngle;
  47212. serializationObject.coneOuterAngle = this._coneOuterAngle;
  47213. serializationObject.coneOuterGain = this._coneOuterGain;
  47214. }
  47215. return serializationObject;
  47216. };
  47217. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  47218. var soundName = parsedSound.name;
  47219. var soundUrl;
  47220. if (parsedSound.url) {
  47221. soundUrl = rootUrl + parsedSound.url;
  47222. }
  47223. else {
  47224. soundUrl = rootUrl + soundName;
  47225. }
  47226. var options = {
  47227. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  47228. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  47229. rolloffFactor: parsedSound.rolloffFactor,
  47230. refDistance: parsedSound.refDistance,
  47231. distanceModel: parsedSound.distanceModel,
  47232. playbackRate: parsedSound.playbackRate
  47233. };
  47234. var newSound;
  47235. if (!sourceSound) {
  47236. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  47237. scene._addPendingData(newSound);
  47238. }
  47239. else {
  47240. var setBufferAndRun = function () {
  47241. if (sourceSound._isReadyToPlay) {
  47242. newSound._audioBuffer = sourceSound.getAudioBuffer();
  47243. newSound._isReadyToPlay = true;
  47244. if (newSound.autoplay) {
  47245. newSound.play();
  47246. }
  47247. }
  47248. else {
  47249. window.setTimeout(setBufferAndRun, 300);
  47250. }
  47251. };
  47252. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  47253. setBufferAndRun();
  47254. }
  47255. if (parsedSound.position) {
  47256. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  47257. newSound.setPosition(soundPosition);
  47258. }
  47259. if (parsedSound.isDirectional) {
  47260. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  47261. if (parsedSound.localDirectionToMesh) {
  47262. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  47263. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  47264. }
  47265. }
  47266. if (parsedSound.connectedMeshId) {
  47267. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  47268. if (connectedMesh) {
  47269. newSound.attachToMesh(connectedMesh);
  47270. }
  47271. }
  47272. return newSound;
  47273. };
  47274. return Sound;
  47275. }());
  47276. BABYLON.Sound = Sound;
  47277. })(BABYLON || (BABYLON = {}));
  47278. //# sourceMappingURL=babylon.sound.js.map
  47279. var BABYLON;
  47280. (function (BABYLON) {
  47281. var SoundTrack = (function () {
  47282. function SoundTrack(scene, options) {
  47283. this.id = -1;
  47284. this._isMainTrack = false;
  47285. this._isInitialized = false;
  47286. this._scene = scene;
  47287. this.soundCollection = new Array();
  47288. this._options = options;
  47289. if (!this._isMainTrack) {
  47290. this._scene.soundTracks.push(this);
  47291. this.id = this._scene.soundTracks.length - 1;
  47292. }
  47293. }
  47294. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  47295. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47296. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  47297. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  47298. if (this._options) {
  47299. if (this._options.volume) {
  47300. this._outputAudioNode.gain.value = this._options.volume;
  47301. }
  47302. if (this._options.mainTrack) {
  47303. this._isMainTrack = this._options.mainTrack;
  47304. }
  47305. }
  47306. this._isInitialized = true;
  47307. }
  47308. };
  47309. SoundTrack.prototype.dispose = function () {
  47310. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47311. if (this._connectedAnalyser) {
  47312. this._connectedAnalyser.stopDebugCanvas();
  47313. }
  47314. while (this.soundCollection.length) {
  47315. this.soundCollection[0].dispose();
  47316. }
  47317. if (this._outputAudioNode) {
  47318. this._outputAudioNode.disconnect();
  47319. }
  47320. this._outputAudioNode = null;
  47321. }
  47322. };
  47323. SoundTrack.prototype.AddSound = function (sound) {
  47324. if (!this._isInitialized) {
  47325. this._initializeSoundTrackAudioGraph();
  47326. }
  47327. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47328. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  47329. }
  47330. if (sound.soundTrackId) {
  47331. if (sound.soundTrackId === -1) {
  47332. this._scene.mainSoundTrack.RemoveSound(sound);
  47333. }
  47334. else {
  47335. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  47336. }
  47337. }
  47338. this.soundCollection.push(sound);
  47339. sound.soundTrackId = this.id;
  47340. };
  47341. SoundTrack.prototype.RemoveSound = function (sound) {
  47342. var index = this.soundCollection.indexOf(sound);
  47343. if (index !== -1) {
  47344. this.soundCollection.splice(index, 1);
  47345. }
  47346. };
  47347. SoundTrack.prototype.setVolume = function (newVolume) {
  47348. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47349. this._outputAudioNode.gain.value = newVolume;
  47350. }
  47351. };
  47352. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  47353. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47354. for (var i = 0; i < this.soundCollection.length; i++) {
  47355. this.soundCollection[i].switchPanningModelToHRTF();
  47356. }
  47357. }
  47358. };
  47359. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  47360. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47361. for (var i = 0; i < this.soundCollection.length; i++) {
  47362. this.soundCollection[i].switchPanningModelToEqualPower();
  47363. }
  47364. }
  47365. };
  47366. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  47367. if (this._connectedAnalyser) {
  47368. this._connectedAnalyser.stopDebugCanvas();
  47369. }
  47370. this._connectedAnalyser = analyser;
  47371. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47372. this._outputAudioNode.disconnect();
  47373. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  47374. }
  47375. };
  47376. return SoundTrack;
  47377. }());
  47378. BABYLON.SoundTrack = SoundTrack;
  47379. })(BABYLON || (BABYLON = {}));
  47380. //# sourceMappingURL=babylon.soundtrack.js.map
  47381. var BABYLON;
  47382. (function (BABYLON) {
  47383. var Analyser = (function () {
  47384. function Analyser(scene) {
  47385. this.SMOOTHING = 0.75;
  47386. this.FFT_SIZE = 512;
  47387. this.BARGRAPHAMPLITUDE = 256;
  47388. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  47389. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  47390. this._scene = scene;
  47391. this._audioEngine = BABYLON.Engine.audioEngine;
  47392. if (this._audioEngine.canUseWebAudio) {
  47393. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  47394. this._webAudioAnalyser.minDecibels = -140;
  47395. this._webAudioAnalyser.maxDecibels = 0;
  47396. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  47397. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  47398. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  47399. }
  47400. }
  47401. Analyser.prototype.getFrequencyBinCount = function () {
  47402. if (this._audioEngine.canUseWebAudio) {
  47403. return this._webAudioAnalyser.frequencyBinCount;
  47404. }
  47405. else {
  47406. return 0;
  47407. }
  47408. };
  47409. Analyser.prototype.getByteFrequencyData = function () {
  47410. if (this._audioEngine.canUseWebAudio) {
  47411. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47412. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47413. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  47414. }
  47415. return this._byteFreqs;
  47416. };
  47417. Analyser.prototype.getByteTimeDomainData = function () {
  47418. if (this._audioEngine.canUseWebAudio) {
  47419. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47420. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47421. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  47422. }
  47423. return this._byteTime;
  47424. };
  47425. Analyser.prototype.getFloatFrequencyData = function () {
  47426. if (this._audioEngine.canUseWebAudio) {
  47427. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47428. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47429. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  47430. }
  47431. return this._floatFreqs;
  47432. };
  47433. Analyser.prototype.drawDebugCanvas = function () {
  47434. var _this = this;
  47435. if (this._audioEngine.canUseWebAudio) {
  47436. if (!this._debugCanvas) {
  47437. this._debugCanvas = document.createElement("canvas");
  47438. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  47439. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  47440. this._debugCanvas.style.position = "absolute";
  47441. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  47442. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  47443. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  47444. document.body.appendChild(this._debugCanvas);
  47445. this._registerFunc = function () {
  47446. _this.drawDebugCanvas();
  47447. };
  47448. this._scene.registerBeforeRender(this._registerFunc);
  47449. }
  47450. if (this._registerFunc) {
  47451. var workingArray = this.getByteFrequencyData();
  47452. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  47453. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  47454. // Draw the frequency domain chart.
  47455. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  47456. var value = workingArray[i];
  47457. var percent = value / this.BARGRAPHAMPLITUDE;
  47458. var height = this.DEBUGCANVASSIZE.height * percent;
  47459. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  47460. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  47461. var hue = i / this.getFrequencyBinCount() * 360;
  47462. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  47463. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  47464. }
  47465. }
  47466. }
  47467. };
  47468. Analyser.prototype.stopDebugCanvas = function () {
  47469. if (this._debugCanvas) {
  47470. this._scene.unregisterBeforeRender(this._registerFunc);
  47471. this._registerFunc = null;
  47472. document.body.removeChild(this._debugCanvas);
  47473. this._debugCanvas = null;
  47474. this._debugCanvasContext = null;
  47475. }
  47476. };
  47477. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  47478. if (this._audioEngine.canUseWebAudio) {
  47479. inputAudioNode.connect(this._webAudioAnalyser);
  47480. this._webAudioAnalyser.connect(outputAudioNode);
  47481. }
  47482. };
  47483. Analyser.prototype.dispose = function () {
  47484. if (this._audioEngine.canUseWebAudio) {
  47485. this._webAudioAnalyser.disconnect();
  47486. }
  47487. };
  47488. return Analyser;
  47489. }());
  47490. BABYLON.Analyser = Analyser;
  47491. })(BABYLON || (BABYLON = {}));
  47492. //# sourceMappingURL=babylon.analyser.js.map
  47493. var BABYLON;
  47494. (function (BABYLON) {
  47495. var CubeTexture = (function (_super) {
  47496. __extends(CubeTexture, _super);
  47497. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  47498. if (onLoad === void 0) { onLoad = null; }
  47499. if (onError === void 0) { onError = null; }
  47500. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  47501. if (prefiltered === void 0) { prefiltered = false; }
  47502. if (forcedExtension === void 0) { forcedExtension = null; }
  47503. var _this = _super.call(this, scene) || this;
  47504. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  47505. _this.name = rootUrl;
  47506. _this.url = rootUrl;
  47507. _this._noMipmap = noMipmap;
  47508. _this.hasAlpha = false;
  47509. _this._format = format;
  47510. _this._prefiltered = prefiltered;
  47511. _this.isCube = true;
  47512. _this._textureMatrix = BABYLON.Matrix.Identity();
  47513. if (prefiltered) {
  47514. _this.gammaSpace = false;
  47515. }
  47516. if (!rootUrl && !files) {
  47517. return _this;
  47518. }
  47519. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  47520. if (!files) {
  47521. if (!extensions) {
  47522. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  47523. }
  47524. files = [];
  47525. for (var index = 0; index < extensions.length; index++) {
  47526. files.push(rootUrl + extensions[index]);
  47527. }
  47528. _this._extensions = extensions;
  47529. }
  47530. _this._files = files;
  47531. if (!_this._texture) {
  47532. if (!scene.useDelayedTextureLoading) {
  47533. if (prefiltered) {
  47534. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  47535. }
  47536. else {
  47537. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  47538. }
  47539. }
  47540. else {
  47541. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  47542. }
  47543. }
  47544. else if (onLoad) {
  47545. if (_this._texture.isReady) {
  47546. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  47547. }
  47548. else {
  47549. _this._texture.onLoadedObservable.add(onLoad);
  47550. }
  47551. }
  47552. return _this;
  47553. }
  47554. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  47555. return new CubeTexture("", scene, null, noMipmap, files);
  47556. };
  47557. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  47558. if (forcedExtension === void 0) { forcedExtension = null; }
  47559. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  47560. };
  47561. // Methods
  47562. CubeTexture.prototype.delayLoad = function () {
  47563. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  47564. return;
  47565. }
  47566. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  47567. this._texture = this._getFromCache(this.url, this._noMipmap);
  47568. if (!this._texture) {
  47569. if (this._prefiltered) {
  47570. this._texture = this.getScene().getEngine().createPrefilteredCubeTexture(this.url, this.getScene(), this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  47571. }
  47572. else {
  47573. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  47574. }
  47575. }
  47576. };
  47577. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  47578. return this._textureMatrix;
  47579. };
  47580. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  47581. this._textureMatrix = value;
  47582. };
  47583. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  47584. var texture = BABYLON.SerializationHelper.Parse(function () {
  47585. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  47586. }, parsedTexture, scene);
  47587. // Animations
  47588. if (parsedTexture.animations) {
  47589. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  47590. var parsedAnimation = parsedTexture.animations[animationIndex];
  47591. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  47592. }
  47593. }
  47594. return texture;
  47595. };
  47596. CubeTexture.prototype.clone = function () {
  47597. var _this = this;
  47598. return BABYLON.SerializationHelper.Clone(function () {
  47599. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  47600. }, this);
  47601. };
  47602. return CubeTexture;
  47603. }(BABYLON.BaseTexture));
  47604. BABYLON.CubeTexture = CubeTexture;
  47605. })(BABYLON || (BABYLON = {}));
  47606. //# sourceMappingURL=babylon.cubeTexture.js.map
  47607. var BABYLON;
  47608. (function (BABYLON) {
  47609. var RenderTargetTexture = (function (_super) {
  47610. __extends(RenderTargetTexture, _super);
  47611. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  47612. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  47613. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  47614. if (isCube === void 0) { isCube = false; }
  47615. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  47616. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  47617. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  47618. if (isMulti === void 0) { isMulti = false; }
  47619. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  47620. _this.isCube = isCube;
  47621. /**
  47622. * Use this list to define the list of mesh you want to render.
  47623. */
  47624. _this.renderList = new Array();
  47625. _this.renderParticles = true;
  47626. _this.renderSprites = false;
  47627. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  47628. _this.ignoreCameraViewport = false;
  47629. // Events
  47630. /**
  47631. * An event triggered when the texture is unbind.
  47632. * @type {BABYLON.Observable}
  47633. */
  47634. _this.onBeforeBindObservable = new BABYLON.Observable();
  47635. /**
  47636. * An event triggered when the texture is unbind.
  47637. * @type {BABYLON.Observable}
  47638. */
  47639. _this.onAfterUnbindObservable = new BABYLON.Observable();
  47640. /**
  47641. * An event triggered before rendering the texture
  47642. * @type {BABYLON.Observable}
  47643. */
  47644. _this.onBeforeRenderObservable = new BABYLON.Observable();
  47645. /**
  47646. * An event triggered after rendering the texture
  47647. * @type {BABYLON.Observable}
  47648. */
  47649. _this.onAfterRenderObservable = new BABYLON.Observable();
  47650. /**
  47651. * An event triggered after the texture clear
  47652. * @type {BABYLON.Observable}
  47653. */
  47654. _this.onClearObservable = new BABYLON.Observable();
  47655. _this._currentRefreshId = -1;
  47656. _this._refreshRate = 1;
  47657. _this._samples = 1;
  47658. scene = _this.getScene();
  47659. _this.name = name;
  47660. _this.isRenderTarget = true;
  47661. _this._size = size;
  47662. _this._generateMipMaps = generateMipMaps;
  47663. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  47664. // Rendering groups
  47665. _this._renderingManager = new BABYLON.RenderingManager(scene);
  47666. if (isMulti) {
  47667. return _this;
  47668. }
  47669. _this._renderTargetOptions = {
  47670. generateMipMaps: generateMipMaps,
  47671. type: type,
  47672. samplingMode: samplingMode,
  47673. generateDepthBuffer: generateDepthBuffer,
  47674. generateStencilBuffer: generateStencilBuffer
  47675. };
  47676. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  47677. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47678. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47679. }
  47680. if (isCube) {
  47681. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  47682. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  47683. _this._textureMatrix = BABYLON.Matrix.Identity();
  47684. }
  47685. else {
  47686. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  47687. }
  47688. return _this;
  47689. }
  47690. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  47691. get: function () {
  47692. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  47693. },
  47694. enumerable: true,
  47695. configurable: true
  47696. });
  47697. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  47698. get: function () {
  47699. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  47700. },
  47701. enumerable: true,
  47702. configurable: true
  47703. });
  47704. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  47705. get: function () {
  47706. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  47707. },
  47708. enumerable: true,
  47709. configurable: true
  47710. });
  47711. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  47712. set: function (callback) {
  47713. if (this._onAfterUnbindObserver) {
  47714. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  47715. }
  47716. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  47717. },
  47718. enumerable: true,
  47719. configurable: true
  47720. });
  47721. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  47722. set: function (callback) {
  47723. if (this._onBeforeRenderObserver) {
  47724. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  47725. }
  47726. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  47727. },
  47728. enumerable: true,
  47729. configurable: true
  47730. });
  47731. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  47732. set: function (callback) {
  47733. if (this._onAfterRenderObserver) {
  47734. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  47735. }
  47736. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  47737. },
  47738. enumerable: true,
  47739. configurable: true
  47740. });
  47741. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  47742. set: function (callback) {
  47743. if (this._onClearObserver) {
  47744. this.onClearObservable.remove(this._onClearObserver);
  47745. }
  47746. this._onClearObserver = this.onClearObservable.add(callback);
  47747. },
  47748. enumerable: true,
  47749. configurable: true
  47750. });
  47751. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  47752. get: function () {
  47753. return this._renderTargetOptions;
  47754. },
  47755. enumerable: true,
  47756. configurable: true
  47757. });
  47758. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  47759. get: function () {
  47760. return this._samples;
  47761. },
  47762. set: function (value) {
  47763. if (this._samples === value) {
  47764. return;
  47765. }
  47766. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  47767. },
  47768. enumerable: true,
  47769. configurable: true
  47770. });
  47771. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  47772. this._currentRefreshId = -1;
  47773. };
  47774. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  47775. get: function () {
  47776. return this._refreshRate;
  47777. },
  47778. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  47779. set: function (value) {
  47780. this._refreshRate = value;
  47781. this.resetRefreshCounter();
  47782. },
  47783. enumerable: true,
  47784. configurable: true
  47785. });
  47786. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  47787. if (!this._postProcessManager) {
  47788. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  47789. this._postProcesses = new Array();
  47790. }
  47791. this._postProcesses.push(postProcess);
  47792. this._postProcesses[0].autoClear = false;
  47793. };
  47794. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  47795. if (!this._postProcesses) {
  47796. return;
  47797. }
  47798. if (dispose) {
  47799. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  47800. var postProcess = _a[_i];
  47801. postProcess.dispose();
  47802. postProcess = null;
  47803. }
  47804. }
  47805. this._postProcesses = [];
  47806. };
  47807. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  47808. if (!this._postProcesses) {
  47809. return;
  47810. }
  47811. var index = this._postProcesses.indexOf(postProcess);
  47812. if (index === -1) {
  47813. return;
  47814. }
  47815. this._postProcesses.splice(index, 1);
  47816. if (this._postProcesses.length > 0) {
  47817. this._postProcesses[0].autoClear = false;
  47818. }
  47819. };
  47820. RenderTargetTexture.prototype._shouldRender = function () {
  47821. if (this._currentRefreshId === -1) {
  47822. this._currentRefreshId = 1;
  47823. return true;
  47824. }
  47825. if (this.refreshRate === this._currentRefreshId) {
  47826. this._currentRefreshId = 1;
  47827. return true;
  47828. }
  47829. this._currentRefreshId++;
  47830. return false;
  47831. };
  47832. RenderTargetTexture.prototype.getRenderSize = function () {
  47833. return this._size;
  47834. };
  47835. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  47836. get: function () {
  47837. return true;
  47838. },
  47839. enumerable: true,
  47840. configurable: true
  47841. });
  47842. RenderTargetTexture.prototype.scale = function (ratio) {
  47843. var newSize = this._size * ratio;
  47844. this.resize(newSize);
  47845. };
  47846. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  47847. if (this.isCube) {
  47848. return this._textureMatrix;
  47849. }
  47850. return _super.prototype.getReflectionTextureMatrix.call(this);
  47851. };
  47852. RenderTargetTexture.prototype.resize = function (size) {
  47853. this.releaseInternalTexture();
  47854. if (this.isCube) {
  47855. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  47856. }
  47857. else {
  47858. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  47859. }
  47860. this._size = size;
  47861. };
  47862. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  47863. var scene = this.getScene();
  47864. var engine = scene.getEngine();
  47865. if (this.useCameraPostProcesses !== undefined) {
  47866. useCameraPostProcess = this.useCameraPostProcesses;
  47867. }
  47868. if (this._waitingRenderList) {
  47869. this.renderList = [];
  47870. for (var index = 0; index < this._waitingRenderList.length; index++) {
  47871. var id = this._waitingRenderList[index];
  47872. this.renderList.push(scene.getMeshByID(id));
  47873. }
  47874. delete this._waitingRenderList;
  47875. }
  47876. // Is predicate defined?
  47877. if (this.renderListPredicate) {
  47878. this.renderList.splice(0); // Clear previous renderList
  47879. var sceneMeshes = this.getScene().meshes;
  47880. for (var index = 0; index < sceneMeshes.length; index++) {
  47881. var mesh = sceneMeshes[index];
  47882. if (this.renderListPredicate(mesh)) {
  47883. this.renderList.push(mesh);
  47884. }
  47885. }
  47886. }
  47887. if (this.renderList && this.renderList.length === 0) {
  47888. return;
  47889. }
  47890. this.onBeforeBindObservable.notifyObservers(this);
  47891. // Set custom projection.
  47892. // Needs to be before binding to prevent changing the aspect ratio.
  47893. var camera;
  47894. if (this.activeCamera) {
  47895. camera = this.activeCamera;
  47896. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  47897. if (this.activeCamera !== scene.activeCamera) {
  47898. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  47899. }
  47900. }
  47901. else {
  47902. camera = scene.activeCamera;
  47903. engine.setViewport(scene.activeCamera.viewport, this._size, this._size);
  47904. }
  47905. // Prepare renderingManager
  47906. this._renderingManager.reset();
  47907. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  47908. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  47909. var sceneRenderId = scene.getRenderId();
  47910. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  47911. var mesh = currentRenderList[meshIndex];
  47912. if (mesh) {
  47913. if (!mesh.isReady()) {
  47914. // Reset _currentRefreshId
  47915. this.resetRefreshCounter();
  47916. continue;
  47917. }
  47918. mesh._preActivateForIntermediateRendering(sceneRenderId);
  47919. var isMasked = void 0;
  47920. if (!this.renderList) {
  47921. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  47922. }
  47923. else {
  47924. isMasked = false;
  47925. }
  47926. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  47927. mesh._activate(sceneRenderId);
  47928. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  47929. var subMesh = mesh.subMeshes[subIndex];
  47930. scene._activeIndices.addCount(subMesh.indexCount, false);
  47931. this._renderingManager.dispatch(subMesh);
  47932. }
  47933. }
  47934. }
  47935. }
  47936. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  47937. var particleSystem = scene.particleSystems[particleIndex];
  47938. var emitter = particleSystem.emitter;
  47939. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  47940. continue;
  47941. }
  47942. if (currentRenderList.indexOf(emitter) >= 0) {
  47943. this._renderingManager.dispatchParticles(particleSystem);
  47944. }
  47945. }
  47946. if (this.isCube) {
  47947. for (var face = 0; face < 6; face++) {
  47948. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  47949. scene.incrementRenderId();
  47950. scene.resetCachedMaterial();
  47951. }
  47952. }
  47953. else {
  47954. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  47955. }
  47956. this.onAfterUnbindObservable.notifyObservers(this);
  47957. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  47958. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  47959. }
  47960. engine.setViewport(scene.activeCamera.viewport);
  47961. scene.resetCachedMaterial();
  47962. };
  47963. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  47964. var _this = this;
  47965. var scene = this.getScene();
  47966. var engine = scene.getEngine();
  47967. // Bind
  47968. if (this._postProcessManager) {
  47969. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  47970. }
  47971. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  47972. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  47973. }
  47974. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  47975. // Clear
  47976. if (this.onClearObservable.hasObservers()) {
  47977. this.onClearObservable.notifyObservers(engine);
  47978. }
  47979. else {
  47980. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  47981. }
  47982. if (!this._doNotChangeAspectRatio) {
  47983. scene.updateTransformMatrix(true);
  47984. }
  47985. // Render
  47986. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  47987. if (this._postProcessManager) {
  47988. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  47989. }
  47990. else if (useCameraPostProcess) {
  47991. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  47992. }
  47993. if (!this._doNotChangeAspectRatio) {
  47994. scene.updateTransformMatrix(true);
  47995. }
  47996. // Dump ?
  47997. if (dumpForDebug) {
  47998. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  47999. }
  48000. // Unbind
  48001. if (!this.isCube || faceIndex === 5) {
  48002. if (this.isCube) {
  48003. if (faceIndex === 5) {
  48004. engine.generateMipMapsForCubemap(this._texture);
  48005. }
  48006. }
  48007. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  48008. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  48009. });
  48010. }
  48011. else {
  48012. this.onAfterRenderObservable.notifyObservers(faceIndex);
  48013. }
  48014. };
  48015. /**
  48016. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  48017. * This allowed control for front to back rendering or reversly depending of the special needs.
  48018. *
  48019. * @param renderingGroupId The rendering group id corresponding to its index
  48020. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  48021. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  48022. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  48023. */
  48024. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  48025. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  48026. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  48027. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  48028. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  48029. };
  48030. /**
  48031. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  48032. *
  48033. * @param renderingGroupId The rendering group id corresponding to its index
  48034. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  48035. */
  48036. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  48037. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  48038. };
  48039. RenderTargetTexture.prototype.clone = function () {
  48040. var textureSize = this.getSize();
  48041. 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);
  48042. // Base texture
  48043. newTexture.hasAlpha = this.hasAlpha;
  48044. newTexture.level = this.level;
  48045. // RenderTarget Texture
  48046. newTexture.coordinatesMode = this.coordinatesMode;
  48047. newTexture.renderList = this.renderList.slice(0);
  48048. return newTexture;
  48049. };
  48050. RenderTargetTexture.prototype.serialize = function () {
  48051. if (!this.name) {
  48052. return null;
  48053. }
  48054. var serializationObject = _super.prototype.serialize.call(this);
  48055. serializationObject.renderTargetSize = this.getRenderSize();
  48056. serializationObject.renderList = [];
  48057. for (var index = 0; index < this.renderList.length; index++) {
  48058. serializationObject.renderList.push(this.renderList[index].id);
  48059. }
  48060. return serializationObject;
  48061. };
  48062. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  48063. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  48064. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  48065. };
  48066. RenderTargetTexture.prototype.dispose = function () {
  48067. if (this._postProcessManager) {
  48068. this._postProcessManager.dispose();
  48069. this._postProcessManager = null;
  48070. }
  48071. this.clearPostProcesses(true);
  48072. this.renderList = null;
  48073. // Remove from custom render targets
  48074. var scene = this.getScene();
  48075. var index = scene.customRenderTargets.indexOf(this);
  48076. if (index >= 0) {
  48077. scene.customRenderTargets.splice(index, 1);
  48078. }
  48079. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  48080. var camera = _a[_i];
  48081. index = camera.customRenderTargets.indexOf(this);
  48082. if (index >= 0) {
  48083. camera.customRenderTargets.splice(index, 1);
  48084. }
  48085. }
  48086. _super.prototype.dispose.call(this);
  48087. };
  48088. RenderTargetTexture.prototype._rebuild = function () {
  48089. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  48090. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  48091. }
  48092. if (this._postProcessManager) {
  48093. this._postProcessManager._rebuild();
  48094. }
  48095. };
  48096. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  48097. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  48098. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  48099. return RenderTargetTexture;
  48100. }(BABYLON.Texture));
  48101. BABYLON.RenderTargetTexture = RenderTargetTexture;
  48102. })(BABYLON || (BABYLON = {}));
  48103. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  48104. var BABYLON;
  48105. (function (BABYLON) {
  48106. ;
  48107. var MultiRenderTarget = (function (_super) {
  48108. __extends(MultiRenderTarget, _super);
  48109. function MultiRenderTarget(name, size, count, scene, options) {
  48110. var _this = this;
  48111. options = options || {};
  48112. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  48113. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  48114. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  48115. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  48116. if (!_this.isSupported) {
  48117. _this.dispose();
  48118. return;
  48119. }
  48120. var types = [];
  48121. var samplingModes = [];
  48122. for (var i = 0; i < count; i++) {
  48123. if (options.types && options.types[i]) {
  48124. types.push(options.types[i]);
  48125. }
  48126. else {
  48127. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  48128. }
  48129. if (options.samplingModes && options.samplingModes[i]) {
  48130. samplingModes.push(options.samplingModes[i]);
  48131. }
  48132. else {
  48133. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  48134. }
  48135. }
  48136. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  48137. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  48138. _this._count = count;
  48139. _this._size = size;
  48140. _this._multiRenderTargetOptions = {
  48141. samplingModes: samplingModes,
  48142. generateMipMaps: generateMipMaps,
  48143. generateDepthBuffer: generateDepthBuffer,
  48144. generateStencilBuffer: generateStencilBuffer,
  48145. generateDepthTexture: generateDepthTexture,
  48146. types: types,
  48147. textureCount: count
  48148. };
  48149. _this._createInternalTextures();
  48150. _this._createTextures();
  48151. return _this;
  48152. }
  48153. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  48154. get: function () {
  48155. var engine = this.getScene().getEngine();
  48156. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  48157. },
  48158. enumerable: true,
  48159. configurable: true
  48160. });
  48161. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  48162. get: function () {
  48163. return this._textures;
  48164. },
  48165. enumerable: true,
  48166. configurable: true
  48167. });
  48168. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  48169. get: function () {
  48170. return this._textures[this._textures.length - 1];
  48171. },
  48172. enumerable: true,
  48173. configurable: true
  48174. });
  48175. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  48176. set: function (wrap) {
  48177. if (this._textures) {
  48178. for (var i = 0; i < this._textures.length; i++) {
  48179. this._textures[i].wrapU = wrap;
  48180. }
  48181. }
  48182. },
  48183. enumerable: true,
  48184. configurable: true
  48185. });
  48186. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  48187. set: function (wrap) {
  48188. if (this._textures) {
  48189. for (var i = 0; i < this._textures.length; i++) {
  48190. this._textures[i].wrapV = wrap;
  48191. }
  48192. }
  48193. },
  48194. enumerable: true,
  48195. configurable: true
  48196. });
  48197. MultiRenderTarget.prototype._rebuild = function () {
  48198. this.releaseInternalTextures();
  48199. this._createInternalTextures();
  48200. for (var i = 0; i < this._internalTextures.length; i++) {
  48201. var texture = this._textures[i];
  48202. texture._texture = this._internalTextures[i];
  48203. }
  48204. // Keeps references to frame buffer and stencil/depth buffer
  48205. this._texture = this._internalTextures[0];
  48206. };
  48207. MultiRenderTarget.prototype._createInternalTextures = function () {
  48208. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  48209. };
  48210. MultiRenderTarget.prototype._createTextures = function () {
  48211. this._textures = [];
  48212. for (var i = 0; i < this._internalTextures.length; i++) {
  48213. var texture = new BABYLON.Texture(null, this.getScene());
  48214. texture._texture = this._internalTextures[i];
  48215. this._textures.push(texture);
  48216. }
  48217. // Keeps references to frame buffer and stencil/depth buffer
  48218. this._texture = this._internalTextures[0];
  48219. };
  48220. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  48221. get: function () {
  48222. return this._samples;
  48223. },
  48224. set: function (value) {
  48225. if (this._samples === value) {
  48226. return;
  48227. }
  48228. for (var i = 0; i < this._internalTextures.length; i++) {
  48229. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  48230. }
  48231. },
  48232. enumerable: true,
  48233. configurable: true
  48234. });
  48235. MultiRenderTarget.prototype.resize = function (size) {
  48236. this.releaseInternalTextures();
  48237. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  48238. this._createInternalTextures();
  48239. };
  48240. MultiRenderTarget.prototype.dispose = function () {
  48241. this.releaseInternalTextures();
  48242. _super.prototype.dispose.call(this);
  48243. };
  48244. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  48245. if (!this._internalTextures) {
  48246. return;
  48247. }
  48248. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  48249. if (this._internalTextures[i] !== undefined) {
  48250. this._internalTextures[i].dispose();
  48251. this._internalTextures.splice(i, 1);
  48252. }
  48253. }
  48254. };
  48255. return MultiRenderTarget;
  48256. }(BABYLON.RenderTargetTexture));
  48257. BABYLON.MultiRenderTarget = MultiRenderTarget;
  48258. })(BABYLON || (BABYLON = {}));
  48259. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  48260. /// <reference path="babylon.renderTargetTexture.ts" />
  48261. var BABYLON;
  48262. (function (BABYLON) {
  48263. var MirrorTexture = (function (_super) {
  48264. __extends(MirrorTexture, _super);
  48265. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  48266. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  48267. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48268. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  48269. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  48270. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  48271. _this._transformMatrix = BABYLON.Matrix.Zero();
  48272. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  48273. _this._blurKernelX = 0;
  48274. _this._blurKernelY = 0;
  48275. _this._blurRatio = 1.0;
  48276. _this.ignoreCameraViewport = true;
  48277. _this.onBeforeRenderObservable.add(function () {
  48278. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  48279. _this._savedViewMatrix = scene.getViewMatrix();
  48280. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  48281. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  48282. scene.clipPlane = _this.mirrorPlane;
  48283. scene.getEngine().cullBackFaces = false;
  48284. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  48285. });
  48286. _this.onAfterRenderObservable.add(function () {
  48287. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  48288. scene.getEngine().cullBackFaces = true;
  48289. scene._mirroredCameraPosition = null;
  48290. delete scene.clipPlane;
  48291. });
  48292. return _this;
  48293. }
  48294. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  48295. get: function () {
  48296. return this._blurRatio;
  48297. },
  48298. set: function (value) {
  48299. if (this._blurRatio === value) {
  48300. return;
  48301. }
  48302. this._blurRatio = value;
  48303. this._preparePostProcesses();
  48304. },
  48305. enumerable: true,
  48306. configurable: true
  48307. });
  48308. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  48309. set: function (value) {
  48310. this.blurKernelX = value;
  48311. this.blurKernelY = value;
  48312. },
  48313. enumerable: true,
  48314. configurable: true
  48315. });
  48316. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  48317. get: function () {
  48318. return this._blurKernelX;
  48319. },
  48320. set: function (value) {
  48321. if (this._blurKernelX === value) {
  48322. return;
  48323. }
  48324. this._blurKernelX = value;
  48325. this._preparePostProcesses();
  48326. },
  48327. enumerable: true,
  48328. configurable: true
  48329. });
  48330. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  48331. get: function () {
  48332. return this._blurKernelY;
  48333. },
  48334. set: function (value) {
  48335. if (this._blurKernelY === value) {
  48336. return;
  48337. }
  48338. this._blurKernelY = value;
  48339. this._preparePostProcesses();
  48340. },
  48341. enumerable: true,
  48342. configurable: true
  48343. });
  48344. MirrorTexture.prototype._preparePostProcesses = function () {
  48345. this.clearPostProcesses(true);
  48346. if (this._blurKernelX && this._blurKernelY) {
  48347. var engine = this.getScene().getEngine();
  48348. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  48349. 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);
  48350. this._blurX.autoClear = false;
  48351. if (this._blurRatio === 1 && this.samples < 2) {
  48352. this._blurX.outputTexture = this._texture;
  48353. }
  48354. else {
  48355. this._blurX.alwaysForcePOT = true;
  48356. }
  48357. 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);
  48358. this._blurY.autoClear = false;
  48359. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  48360. this.addPostProcess(this._blurX);
  48361. this.addPostProcess(this._blurY);
  48362. }
  48363. };
  48364. MirrorTexture.prototype.clone = function () {
  48365. var textureSize = this.getSize();
  48366. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  48367. // Base texture
  48368. newTexture.hasAlpha = this.hasAlpha;
  48369. newTexture.level = this.level;
  48370. // Mirror Texture
  48371. newTexture.mirrorPlane = this.mirrorPlane.clone();
  48372. newTexture.renderList = this.renderList.slice(0);
  48373. return newTexture;
  48374. };
  48375. MirrorTexture.prototype.serialize = function () {
  48376. if (!this.name) {
  48377. return null;
  48378. }
  48379. var serializationObject = _super.prototype.serialize.call(this);
  48380. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  48381. return serializationObject;
  48382. };
  48383. return MirrorTexture;
  48384. }(BABYLON.RenderTargetTexture));
  48385. BABYLON.MirrorTexture = MirrorTexture;
  48386. })(BABYLON || (BABYLON = {}));
  48387. //# sourceMappingURL=babylon.mirrorTexture.js.map
  48388. /// <reference path="babylon.renderTargetTexture.ts" />
  48389. var BABYLON;
  48390. (function (BABYLON) {
  48391. /**
  48392. * Creates a refraction texture used by refraction channel of the standard material.
  48393. * @param name the texture name
  48394. * @param size size of the underlying texture
  48395. * @param scene root scene
  48396. */
  48397. var RefractionTexture = (function (_super) {
  48398. __extends(RefractionTexture, _super);
  48399. function RefractionTexture(name, size, scene, generateMipMaps) {
  48400. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  48401. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  48402. _this.depth = 2.0;
  48403. _this.onBeforeRenderObservable.add(function () {
  48404. scene.clipPlane = _this.refractionPlane;
  48405. });
  48406. _this.onAfterRenderObservable.add(function () {
  48407. delete scene.clipPlane;
  48408. });
  48409. return _this;
  48410. }
  48411. RefractionTexture.prototype.clone = function () {
  48412. var textureSize = this.getSize();
  48413. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  48414. // Base texture
  48415. newTexture.hasAlpha = this.hasAlpha;
  48416. newTexture.level = this.level;
  48417. // Refraction Texture
  48418. newTexture.refractionPlane = this.refractionPlane.clone();
  48419. newTexture.renderList = this.renderList.slice(0);
  48420. newTexture.depth = this.depth;
  48421. return newTexture;
  48422. };
  48423. RefractionTexture.prototype.serialize = function () {
  48424. if (!this.name) {
  48425. return null;
  48426. }
  48427. var serializationObject = _super.prototype.serialize.call(this);
  48428. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  48429. serializationObject.depth = this.depth;
  48430. return serializationObject;
  48431. };
  48432. return RefractionTexture;
  48433. }(BABYLON.RenderTargetTexture));
  48434. BABYLON.RefractionTexture = RefractionTexture;
  48435. })(BABYLON || (BABYLON = {}));
  48436. //# sourceMappingURL=babylon.refractionTexture.js.map
  48437. /// <reference path="babylon.texture.ts" />
  48438. var BABYLON;
  48439. (function (BABYLON) {
  48440. var DynamicTexture = (function (_super) {
  48441. __extends(DynamicTexture, _super);
  48442. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  48443. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48444. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  48445. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  48446. _this.name = name;
  48447. var engine = _this.getScene().getEngine();
  48448. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48449. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48450. _this._generateMipMaps = generateMipMaps;
  48451. if (options.getContext) {
  48452. _this._canvas = options;
  48453. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  48454. }
  48455. else {
  48456. _this._canvas = document.createElement("canvas");
  48457. if (options.width) {
  48458. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  48459. }
  48460. else {
  48461. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  48462. }
  48463. }
  48464. var textureSize = _this.getSize();
  48465. _this._canvas.width = textureSize.width;
  48466. _this._canvas.height = textureSize.height;
  48467. _this._context = _this._canvas.getContext("2d");
  48468. return _this;
  48469. }
  48470. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  48471. get: function () {
  48472. return true;
  48473. },
  48474. enumerable: true,
  48475. configurable: true
  48476. });
  48477. DynamicTexture.prototype._recreate = function (textureSize) {
  48478. this._canvas.width = textureSize.width;
  48479. this._canvas.height = textureSize.height;
  48480. this.releaseInternalTexture();
  48481. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  48482. };
  48483. DynamicTexture.prototype.scale = function (ratio) {
  48484. var textureSize = this.getSize();
  48485. textureSize.width *= ratio;
  48486. textureSize.height *= ratio;
  48487. this._recreate(textureSize);
  48488. };
  48489. DynamicTexture.prototype.scaleTo = function (width, height) {
  48490. var textureSize = this.getSize();
  48491. textureSize.width = width;
  48492. textureSize.height = height;
  48493. this._recreate(textureSize);
  48494. };
  48495. DynamicTexture.prototype.getContext = function () {
  48496. return this._context;
  48497. };
  48498. DynamicTexture.prototype.clear = function () {
  48499. var size = this.getSize();
  48500. this._context.fillRect(0, 0, size.width, size.height);
  48501. };
  48502. DynamicTexture.prototype.update = function (invertY) {
  48503. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  48504. };
  48505. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  48506. if (update === void 0) { update = true; }
  48507. var size = this.getSize();
  48508. if (clearColor) {
  48509. this._context.fillStyle = clearColor;
  48510. this._context.fillRect(0, 0, size.width, size.height);
  48511. }
  48512. this._context.font = font;
  48513. if (x === null || x === undefined) {
  48514. var textSize = this._context.measureText(text);
  48515. x = (size.width - textSize.width) / 2;
  48516. }
  48517. if (y === null || y === undefined) {
  48518. var fontSize = parseInt((font.replace(/\D/g, '')));
  48519. ;
  48520. y = (size.height / 2) + (fontSize / 3.65);
  48521. }
  48522. this._context.fillStyle = color;
  48523. this._context.fillText(text, x, y);
  48524. if (update) {
  48525. this.update(invertY);
  48526. }
  48527. };
  48528. DynamicTexture.prototype.clone = function () {
  48529. var textureSize = this.getSize();
  48530. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  48531. // Base texture
  48532. newTexture.hasAlpha = this.hasAlpha;
  48533. newTexture.level = this.level;
  48534. // Dynamic Texture
  48535. newTexture.wrapU = this.wrapU;
  48536. newTexture.wrapV = this.wrapV;
  48537. return newTexture;
  48538. };
  48539. DynamicTexture.prototype._rebuild = function () {
  48540. this.update();
  48541. };
  48542. return DynamicTexture;
  48543. }(BABYLON.Texture));
  48544. BABYLON.DynamicTexture = DynamicTexture;
  48545. })(BABYLON || (BABYLON = {}));
  48546. //# sourceMappingURL=babylon.dynamicTexture.js.map
  48547. var BABYLON;
  48548. (function (BABYLON) {
  48549. var VideoTexture = (function (_super) {
  48550. __extends(VideoTexture, _super);
  48551. /**
  48552. * Creates a video texture.
  48553. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  48554. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  48555. * @param {BABYLON.Scene} scene is obviously the current scene.
  48556. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  48557. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  48558. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  48559. */
  48560. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  48561. if (generateMipMaps === void 0) { generateMipMaps = false; }
  48562. if (invertY === void 0) { invertY = false; }
  48563. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48564. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  48565. _this._autoLaunch = true;
  48566. var urls;
  48567. _this.name = name;
  48568. if (urlsOrVideo instanceof HTMLVideoElement) {
  48569. _this.video = urlsOrVideo;
  48570. }
  48571. else {
  48572. urls = urlsOrVideo;
  48573. _this.video = document.createElement("video");
  48574. _this.video.autoplay = false;
  48575. _this.video.loop = true;
  48576. }
  48577. _this._generateMipMaps = generateMipMaps;
  48578. _this._samplingMode = samplingMode;
  48579. if (!_this.getScene().getEngine().needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  48580. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  48581. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  48582. }
  48583. else {
  48584. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48585. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48586. _this._generateMipMaps = false;
  48587. }
  48588. if (urls) {
  48589. _this.video.addEventListener("canplay", function () {
  48590. _this._createTexture();
  48591. });
  48592. urls.forEach(function (url) {
  48593. var source = document.createElement("source");
  48594. source.src = url;
  48595. _this.video.appendChild(source);
  48596. });
  48597. }
  48598. else {
  48599. _this._createTexture();
  48600. }
  48601. _this._lastUpdate = BABYLON.Tools.Now;
  48602. return _this;
  48603. }
  48604. VideoTexture.prototype.__setTextureReady = function () {
  48605. this._texture.isReady = true;
  48606. };
  48607. VideoTexture.prototype._createTexture = function () {
  48608. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  48609. if (this._autoLaunch) {
  48610. this._autoLaunch = false;
  48611. this.video.play();
  48612. }
  48613. this._setTextureReady = this.__setTextureReady.bind(this);
  48614. this.video.addEventListener("playing", this._setTextureReady);
  48615. };
  48616. VideoTexture.prototype._rebuild = function () {
  48617. this.update();
  48618. };
  48619. VideoTexture.prototype.update = function () {
  48620. var now = BABYLON.Tools.Now;
  48621. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  48622. return false;
  48623. }
  48624. this._lastUpdate = now;
  48625. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  48626. return true;
  48627. };
  48628. VideoTexture.prototype.dispose = function () {
  48629. _super.prototype.dispose.call(this);
  48630. this.video.removeEventListener("playing", this._setTextureReady);
  48631. };
  48632. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  48633. var video = document.createElement("video");
  48634. var constraintsDeviceId;
  48635. if (constraints && constraints.deviceId) {
  48636. constraintsDeviceId = {
  48637. exact: constraints.deviceId
  48638. };
  48639. }
  48640. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  48641. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  48642. if (navigator.getUserMedia) {
  48643. navigator.getUserMedia({
  48644. video: {
  48645. deviceId: constraintsDeviceId,
  48646. width: {
  48647. min: (constraints && constraints.minWidth) || 256,
  48648. max: (constraints && constraints.maxWidth) || 640
  48649. },
  48650. height: {
  48651. min: (constraints && constraints.minHeight) || 256,
  48652. max: (constraints && constraints.maxHeight) || 480
  48653. }
  48654. }
  48655. }, function (stream) {
  48656. if (video.mozSrcObject !== undefined) {
  48657. video.mozSrcObject = stream;
  48658. }
  48659. else {
  48660. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  48661. }
  48662. video.play();
  48663. if (onReady) {
  48664. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  48665. }
  48666. }, function (e) {
  48667. BABYLON.Tools.Error(e.name);
  48668. });
  48669. }
  48670. };
  48671. return VideoTexture;
  48672. }(BABYLON.Texture));
  48673. BABYLON.VideoTexture = VideoTexture;
  48674. })(BABYLON || (BABYLON = {}));
  48675. //# sourceMappingURL=babylon.videoTexture.js.map
  48676. var BABYLON;
  48677. (function (BABYLON) {
  48678. var RawTexture = (function (_super) {
  48679. __extends(RawTexture, _super);
  48680. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  48681. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48682. if (invertY === void 0) { invertY = false; }
  48683. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48684. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  48685. _this.format = format;
  48686. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  48687. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48688. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48689. return _this;
  48690. }
  48691. RawTexture.prototype.update = function (data) {
  48692. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  48693. };
  48694. // Statics
  48695. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48696. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48697. if (invertY === void 0) { invertY = false; }
  48698. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48699. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  48700. };
  48701. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48702. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48703. if (invertY === void 0) { invertY = false; }
  48704. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48705. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  48706. };
  48707. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48708. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48709. if (invertY === void 0) { invertY = false; }
  48710. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48711. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  48712. };
  48713. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48714. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48715. if (invertY === void 0) { invertY = false; }
  48716. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48717. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  48718. };
  48719. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  48720. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48721. if (invertY === void 0) { invertY = false; }
  48722. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48723. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  48724. };
  48725. return RawTexture;
  48726. }(BABYLON.Texture));
  48727. BABYLON.RawTexture = RawTexture;
  48728. })(BABYLON || (BABYLON = {}));
  48729. //# sourceMappingURL=babylon.rawTexture.js.map
  48730. var BABYLON;
  48731. (function (BABYLON) {
  48732. var PostProcess = (function () {
  48733. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  48734. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  48735. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  48736. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  48737. if (blockCompilation === void 0) { blockCompilation = false; }
  48738. this.name = name;
  48739. this.width = -1;
  48740. this.height = -1;
  48741. this.autoClear = true;
  48742. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  48743. /*
  48744. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  48745. Can only be used on a single postprocess or on the last one of a chain.
  48746. */
  48747. this.enablePixelPerfectMode = false;
  48748. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  48749. this.alwaysForcePOT = false;
  48750. this.samples = 1;
  48751. this.adaptScaleToCurrentViewport = false;
  48752. this._reusable = false;
  48753. this._textures = new BABYLON.SmartArray(2);
  48754. this._currentRenderTextureInd = 0;
  48755. this._scaleRatio = new BABYLON.Vector2(1, 1);
  48756. this._texelSize = BABYLON.Vector2.Zero();
  48757. // Events
  48758. /**
  48759. * An event triggered when the postprocess is activated.
  48760. * @type {BABYLON.Observable}
  48761. */
  48762. this.onActivateObservable = new BABYLON.Observable();
  48763. /**
  48764. * An event triggered when the postprocess changes its size.
  48765. * @type {BABYLON.Observable}
  48766. */
  48767. this.onSizeChangedObservable = new BABYLON.Observable();
  48768. /**
  48769. * An event triggered when the postprocess applies its effect.
  48770. * @type {BABYLON.Observable}
  48771. */
  48772. this.onApplyObservable = new BABYLON.Observable();
  48773. /**
  48774. * An event triggered before rendering the postprocess
  48775. * @type {BABYLON.Observable}
  48776. */
  48777. this.onBeforeRenderObservable = new BABYLON.Observable();
  48778. /**
  48779. * An event triggered after rendering the postprocess
  48780. * @type {BABYLON.Observable}
  48781. */
  48782. this.onAfterRenderObservable = new BABYLON.Observable();
  48783. if (camera != null) {
  48784. this._camera = camera;
  48785. this._scene = camera.getScene();
  48786. camera.attachPostProcess(this);
  48787. this._engine = this._scene.getEngine();
  48788. this._scene.postProcesses.push(this);
  48789. }
  48790. else {
  48791. this._engine = engine;
  48792. this._engine.postProcesses.push(this);
  48793. }
  48794. this._options = options;
  48795. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  48796. this._reusable = reusable || false;
  48797. this._textureType = textureType;
  48798. this._samplers = samplers || [];
  48799. this._samplers.push("textureSampler");
  48800. this._fragmentUrl = fragmentUrl;
  48801. this._vertexUrl = vertexUrl;
  48802. this._parameters = parameters || [];
  48803. this._parameters.push("scale");
  48804. this._indexParameters = indexParameters;
  48805. if (!blockCompilation) {
  48806. this.updateEffect(defines);
  48807. }
  48808. }
  48809. Object.defineProperty(PostProcess.prototype, "onActivate", {
  48810. set: function (callback) {
  48811. if (this._onActivateObserver) {
  48812. this.onActivateObservable.remove(this._onActivateObserver);
  48813. }
  48814. this._onActivateObserver = this.onActivateObservable.add(callback);
  48815. },
  48816. enumerable: true,
  48817. configurable: true
  48818. });
  48819. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  48820. set: function (callback) {
  48821. if (this._onSizeChangedObserver) {
  48822. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  48823. }
  48824. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  48825. },
  48826. enumerable: true,
  48827. configurable: true
  48828. });
  48829. Object.defineProperty(PostProcess.prototype, "onApply", {
  48830. set: function (callback) {
  48831. if (this._onApplyObserver) {
  48832. this.onApplyObservable.remove(this._onApplyObserver);
  48833. }
  48834. this._onApplyObserver = this.onApplyObservable.add(callback);
  48835. },
  48836. enumerable: true,
  48837. configurable: true
  48838. });
  48839. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  48840. set: function (callback) {
  48841. if (this._onBeforeRenderObserver) {
  48842. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  48843. }
  48844. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  48845. },
  48846. enumerable: true,
  48847. configurable: true
  48848. });
  48849. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  48850. set: function (callback) {
  48851. if (this._onAfterRenderObserver) {
  48852. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  48853. }
  48854. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  48855. },
  48856. enumerable: true,
  48857. configurable: true
  48858. });
  48859. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  48860. get: function () {
  48861. return this._textures.data[this._currentRenderTextureInd];
  48862. },
  48863. set: function (value) {
  48864. this._forcedOutputTexture = value;
  48865. },
  48866. enumerable: true,
  48867. configurable: true
  48868. });
  48869. PostProcess.prototype.getCamera = function () {
  48870. return this._camera;
  48871. };
  48872. Object.defineProperty(PostProcess.prototype, "texelSize", {
  48873. get: function () {
  48874. if (this._shareOutputWithPostProcess) {
  48875. return this._shareOutputWithPostProcess.texelSize;
  48876. }
  48877. if (this._forcedOutputTexture) {
  48878. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  48879. }
  48880. return this._texelSize;
  48881. },
  48882. enumerable: true,
  48883. configurable: true
  48884. });
  48885. PostProcess.prototype.getEngine = function () {
  48886. return this._engine;
  48887. };
  48888. PostProcess.prototype.getEffect = function () {
  48889. return this._effect;
  48890. };
  48891. PostProcess.prototype.shareOutputWith = function (postProcess) {
  48892. this._disposeTextures();
  48893. this._shareOutputWithPostProcess = postProcess;
  48894. return this;
  48895. };
  48896. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  48897. 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);
  48898. };
  48899. PostProcess.prototype.isReusable = function () {
  48900. return this._reusable;
  48901. };
  48902. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  48903. PostProcess.prototype.markTextureDirty = function () {
  48904. this.width = -1;
  48905. };
  48906. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  48907. var _this = this;
  48908. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  48909. camera = camera || this._camera;
  48910. var scene = camera.getScene();
  48911. var engine = scene.getEngine();
  48912. var maxSize = engine.getCaps().maxTextureSize;
  48913. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  48914. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  48915. var desiredWidth = (this._options.width || requiredWidth);
  48916. var desiredHeight = this._options.height || requiredHeight;
  48917. if (this.adaptScaleToCurrentViewport) {
  48918. var currentViewport = engine.currentViewport;
  48919. if (currentViewport) {
  48920. desiredWidth *= currentViewport.width;
  48921. desiredHeight *= currentViewport.height;
  48922. }
  48923. }
  48924. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  48925. if (!this._options.width) {
  48926. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  48927. }
  48928. if (!this._options.height) {
  48929. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  48930. }
  48931. }
  48932. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  48933. if (this._textures.length > 0) {
  48934. for (var i = 0; i < this._textures.length; i++) {
  48935. this._engine._releaseTexture(this._textures.data[i]);
  48936. }
  48937. this._textures.reset();
  48938. }
  48939. this.width = desiredWidth;
  48940. this.height = desiredHeight;
  48941. var textureSize = { width: this.width, height: this.height };
  48942. var textureOptions = {
  48943. generateMipMaps: false,
  48944. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  48945. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  48946. samplingMode: this.renderTargetSamplingMode,
  48947. type: this._textureType
  48948. };
  48949. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  48950. if (this._reusable) {
  48951. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  48952. }
  48953. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  48954. this.onSizeChangedObservable.notifyObservers(this);
  48955. }
  48956. this._textures.forEach(function (texture) {
  48957. if (texture.samples !== _this.samples) {
  48958. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  48959. }
  48960. });
  48961. }
  48962. var target;
  48963. if (this._shareOutputWithPostProcess) {
  48964. target = this._shareOutputWithPostProcess.outputTexture;
  48965. }
  48966. else if (this._forcedOutputTexture) {
  48967. target = this._forcedOutputTexture;
  48968. this.width = this._forcedOutputTexture.width;
  48969. this.height = this._forcedOutputTexture.height;
  48970. }
  48971. else {
  48972. target = this.outputTexture;
  48973. }
  48974. if (this.enablePixelPerfectMode) {
  48975. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  48976. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  48977. }
  48978. else {
  48979. this._scaleRatio.copyFromFloats(1, 1);
  48980. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  48981. }
  48982. this.onActivateObservable.notifyObservers(camera);
  48983. // Clear
  48984. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  48985. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  48986. }
  48987. if (this._reusable) {
  48988. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  48989. }
  48990. };
  48991. Object.defineProperty(PostProcess.prototype, "isSupported", {
  48992. get: function () {
  48993. return this._effect.isSupported;
  48994. },
  48995. enumerable: true,
  48996. configurable: true
  48997. });
  48998. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  48999. get: function () {
  49000. if (this._shareOutputWithPostProcess) {
  49001. return this._shareOutputWithPostProcess.aspectRatio;
  49002. }
  49003. if (this._forcedOutputTexture) {
  49004. var size = this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  49005. }
  49006. return this.width / this.height;
  49007. },
  49008. enumerable: true,
  49009. configurable: true
  49010. });
  49011. PostProcess.prototype.apply = function () {
  49012. // Check
  49013. if (!this._effect || !this._effect.isReady())
  49014. return null;
  49015. // States
  49016. this._engine.enableEffect(this._effect);
  49017. this._engine.setState(false);
  49018. this._engine.setDepthBuffer(false);
  49019. this._engine.setDepthWrite(false);
  49020. // Alpha
  49021. this._engine.setAlphaMode(this.alphaMode);
  49022. if (this.alphaConstants) {
  49023. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  49024. }
  49025. // Texture
  49026. var source;
  49027. if (this._shareOutputWithPostProcess) {
  49028. source = this._shareOutputWithPostProcess.outputTexture;
  49029. }
  49030. else if (this._forcedOutputTexture) {
  49031. source = this._forcedOutputTexture;
  49032. }
  49033. else {
  49034. source = this.outputTexture;
  49035. }
  49036. this._effect._bindTexture("textureSampler", source);
  49037. // Parameters
  49038. this._effect.setVector2("scale", this._scaleRatio);
  49039. this.onApplyObservable.notifyObservers(this._effect);
  49040. return this._effect;
  49041. };
  49042. PostProcess.prototype._disposeTextures = function () {
  49043. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  49044. return;
  49045. }
  49046. if (this._textures.length > 0) {
  49047. for (var i = 0; i < this._textures.length; i++) {
  49048. this._engine._releaseTexture(this._textures.data[i]);
  49049. }
  49050. }
  49051. this._textures.dispose();
  49052. };
  49053. PostProcess.prototype.dispose = function (camera) {
  49054. camera = camera || this._camera;
  49055. this._disposeTextures();
  49056. if (this._scene) {
  49057. var index_1 = this._scene.postProcesses.indexOf(this);
  49058. if (index_1 !== -1) {
  49059. this._scene.postProcesses.splice(index_1, 1);
  49060. }
  49061. }
  49062. else {
  49063. var index_2 = this._engine.postProcesses.indexOf(this);
  49064. if (index_2 !== -1) {
  49065. this._engine.postProcesses.splice(index_2, 1);
  49066. }
  49067. }
  49068. if (!camera) {
  49069. return;
  49070. }
  49071. camera.detachPostProcess(this);
  49072. var index = camera._postProcesses.indexOf(this);
  49073. if (index === 0 && camera._postProcesses.length > 0) {
  49074. this._camera._postProcesses[0].markTextureDirty();
  49075. }
  49076. this.onActivateObservable.clear();
  49077. this.onAfterRenderObservable.clear();
  49078. this.onApplyObservable.clear();
  49079. this.onBeforeRenderObservable.clear();
  49080. this.onSizeChangedObservable.clear();
  49081. };
  49082. return PostProcess;
  49083. }());
  49084. BABYLON.PostProcess = PostProcess;
  49085. })(BABYLON || (BABYLON = {}));
  49086. //# sourceMappingURL=babylon.postProcess.js.map
  49087. var BABYLON;
  49088. (function (BABYLON) {
  49089. var PassPostProcess = (function (_super) {
  49090. __extends(PassPostProcess, _super);
  49091. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  49092. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49093. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  49094. }
  49095. return PassPostProcess;
  49096. }(BABYLON.PostProcess));
  49097. BABYLON.PassPostProcess = PassPostProcess;
  49098. })(BABYLON || (BABYLON = {}));
  49099. //# sourceMappingURL=babylon.passPostProcess.js.map
  49100. var BABYLON;
  49101. (function (BABYLON) {
  49102. var ShadowGenerator = (function () {
  49103. /**
  49104. * Creates a ShadowGenerator object.
  49105. * A ShadowGenerator is the required tool to use the shadows.
  49106. * Each light casting shadows needs to use its own ShadowGenerator.
  49107. * Required parameters :
  49108. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  49109. * - `light`: the light object generating the shadows.
  49110. * - `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.
  49111. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  49112. */
  49113. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  49114. // Members
  49115. this._bias = 0.00005;
  49116. this._blurBoxOffset = 1;
  49117. this._blurScale = 2;
  49118. this._blurKernel = 1;
  49119. this._useKernelBlur = false;
  49120. this._filter = ShadowGenerator.FILTER_NONE;
  49121. this._darkness = 0;
  49122. this._transparencyShadow = false;
  49123. /**
  49124. * Controls the extent to which the shadows fade out at the edge of the frustum
  49125. * Used only by directionals and spots
  49126. */
  49127. this.frustumEdgeFalloff = 0;
  49128. this.forceBackFacesOnly = false;
  49129. this._lightDirection = BABYLON.Vector3.Zero();
  49130. this._viewMatrix = BABYLON.Matrix.Zero();
  49131. this._projectionMatrix = BABYLON.Matrix.Zero();
  49132. this._transformMatrix = BABYLON.Matrix.Zero();
  49133. this._worldViewProjection = BABYLON.Matrix.Zero();
  49134. this._currentFaceIndex = 0;
  49135. this._currentFaceIndexCache = 0;
  49136. this._isCube = false;
  49137. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  49138. this._mapSize = mapSize;
  49139. this._light = light;
  49140. this._scene = light.getScene();
  49141. light._shadowGenerator = this;
  49142. // Texture type fallback from float to int if not supported.
  49143. var caps = this._scene.getEngine().getCaps();
  49144. if (!useFullFloatFirst) {
  49145. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  49146. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  49147. }
  49148. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  49149. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  49150. }
  49151. else {
  49152. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  49153. }
  49154. }
  49155. else {
  49156. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  49157. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  49158. }
  49159. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  49160. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  49161. }
  49162. else {
  49163. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  49164. }
  49165. }
  49166. this._initializeGenerator();
  49167. }
  49168. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  49169. // Static
  49170. get: function () {
  49171. return ShadowGenerator._FILTER_NONE;
  49172. },
  49173. enumerable: true,
  49174. configurable: true
  49175. });
  49176. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  49177. get: function () {
  49178. return ShadowGenerator._FILTER_POISSONSAMPLING;
  49179. },
  49180. enumerable: true,
  49181. configurable: true
  49182. });
  49183. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  49184. get: function () {
  49185. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  49186. },
  49187. enumerable: true,
  49188. configurable: true
  49189. });
  49190. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  49191. get: function () {
  49192. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  49193. },
  49194. enumerable: true,
  49195. configurable: true
  49196. });
  49197. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  49198. get: function () {
  49199. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  49200. },
  49201. enumerable: true,
  49202. configurable: true
  49203. });
  49204. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  49205. get: function () {
  49206. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  49207. },
  49208. enumerable: true,
  49209. configurable: true
  49210. });
  49211. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  49212. get: function () {
  49213. return this._bias;
  49214. },
  49215. set: function (bias) {
  49216. this._bias = bias;
  49217. },
  49218. enumerable: true,
  49219. configurable: true
  49220. });
  49221. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  49222. get: function () {
  49223. return this._blurBoxOffset;
  49224. },
  49225. set: function (value) {
  49226. if (this._blurBoxOffset === value) {
  49227. return;
  49228. }
  49229. this._blurBoxOffset = value;
  49230. this._disposeBlurPostProcesses();
  49231. },
  49232. enumerable: true,
  49233. configurable: true
  49234. });
  49235. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  49236. get: function () {
  49237. return this._blurScale;
  49238. },
  49239. set: function (value) {
  49240. if (this._blurScale === value) {
  49241. return;
  49242. }
  49243. this._blurScale = value;
  49244. this._disposeBlurPostProcesses();
  49245. },
  49246. enumerable: true,
  49247. configurable: true
  49248. });
  49249. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  49250. get: function () {
  49251. return this._blurKernel;
  49252. },
  49253. set: function (value) {
  49254. if (this._blurKernel === value) {
  49255. return;
  49256. }
  49257. this._blurKernel = value;
  49258. this._disposeBlurPostProcesses();
  49259. },
  49260. enumerable: true,
  49261. configurable: true
  49262. });
  49263. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  49264. get: function () {
  49265. return this._useKernelBlur;
  49266. },
  49267. set: function (value) {
  49268. if (this._useKernelBlur === value) {
  49269. return;
  49270. }
  49271. this._useKernelBlur = value;
  49272. this._disposeBlurPostProcesses();
  49273. },
  49274. enumerable: true,
  49275. configurable: true
  49276. });
  49277. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  49278. get: function () {
  49279. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  49280. },
  49281. set: function (value) {
  49282. this._depthScale = value;
  49283. },
  49284. enumerable: true,
  49285. configurable: true
  49286. });
  49287. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  49288. get: function () {
  49289. return this._filter;
  49290. },
  49291. set: function (value) {
  49292. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  49293. if (this._light.needCube()) {
  49294. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  49295. this.useExponentialShadowMap = true;
  49296. return;
  49297. }
  49298. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  49299. this.useCloseExponentialShadowMap = true;
  49300. return;
  49301. }
  49302. }
  49303. if (this._filter === value) {
  49304. return;
  49305. }
  49306. this._filter = value;
  49307. this._disposeBlurPostProcesses();
  49308. this._applyFilterValues();
  49309. this._light._markMeshesAsLightDirty();
  49310. },
  49311. enumerable: true,
  49312. configurable: true
  49313. });
  49314. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  49315. get: function () {
  49316. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  49317. },
  49318. set: function (value) {
  49319. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  49320. return;
  49321. }
  49322. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  49323. },
  49324. enumerable: true,
  49325. configurable: true
  49326. });
  49327. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  49328. get: function () {
  49329. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  49330. return this.useExponentialShadowMap;
  49331. },
  49332. set: function (value) {
  49333. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  49334. this.useExponentialShadowMap = value;
  49335. },
  49336. enumerable: true,
  49337. configurable: true
  49338. });
  49339. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  49340. get: function () {
  49341. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  49342. return this.useBlurExponentialShadowMap;
  49343. },
  49344. set: function (value) {
  49345. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  49346. this.useBlurExponentialShadowMap = value;
  49347. },
  49348. enumerable: true,
  49349. configurable: true
  49350. });
  49351. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  49352. get: function () {
  49353. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  49354. },
  49355. set: function (value) {
  49356. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  49357. return;
  49358. }
  49359. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  49360. },
  49361. enumerable: true,
  49362. configurable: true
  49363. });
  49364. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  49365. get: function () {
  49366. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  49367. },
  49368. set: function (value) {
  49369. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  49370. return;
  49371. }
  49372. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  49373. },
  49374. enumerable: true,
  49375. configurable: true
  49376. });
  49377. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  49378. get: function () {
  49379. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  49380. },
  49381. set: function (value) {
  49382. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  49383. return;
  49384. }
  49385. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  49386. },
  49387. enumerable: true,
  49388. configurable: true
  49389. });
  49390. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  49391. get: function () {
  49392. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  49393. },
  49394. set: function (value) {
  49395. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  49396. return;
  49397. }
  49398. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  49399. },
  49400. enumerable: true,
  49401. configurable: true
  49402. });
  49403. /**
  49404. * Returns the darkness value (float).
  49405. */
  49406. ShadowGenerator.prototype.getDarkness = function () {
  49407. return this._darkness;
  49408. };
  49409. /**
  49410. * Sets the ShadowGenerator darkness value (float <= 1.0).
  49411. * Returns the ShadowGenerator.
  49412. */
  49413. ShadowGenerator.prototype.setDarkness = function (darkness) {
  49414. if (darkness >= 1.0)
  49415. this._darkness = 1.0;
  49416. else if (darkness <= 0.0)
  49417. this._darkness = 0.0;
  49418. else
  49419. this._darkness = darkness;
  49420. return this;
  49421. };
  49422. /**
  49423. * Sets the ability to have transparent shadow (boolean).
  49424. * Returns the ShadowGenerator.
  49425. */
  49426. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  49427. this._transparencyShadow = hasShadow;
  49428. return this;
  49429. };
  49430. /**
  49431. * Returns a RenderTargetTexture object : the shadow map texture.
  49432. */
  49433. ShadowGenerator.prototype.getShadowMap = function () {
  49434. return this._shadowMap;
  49435. };
  49436. /**
  49437. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  49438. */
  49439. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  49440. if (this._shadowMap2) {
  49441. return this._shadowMap2;
  49442. }
  49443. return this._shadowMap;
  49444. };
  49445. /**
  49446. * Helper function to add a mesh and its descendants to the list of shadow casters
  49447. * @param mesh Mesh to add
  49448. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  49449. */
  49450. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  49451. if (includeDescendants === void 0) { includeDescendants = true; }
  49452. this._shadowMap.renderList.push(mesh);
  49453. if (includeDescendants) {
  49454. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  49455. }
  49456. return this;
  49457. var _a;
  49458. };
  49459. /**
  49460. * Helper function to remove a mesh and its descendants from the list of shadow casters
  49461. * @param mesh Mesh to remove
  49462. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  49463. */
  49464. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  49465. if (includeDescendants === void 0) { includeDescendants = true; }
  49466. var index = this._shadowMap.renderList.indexOf(mesh);
  49467. if (index !== -1) {
  49468. this._shadowMap.renderList.splice(index, 1);
  49469. }
  49470. if (includeDescendants) {
  49471. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  49472. var child = _a[_i];
  49473. this.removeShadowCaster(child);
  49474. }
  49475. }
  49476. return this;
  49477. };
  49478. /**
  49479. * Returns the associated light object.
  49480. */
  49481. ShadowGenerator.prototype.getLight = function () {
  49482. return this._light;
  49483. };
  49484. ShadowGenerator.prototype._initializeGenerator = function () {
  49485. this._light._markMeshesAsLightDirty();
  49486. this._initializeShadowMap();
  49487. };
  49488. ShadowGenerator.prototype._initializeShadowMap = function () {
  49489. var _this = this;
  49490. // Render target
  49491. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  49492. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49493. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49494. this._shadowMap.anisotropicFilteringLevel = 1;
  49495. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  49496. this._shadowMap.renderParticles = false;
  49497. this._shadowMap.ignoreCameraViewport = true;
  49498. // Record Face Index before render.
  49499. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  49500. _this._currentFaceIndex = faceIndex;
  49501. });
  49502. // Custom render function.
  49503. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  49504. // Blur if required afer render.
  49505. this._shadowMap.onAfterUnbindObservable.add(function () {
  49506. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  49507. return;
  49508. }
  49509. if (!_this._blurPostProcesses) {
  49510. _this._initializeBlurRTTAndPostProcesses();
  49511. }
  49512. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture(), true);
  49513. });
  49514. // Clear according to the chosen filter.
  49515. this._shadowMap.onClearObservable.add(function (engine) {
  49516. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  49517. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  49518. }
  49519. else {
  49520. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  49521. }
  49522. });
  49523. };
  49524. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  49525. var _this = this;
  49526. var engine = this._scene.getEngine();
  49527. var targetSize = this._mapSize / this.blurScale;
  49528. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  49529. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  49530. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49531. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49532. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  49533. }
  49534. if (this.useKernelBlur) {
  49535. 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);
  49536. this._kernelBlurXPostprocess.width = targetSize;
  49537. this._kernelBlurXPostprocess.height = targetSize;
  49538. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  49539. effect.setTexture("textureSampler", _this._shadowMap);
  49540. });
  49541. 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);
  49542. this._kernelBlurXPostprocess.autoClear = false;
  49543. this._kernelBlurYPostprocess.autoClear = false;
  49544. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  49545. this._kernelBlurXPostprocess.packedFloat = true;
  49546. this._kernelBlurYPostprocess.packedFloat = true;
  49547. }
  49548. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  49549. }
  49550. else {
  49551. 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);
  49552. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  49553. effect.setFloat2("screenSize", targetSize, targetSize);
  49554. effect.setTexture("textureSampler", _this._shadowMap);
  49555. });
  49556. this._boxBlurPostprocess.autoClear = false;
  49557. this._blurPostProcesses = [this._boxBlurPostprocess];
  49558. }
  49559. };
  49560. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  49561. var index;
  49562. var engine = this._scene.getEngine();
  49563. if (depthOnlySubMeshes.length) {
  49564. engine.setColorWrite(false);
  49565. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  49566. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  49567. }
  49568. engine.setColorWrite(true);
  49569. }
  49570. for (index = 0; index < opaqueSubMeshes.length; index++) {
  49571. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  49572. }
  49573. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  49574. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  49575. }
  49576. if (this._transparencyShadow) {
  49577. for (index = 0; index < transparentSubMeshes.length; index++) {
  49578. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  49579. }
  49580. }
  49581. };
  49582. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  49583. var _this = this;
  49584. var mesh = subMesh.getRenderingMesh();
  49585. var scene = this._scene;
  49586. var engine = scene.getEngine();
  49587. // Culling
  49588. engine.setState(subMesh.getMaterial().backFaceCulling);
  49589. // Managing instances
  49590. var batch = mesh._getInstancesRenderList(subMesh._id);
  49591. if (batch.mustReturn) {
  49592. return;
  49593. }
  49594. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  49595. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  49596. engine.enableEffect(this._effect);
  49597. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  49598. var material = subMesh.getMaterial();
  49599. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  49600. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  49601. this._effect.setVector3("lightPosition", this.getLight().position);
  49602. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  49603. // Alpha test
  49604. if (material && material.needAlphaTesting()) {
  49605. var alphaTexture = material.getAlphaTestTexture();
  49606. if (alphaTexture) {
  49607. this._effect.setTexture("diffuseSampler", alphaTexture);
  49608. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  49609. }
  49610. }
  49611. // Bones
  49612. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  49613. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  49614. }
  49615. if (this.forceBackFacesOnly) {
  49616. engine.setState(true, 0, false, true);
  49617. }
  49618. // Draw
  49619. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  49620. if (this.forceBackFacesOnly) {
  49621. engine.setState(true, 0, false, false);
  49622. }
  49623. }
  49624. else {
  49625. // Need to reset refresh rate of the shadowMap
  49626. this._shadowMap.resetRefreshCounter();
  49627. }
  49628. };
  49629. ShadowGenerator.prototype._applyFilterValues = function () {
  49630. if (this.filter === ShadowGenerator.FILTER_NONE) {
  49631. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  49632. }
  49633. else {
  49634. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  49635. }
  49636. };
  49637. /**
  49638. * Force shader compilation including textures ready check
  49639. */
  49640. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  49641. var _this = this;
  49642. var scene = this._scene;
  49643. var engine = scene.getEngine();
  49644. var subMeshes = new Array();
  49645. var currentIndex = 0;
  49646. for (var _i = 0, _a = this.getShadowMap().renderList; _i < _a.length; _i++) {
  49647. var mesh = _a[_i];
  49648. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  49649. }
  49650. var checkReady = function () {
  49651. if (!_this._scene || !_this._scene.getEngine()) {
  49652. return;
  49653. }
  49654. var subMesh = subMeshes[currentIndex];
  49655. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  49656. currentIndex++;
  49657. if (currentIndex >= subMeshes.length) {
  49658. if (onCompiled) {
  49659. onCompiled(_this);
  49660. }
  49661. return;
  49662. }
  49663. }
  49664. setTimeout(checkReady, 16);
  49665. };
  49666. if (subMeshes.length > 0) {
  49667. checkReady();
  49668. }
  49669. };
  49670. /**
  49671. * Boolean : true when the ShadowGenerator is finally computed.
  49672. */
  49673. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  49674. var defines = [];
  49675. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  49676. defines.push("#define FLOAT");
  49677. }
  49678. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  49679. defines.push("#define ESM");
  49680. }
  49681. var attribs = [BABYLON.VertexBuffer.PositionKind];
  49682. var mesh = subMesh.getMesh();
  49683. var material = subMesh.getMaterial();
  49684. // Alpha test
  49685. if (material && material.needAlphaTesting()) {
  49686. var alphaTexture = material.getAlphaTestTexture();
  49687. if (alphaTexture) {
  49688. defines.push("#define ALPHATEST");
  49689. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49690. attribs.push(BABYLON.VertexBuffer.UVKind);
  49691. defines.push("#define UV1");
  49692. }
  49693. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  49694. if (alphaTexture.coordinatesIndex === 1) {
  49695. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  49696. defines.push("#define UV2");
  49697. }
  49698. }
  49699. }
  49700. }
  49701. // Bones
  49702. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  49703. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  49704. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  49705. if (mesh.numBoneInfluencers > 4) {
  49706. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  49707. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  49708. }
  49709. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  49710. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  49711. }
  49712. else {
  49713. defines.push("#define NUM_BONE_INFLUENCERS 0");
  49714. }
  49715. // Instances
  49716. if (useInstances) {
  49717. defines.push("#define INSTANCES");
  49718. attribs.push("world0");
  49719. attribs.push("world1");
  49720. attribs.push("world2");
  49721. attribs.push("world3");
  49722. }
  49723. // Get correct effect
  49724. var join = defines.join("\n");
  49725. if (this._cachedDefines !== join) {
  49726. this._cachedDefines = join;
  49727. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  49728. }
  49729. return this._effect.isReady();
  49730. };
  49731. /**
  49732. * This creates the defines related to the standard BJS materials.
  49733. */
  49734. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  49735. var scene = this._scene;
  49736. var light = this._light;
  49737. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  49738. return;
  49739. }
  49740. defines["SHADOW" + lightIndex] = true;
  49741. if (this.usePoissonSampling) {
  49742. defines["SHADOWPCF" + lightIndex] = true;
  49743. }
  49744. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  49745. defines["SHADOWESM" + lightIndex] = true;
  49746. }
  49747. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  49748. defines["SHADOWCLOSEESM" + lightIndex] = true;
  49749. }
  49750. if (light.needCube()) {
  49751. defines["SHADOWCUBE" + lightIndex] = true;
  49752. }
  49753. };
  49754. /**
  49755. * This binds shadow lights related to the standard BJS materials.
  49756. * It implies the unifroms available on the materials are the standard BJS ones.
  49757. */
  49758. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  49759. var light = this._light;
  49760. var scene = this._scene;
  49761. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  49762. return;
  49763. }
  49764. if (!light.needCube()) {
  49765. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  49766. }
  49767. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  49768. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  49769. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  49770. };
  49771. // Methods
  49772. /**
  49773. * Returns a Matrix object : the updated transformation matrix.
  49774. */
  49775. ShadowGenerator.prototype.getTransformMatrix = function () {
  49776. var scene = this._scene;
  49777. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  49778. return this._transformMatrix;
  49779. }
  49780. this._currentRenderID = scene.getRenderId();
  49781. this._currentFaceIndexCache = this._currentFaceIndex;
  49782. var lightPosition = this._light.position;
  49783. if (this._light.computeTransformedInformation()) {
  49784. lightPosition = this._light.transformedPosition;
  49785. }
  49786. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  49787. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  49788. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  49789. }
  49790. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  49791. this._cachedPosition = lightPosition.clone();
  49792. this._cachedDirection = this._lightDirection.clone();
  49793. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  49794. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  49795. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  49796. }
  49797. return this._transformMatrix;
  49798. };
  49799. ShadowGenerator.prototype.recreateShadowMap = function () {
  49800. // Track render list.
  49801. var renderList = this._shadowMap.renderList;
  49802. // Clean up existing data.
  49803. this._disposeRTTandPostProcesses();
  49804. // Reinitializes.
  49805. this._initializeGenerator();
  49806. // Reaffect the filter to ensure a correct fallback if necessary.
  49807. this.filter = this.filter;
  49808. // Reaffect the filter.
  49809. this._applyFilterValues();
  49810. // Reaffect Render List.
  49811. this._shadowMap.renderList = renderList;
  49812. };
  49813. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  49814. if (this._shadowMap2) {
  49815. this._shadowMap2.dispose();
  49816. this._shadowMap2 = null;
  49817. }
  49818. if (this._downSamplePostprocess) {
  49819. this._downSamplePostprocess.dispose();
  49820. this._downSamplePostprocess = null;
  49821. }
  49822. if (this._boxBlurPostprocess) {
  49823. this._boxBlurPostprocess.dispose();
  49824. this._boxBlurPostprocess = null;
  49825. }
  49826. if (this._kernelBlurXPostprocess) {
  49827. this._kernelBlurXPostprocess.dispose();
  49828. this._kernelBlurXPostprocess = null;
  49829. }
  49830. if (this._kernelBlurYPostprocess) {
  49831. this._kernelBlurYPostprocess.dispose();
  49832. this._kernelBlurYPostprocess = null;
  49833. }
  49834. this._blurPostProcesses = null;
  49835. };
  49836. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  49837. if (this._shadowMap) {
  49838. this._shadowMap.dispose();
  49839. this._shadowMap = null;
  49840. }
  49841. this._disposeBlurPostProcesses();
  49842. };
  49843. /**
  49844. * Disposes the ShadowGenerator.
  49845. * Returns nothing.
  49846. */
  49847. ShadowGenerator.prototype.dispose = function () {
  49848. this._disposeRTTandPostProcesses();
  49849. this._light._shadowGenerator = null;
  49850. this._light._markMeshesAsLightDirty();
  49851. };
  49852. /**
  49853. * Serializes the ShadowGenerator and returns a serializationObject.
  49854. */
  49855. ShadowGenerator.prototype.serialize = function () {
  49856. var serializationObject = {};
  49857. var shadowMap = this.getShadowMap();
  49858. serializationObject.lightId = this._light.id;
  49859. serializationObject.mapSize = shadowMap.getRenderSize();
  49860. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  49861. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  49862. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  49863. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  49864. serializationObject.usePoissonSampling = this.usePoissonSampling;
  49865. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  49866. serializationObject.depthScale = this.depthScale;
  49867. serializationObject.darkness = this.getDarkness();
  49868. serializationObject.blurBoxOffset = this.blurBoxOffset;
  49869. serializationObject.blurKernel = this.blurKernel;
  49870. serializationObject.blurScale = this.blurScale;
  49871. serializationObject.useKernelBlur = this.useKernelBlur;
  49872. serializationObject.transparencyShadow = this._transparencyShadow;
  49873. serializationObject.renderList = [];
  49874. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  49875. var mesh = shadowMap.renderList[meshIndex];
  49876. serializationObject.renderList.push(mesh.id);
  49877. }
  49878. return serializationObject;
  49879. };
  49880. /**
  49881. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  49882. */
  49883. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  49884. //casting to point light, as light is missing the position attr and typescript complains.
  49885. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  49886. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  49887. var shadowMap = shadowGenerator.getShadowMap();
  49888. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  49889. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  49890. meshes.forEach(function (mesh) {
  49891. shadowMap.renderList.push(mesh);
  49892. });
  49893. }
  49894. if (parsedShadowGenerator.usePoissonSampling) {
  49895. shadowGenerator.usePoissonSampling = true;
  49896. }
  49897. else if (parsedShadowGenerator.useExponentialShadowMap) {
  49898. shadowGenerator.useExponentialShadowMap = true;
  49899. }
  49900. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  49901. shadowGenerator.useBlurExponentialShadowMap = true;
  49902. }
  49903. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  49904. shadowGenerator.useCloseExponentialShadowMap = true;
  49905. }
  49906. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  49907. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  49908. }
  49909. else if (parsedShadowGenerator.useVarianceShadowMap) {
  49910. shadowGenerator.useExponentialShadowMap = true;
  49911. }
  49912. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  49913. shadowGenerator.useBlurExponentialShadowMap = true;
  49914. }
  49915. if (parsedShadowGenerator.depthScale) {
  49916. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  49917. }
  49918. if (parsedShadowGenerator.blurScale) {
  49919. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  49920. }
  49921. if (parsedShadowGenerator.blurBoxOffset) {
  49922. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  49923. }
  49924. if (parsedShadowGenerator.useKernelBlur) {
  49925. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  49926. }
  49927. if (parsedShadowGenerator.blurKernel) {
  49928. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  49929. }
  49930. if (parsedShadowGenerator.bias !== undefined) {
  49931. shadowGenerator.bias = parsedShadowGenerator.bias;
  49932. }
  49933. if (parsedShadowGenerator.darkness) {
  49934. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  49935. }
  49936. if (parsedShadowGenerator.transparencyShadow) {
  49937. shadowGenerator.setTransparencyShadow(true);
  49938. }
  49939. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  49940. return shadowGenerator;
  49941. };
  49942. ShadowGenerator._FILTER_NONE = 0;
  49943. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  49944. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  49945. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  49946. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  49947. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  49948. return ShadowGenerator;
  49949. }());
  49950. BABYLON.ShadowGenerator = ShadowGenerator;
  49951. })(BABYLON || (BABYLON = {}));
  49952. //# sourceMappingURL=babylon.shadowGenerator.js.map
  49953. var BABYLON;
  49954. (function (BABYLON) {
  49955. var DefaultLoadingScreen = (function () {
  49956. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  49957. if (_loadingText === void 0) { _loadingText = ""; }
  49958. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  49959. var _this = this;
  49960. this._renderingCanvas = _renderingCanvas;
  49961. this._loadingText = _loadingText;
  49962. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  49963. // Resize
  49964. this._resizeLoadingUI = function () {
  49965. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  49966. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  49967. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  49968. _this._loadingDiv.style.left = canvasRect.left + "px";
  49969. _this._loadingDiv.style.top = canvasRect.top + "px";
  49970. _this._loadingDiv.style.width = canvasRect.width + "px";
  49971. _this._loadingDiv.style.height = canvasRect.height + "px";
  49972. };
  49973. }
  49974. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  49975. if (this._loadingDiv) {
  49976. // Do not add a loading screen if there is already one
  49977. return;
  49978. }
  49979. this._loadingDiv = document.createElement("div");
  49980. this._loadingDiv.id = "babylonjsLoadingDiv";
  49981. this._loadingDiv.style.opacity = "0";
  49982. this._loadingDiv.style.transition = "opacity 1.5s ease";
  49983. this._loadingDiv.style.pointerEvents = "none";
  49984. // Loading text
  49985. this._loadingTextDiv = document.createElement("div");
  49986. this._loadingTextDiv.style.position = "absolute";
  49987. this._loadingTextDiv.style.left = "0";
  49988. this._loadingTextDiv.style.top = "50%";
  49989. this._loadingTextDiv.style.marginTop = "80px";
  49990. this._loadingTextDiv.style.width = "100%";
  49991. this._loadingTextDiv.style.height = "20px";
  49992. this._loadingTextDiv.style.fontFamily = "Arial";
  49993. this._loadingTextDiv.style.fontSize = "14px";
  49994. this._loadingTextDiv.style.color = "white";
  49995. this._loadingTextDiv.style.textAlign = "center";
  49996. this._loadingTextDiv.innerHTML = "Loading";
  49997. this._loadingDiv.appendChild(this._loadingTextDiv);
  49998. //set the predefined text
  49999. this._loadingTextDiv.innerHTML = this._loadingText;
  50000. // Generating keyframes
  50001. var style = document.createElement('style');
  50002. style.type = 'text/css';
  50003. 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 }";
  50004. style.innerHTML = keyFrames;
  50005. document.getElementsByTagName('head')[0].appendChild(style);
  50006. // Loading img
  50007. var imgBack = new Image();
  50008. 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";
  50009. imgBack.style.position = "absolute";
  50010. imgBack.style.left = "50%";
  50011. imgBack.style.top = "50%";
  50012. imgBack.style.marginLeft = "-60px";
  50013. imgBack.style.marginTop = "-60px";
  50014. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  50015. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  50016. imgBack.style.transformOrigin = "50% 50%";
  50017. imgBack.style.webkitTransformOrigin = "50% 50%";
  50018. this._loadingDiv.appendChild(imgBack);
  50019. this._resizeLoadingUI();
  50020. window.addEventListener("resize", this._resizeLoadingUI);
  50021. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  50022. document.body.appendChild(this._loadingDiv);
  50023. this._loadingDiv.style.opacity = "1";
  50024. };
  50025. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  50026. var _this = this;
  50027. if (!this._loadingDiv) {
  50028. return;
  50029. }
  50030. var onTransitionEnd = function () {
  50031. if (!_this._loadingDiv) {
  50032. return;
  50033. }
  50034. document.body.removeChild(_this._loadingDiv);
  50035. window.removeEventListener("resize", _this._resizeLoadingUI);
  50036. _this._loadingDiv = null;
  50037. };
  50038. this._loadingDiv.style.opacity = "0";
  50039. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  50040. };
  50041. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  50042. set: function (text) {
  50043. this._loadingText = text;
  50044. if (this._loadingTextDiv) {
  50045. this._loadingTextDiv.innerHTML = this._loadingText;
  50046. }
  50047. },
  50048. enumerable: true,
  50049. configurable: true
  50050. });
  50051. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  50052. get: function () {
  50053. return this._loadingDivBackgroundColor;
  50054. },
  50055. set: function (color) {
  50056. this._loadingDivBackgroundColor = color;
  50057. if (!this._loadingDiv) {
  50058. return;
  50059. }
  50060. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  50061. },
  50062. enumerable: true,
  50063. configurable: true
  50064. });
  50065. return DefaultLoadingScreen;
  50066. }());
  50067. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  50068. })(BABYLON || (BABYLON = {}));
  50069. //# sourceMappingURL=babylon.loadingScreen.js.map
  50070. var BABYLON;
  50071. (function (BABYLON) {
  50072. var SceneLoader = (function () {
  50073. function SceneLoader() {
  50074. }
  50075. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  50076. get: function () {
  50077. return 0;
  50078. },
  50079. enumerable: true,
  50080. configurable: true
  50081. });
  50082. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  50083. get: function () {
  50084. return 1;
  50085. },
  50086. enumerable: true,
  50087. configurable: true
  50088. });
  50089. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  50090. get: function () {
  50091. return 2;
  50092. },
  50093. enumerable: true,
  50094. configurable: true
  50095. });
  50096. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  50097. get: function () {
  50098. return 3;
  50099. },
  50100. enumerable: true,
  50101. configurable: true
  50102. });
  50103. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  50104. get: function () {
  50105. return SceneLoader._ForceFullSceneLoadingForIncremental;
  50106. },
  50107. set: function (value) {
  50108. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  50109. },
  50110. enumerable: true,
  50111. configurable: true
  50112. });
  50113. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  50114. get: function () {
  50115. return SceneLoader._ShowLoadingScreen;
  50116. },
  50117. set: function (value) {
  50118. SceneLoader._ShowLoadingScreen = value;
  50119. },
  50120. enumerable: true,
  50121. configurable: true
  50122. });
  50123. Object.defineProperty(SceneLoader, "loggingLevel", {
  50124. get: function () {
  50125. return SceneLoader._loggingLevel;
  50126. },
  50127. set: function (value) {
  50128. SceneLoader._loggingLevel = value;
  50129. },
  50130. enumerable: true,
  50131. configurable: true
  50132. });
  50133. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  50134. get: function () {
  50135. return SceneLoader._CleanBoneMatrixWeights;
  50136. },
  50137. set: function (value) {
  50138. SceneLoader._CleanBoneMatrixWeights = value;
  50139. },
  50140. enumerable: true,
  50141. configurable: true
  50142. });
  50143. SceneLoader._getDefaultPlugin = function () {
  50144. return SceneLoader._registeredPlugins[".babylon"];
  50145. };
  50146. SceneLoader._getPluginForExtension = function (extension) {
  50147. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  50148. if (registeredPlugin) {
  50149. return registeredPlugin;
  50150. }
  50151. return SceneLoader._getDefaultPlugin();
  50152. };
  50153. SceneLoader._getPluginForDirectLoad = function (data) {
  50154. for (var extension in SceneLoader._registeredPlugins) {
  50155. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  50156. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  50157. return SceneLoader._registeredPlugins[extension];
  50158. }
  50159. }
  50160. return SceneLoader._getDefaultPlugin();
  50161. };
  50162. SceneLoader._getPluginForFilename = function (sceneFilename) {
  50163. if (sceneFilename.name) {
  50164. sceneFilename = sceneFilename.name;
  50165. }
  50166. var dotPosition = sceneFilename.lastIndexOf(".");
  50167. var queryStringPosition = sceneFilename.indexOf("?");
  50168. if (queryStringPosition === -1) {
  50169. queryStringPosition = sceneFilename.length;
  50170. }
  50171. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  50172. return SceneLoader._getPluginForExtension(extension);
  50173. };
  50174. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  50175. SceneLoader._getDirectLoad = function (sceneFilename) {
  50176. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  50177. return sceneFilename.substr(5);
  50178. }
  50179. return null;
  50180. };
  50181. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  50182. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  50183. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  50184. var plugin = registeredPlugin.plugin;
  50185. var useArrayBuffer = registeredPlugin.isBinary;
  50186. var database;
  50187. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  50188. var dataCallback = function (data) {
  50189. if (scene.isDisposed) {
  50190. onError("Scene has been disposed");
  50191. return;
  50192. }
  50193. scene.database = database;
  50194. try {
  50195. onSuccess(plugin, data);
  50196. }
  50197. catch (e) {
  50198. onError(null, e);
  50199. }
  50200. };
  50201. var manifestChecked = function (success) {
  50202. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  50203. onError(request.status + " " + request.statusText);
  50204. });
  50205. };
  50206. if (directLoad) {
  50207. dataCallback(directLoad);
  50208. return;
  50209. }
  50210. if (rootUrl.indexOf("file:") === -1) {
  50211. if (scene.getEngine().enableOfflineSupport) {
  50212. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  50213. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  50214. }
  50215. else {
  50216. manifestChecked(true);
  50217. }
  50218. }
  50219. else {
  50220. var fileOrString = sceneFilename;
  50221. if (fileOrString.name) {
  50222. BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  50223. }
  50224. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  50225. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  50226. }
  50227. else {
  50228. onError("Unable to find file named " + sceneFilename);
  50229. return;
  50230. }
  50231. }
  50232. };
  50233. // Public functions
  50234. SceneLoader.GetPluginForExtension = function (extension) {
  50235. return SceneLoader._getPluginForExtension(extension).plugin;
  50236. };
  50237. SceneLoader.RegisterPlugin = function (plugin) {
  50238. if (typeof plugin.extensions === "string") {
  50239. var extension = plugin.extensions;
  50240. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  50241. plugin: plugin,
  50242. isBinary: false
  50243. };
  50244. }
  50245. else {
  50246. var extensions = plugin.extensions;
  50247. Object.keys(extensions).forEach(function (extension) {
  50248. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  50249. plugin: plugin,
  50250. isBinary: extensions[extension].isBinary
  50251. };
  50252. });
  50253. }
  50254. };
  50255. /**
  50256. * Import meshes into a scene
  50257. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  50258. * @param rootUrl a string that defines the root url for scene and resources
  50259. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  50260. * @param scene the instance of BABYLON.Scene to append to
  50261. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  50262. * @param onProgress a callback with a progress event for each file being loaded
  50263. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  50264. */
  50265. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  50266. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  50267. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  50268. return;
  50269. }
  50270. var loadingToken = {};
  50271. scene._addPendingData(loadingToken);
  50272. var errorHandler = function (message, exception) {
  50273. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  50274. if (onError) {
  50275. onError(scene, errorMessage, exception);
  50276. }
  50277. else {
  50278. BABYLON.Tools.Error(errorMessage);
  50279. // should the exception be thrown?
  50280. }
  50281. scene._removePendingData(loadingToken);
  50282. };
  50283. var progressHandler = function (event) {
  50284. if (onProgress) {
  50285. onProgress(event);
  50286. }
  50287. };
  50288. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  50289. if (plugin.importMesh) {
  50290. var syncedPlugin = plugin;
  50291. var meshes = new Array();
  50292. var particleSystems = new Array();
  50293. var skeletons = new Array();
  50294. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  50295. return;
  50296. }
  50297. if (onSuccess) {
  50298. // wrap onSuccess with try-catch to know if something went wrong.
  50299. try {
  50300. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  50301. onSuccess(meshes, particleSystems, skeletons);
  50302. scene._removePendingData(loadingToken);
  50303. }
  50304. catch (e) {
  50305. var message = 'Error in onSuccess callback.';
  50306. errorHandler(message, e);
  50307. }
  50308. }
  50309. }
  50310. else {
  50311. var asyncedPlugin = plugin;
  50312. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  50313. if (onSuccess) {
  50314. try {
  50315. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  50316. onSuccess(meshes, particleSystems, skeletons);
  50317. scene._removePendingData(loadingToken);
  50318. }
  50319. catch (e) {
  50320. var message = 'Error in onSuccess callback.';
  50321. errorHandler(message, e);
  50322. }
  50323. }
  50324. }, progressHandler, errorHandler);
  50325. }
  50326. }, progressHandler, errorHandler);
  50327. };
  50328. /**
  50329. * Load a scene
  50330. * @param rootUrl a string that defines the root url for scene and resources
  50331. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  50332. * @param engine is the instance of BABYLON.Engine to use to create the scene
  50333. * @param onSuccess a callback with the scene when import succeeds
  50334. * @param onProgress a callback with a progress event for each file being loaded
  50335. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  50336. */
  50337. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  50338. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  50339. };
  50340. /**
  50341. * Append a scene
  50342. * @param rootUrl a string that defines the root url for scene and resources
  50343. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  50344. * @param scene is the instance of BABYLON.Scene to append to
  50345. * @param onSuccess a callback with the scene when import succeeds
  50346. * @param onProgress a callback with a progress event for each file being loaded
  50347. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  50348. */
  50349. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  50350. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  50351. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  50352. return;
  50353. }
  50354. if (SceneLoader.ShowLoadingScreen) {
  50355. scene.getEngine().displayLoadingUI();
  50356. }
  50357. var loadingToken = {};
  50358. scene._addPendingData(loadingToken);
  50359. var errorHandler = function (message, exception) {
  50360. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  50361. if (onError) {
  50362. onError(scene, errorMessage, exception);
  50363. }
  50364. else {
  50365. BABYLON.Tools.Error(errorMessage);
  50366. // should the exception be thrown?
  50367. }
  50368. scene._removePendingData(loadingToken);
  50369. scene.getEngine().hideLoadingUI();
  50370. };
  50371. var progressHandler = function (event) {
  50372. if (onProgress) {
  50373. onProgress(event);
  50374. }
  50375. };
  50376. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  50377. if (plugin.load) {
  50378. var syncedPlugin = plugin;
  50379. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  50380. return;
  50381. }
  50382. if (onSuccess) {
  50383. try {
  50384. onSuccess(scene);
  50385. }
  50386. catch (e) {
  50387. errorHandler("Error in onSuccess callback", e);
  50388. }
  50389. }
  50390. scene.loadingPluginName = plugin.name;
  50391. scene._removePendingData(loadingToken);
  50392. }
  50393. else {
  50394. var asyncedPlugin = plugin;
  50395. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  50396. if (onSuccess) {
  50397. onSuccess(scene);
  50398. }
  50399. scene.loadingPluginName = plugin.name;
  50400. scene._removePendingData(loadingToken);
  50401. }, progressHandler, errorHandler);
  50402. }
  50403. if (SceneLoader.ShowLoadingScreen) {
  50404. scene.executeWhenReady(function () {
  50405. scene.getEngine().hideLoadingUI();
  50406. });
  50407. }
  50408. }, progressHandler, errorHandler);
  50409. };
  50410. // Flags
  50411. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  50412. SceneLoader._ShowLoadingScreen = true;
  50413. SceneLoader._CleanBoneMatrixWeights = false;
  50414. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  50415. // Members
  50416. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  50417. SceneLoader._registeredPlugins = {};
  50418. return SceneLoader;
  50419. }());
  50420. BABYLON.SceneLoader = SceneLoader;
  50421. ;
  50422. })(BABYLON || (BABYLON = {}));
  50423. //# sourceMappingURL=babylon.sceneLoader.js.map
  50424. var BABYLON;
  50425. (function (BABYLON) {
  50426. var Internals;
  50427. (function (Internals) {
  50428. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  50429. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  50430. var parsedMaterial = parsedData.materials[index];
  50431. if (parsedMaterial.id === id) {
  50432. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  50433. }
  50434. }
  50435. return null;
  50436. };
  50437. var isDescendantOf = function (mesh, names, hierarchyIds) {
  50438. for (var i in names) {
  50439. if (mesh.name === names[i]) {
  50440. hierarchyIds.push(mesh.id);
  50441. return true;
  50442. }
  50443. }
  50444. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  50445. hierarchyIds.push(mesh.id);
  50446. return true;
  50447. }
  50448. return false;
  50449. };
  50450. var logOperation = function (operation, producer) {
  50451. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  50452. };
  50453. BABYLON.SceneLoader.RegisterPlugin({
  50454. name: "babylon.js",
  50455. extensions: ".babylon",
  50456. canDirectLoad: function (data) {
  50457. if (data.indexOf("babylon") !== -1) {
  50458. return true;
  50459. }
  50460. return false;
  50461. },
  50462. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  50463. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  50464. // when SceneLoader.debugLogging = true (default), or exception encountered.
  50465. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  50466. // and avoid problems with multiple concurrent .babylon loads.
  50467. var log = "importMesh has failed JSON parse";
  50468. try {
  50469. var parsedData = JSON.parse(data);
  50470. log = "";
  50471. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  50472. if (!meshesNames) {
  50473. meshesNames = null;
  50474. }
  50475. else if (!Array.isArray(meshesNames)) {
  50476. meshesNames = [meshesNames];
  50477. }
  50478. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  50479. var loadedSkeletonsIds = [];
  50480. var loadedMaterialsIds = [];
  50481. var hierarchyIds = new Array();
  50482. var index;
  50483. var cache;
  50484. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  50485. var parsedMesh = parsedData.meshes[index];
  50486. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  50487. if (meshesNames !== null) {
  50488. // Remove found mesh name from list.
  50489. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  50490. }
  50491. //Geometry?
  50492. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  50493. //does the file contain geometries?
  50494. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  50495. //find the correct geometry and add it to the scene
  50496. var found = false;
  50497. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  50498. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  50499. return;
  50500. }
  50501. else {
  50502. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  50503. if (parsedGeometryData.id === parsedMesh.geometryId) {
  50504. switch (geometryType) {
  50505. case "boxes":
  50506. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  50507. break;
  50508. case "spheres":
  50509. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  50510. break;
  50511. case "cylinders":
  50512. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  50513. break;
  50514. case "toruses":
  50515. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  50516. break;
  50517. case "grounds":
  50518. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  50519. break;
  50520. case "planes":
  50521. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  50522. break;
  50523. case "torusKnots":
  50524. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  50525. break;
  50526. case "vertexData":
  50527. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  50528. break;
  50529. }
  50530. found = true;
  50531. }
  50532. });
  50533. }
  50534. });
  50535. if (found === false) {
  50536. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  50537. }
  50538. }
  50539. }
  50540. // Material ?
  50541. if (parsedMesh.materialId) {
  50542. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  50543. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  50544. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  50545. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  50546. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  50547. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  50548. var subMatId = parsedMultiMaterial.materials[matIndex];
  50549. loadedMaterialsIds.push(subMatId);
  50550. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  50551. log += "\n\tMaterial " + mat.toString(fullDetails);
  50552. }
  50553. loadedMaterialsIds.push(parsedMultiMaterial.id);
  50554. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  50555. materialFound = true;
  50556. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  50557. break;
  50558. }
  50559. }
  50560. }
  50561. if (materialFound === false) {
  50562. loadedMaterialsIds.push(parsedMesh.materialId);
  50563. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  50564. if (!mat) {
  50565. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  50566. }
  50567. else {
  50568. log += "\n\tMaterial " + mat.toString(fullDetails);
  50569. }
  50570. }
  50571. }
  50572. // Skeleton ?
  50573. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  50574. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  50575. if (skeletonAlreadyLoaded === false) {
  50576. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  50577. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  50578. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  50579. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  50580. skeletons.push(skeleton);
  50581. loadedSkeletonsIds.push(parsedSkeleton.id);
  50582. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  50583. }
  50584. }
  50585. }
  50586. }
  50587. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  50588. meshes.push(mesh);
  50589. log += "\n\tMesh " + mesh.toString(fullDetails);
  50590. }
  50591. }
  50592. // Connecting parents
  50593. var currentMesh;
  50594. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  50595. currentMesh = scene.meshes[index];
  50596. if (currentMesh._waitingParentId) {
  50597. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  50598. currentMesh._waitingParentId = undefined;
  50599. }
  50600. }
  50601. // freeze and compute world matrix application
  50602. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  50603. currentMesh = scene.meshes[index];
  50604. if (currentMesh._waitingFreezeWorldMatrix) {
  50605. currentMesh.freezeWorldMatrix();
  50606. currentMesh._waitingFreezeWorldMatrix = undefined;
  50607. }
  50608. else {
  50609. currentMesh.computeWorldMatrix(true);
  50610. }
  50611. }
  50612. }
  50613. // Particles
  50614. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  50615. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  50616. var parsedParticleSystem = parsedData.particleSystems[index];
  50617. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  50618. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  50619. }
  50620. }
  50621. }
  50622. return true;
  50623. }
  50624. catch (err) {
  50625. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  50626. if (onError) {
  50627. onError(msg, err);
  50628. }
  50629. else {
  50630. BABYLON.Tools.Log(msg);
  50631. log = null;
  50632. throw err;
  50633. }
  50634. }
  50635. finally {
  50636. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  50637. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  50638. }
  50639. }
  50640. },
  50641. load: function (scene, data, rootUrl, onError) {
  50642. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  50643. // when SceneLoader.debugLogging = true (default), or exception encountered.
  50644. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  50645. // and avoid problems with multiple concurrent .babylon loads.
  50646. var log = "importScene has failed JSON parse";
  50647. try {
  50648. var parsedData = JSON.parse(data);
  50649. log = "";
  50650. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  50651. // Scene
  50652. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  50653. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  50654. }
  50655. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  50656. scene.autoClear = parsedData.autoClear;
  50657. }
  50658. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  50659. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  50660. }
  50661. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  50662. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  50663. }
  50664. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  50665. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  50666. }
  50667. // Fog
  50668. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  50669. scene.fogMode = parsedData.fogMode;
  50670. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  50671. scene.fogStart = parsedData.fogStart;
  50672. scene.fogEnd = parsedData.fogEnd;
  50673. scene.fogDensity = parsedData.fogDensity;
  50674. log += "\tFog mode for scene: ";
  50675. switch (scene.fogMode) {
  50676. // getters not compiling, so using hardcoded
  50677. case 1:
  50678. log += "exp\n";
  50679. break;
  50680. case 2:
  50681. log += "exp2\n";
  50682. break;
  50683. case 3:
  50684. log += "linear\n";
  50685. break;
  50686. }
  50687. }
  50688. //Physics
  50689. if (parsedData.physicsEnabled) {
  50690. var physicsPlugin;
  50691. if (parsedData.physicsEngine === "cannon") {
  50692. physicsPlugin = new BABYLON.CannonJSPlugin();
  50693. }
  50694. else if (parsedData.physicsEngine === "oimo") {
  50695. physicsPlugin = new BABYLON.OimoJSPlugin();
  50696. }
  50697. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  50698. //else - default engine, which is currently oimo
  50699. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  50700. scene.enablePhysics(physicsGravity, physicsPlugin);
  50701. }
  50702. // Metadata
  50703. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  50704. scene.metadata = parsedData.metadata;
  50705. }
  50706. //collisions, if defined. otherwise, default is true
  50707. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  50708. scene.collisionsEnabled = parsedData.collisionsEnabled;
  50709. }
  50710. scene.workerCollisions = !!parsedData.workerCollisions;
  50711. var index;
  50712. var cache;
  50713. // Lights
  50714. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  50715. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  50716. var parsedLight = parsedData.lights[index];
  50717. var light = BABYLON.Light.Parse(parsedLight, scene);
  50718. log += (index === 0 ? "\n\tLights:" : "");
  50719. log += "\n\t\t" + light.toString(fullDetails);
  50720. }
  50721. }
  50722. // Animations
  50723. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  50724. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  50725. var parsedAnimation = parsedData.animations[index];
  50726. var animation = BABYLON.Animation.Parse(parsedAnimation);
  50727. scene.animations.push(animation);
  50728. log += (index === 0 ? "\n\tAnimations:" : "");
  50729. log += "\n\t\t" + animation.toString(fullDetails);
  50730. }
  50731. }
  50732. if (parsedData.autoAnimate) {
  50733. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  50734. }
  50735. // Materials
  50736. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  50737. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  50738. var parsedMaterial = parsedData.materials[index];
  50739. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  50740. log += (index === 0 ? "\n\tMaterials:" : "");
  50741. log += "\n\t\t" + mat.toString(fullDetails);
  50742. }
  50743. }
  50744. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  50745. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  50746. var parsedMultiMaterial = parsedData.multiMaterials[index];
  50747. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  50748. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  50749. log += "\n\t\t" + mmat.toString(fullDetails);
  50750. }
  50751. }
  50752. // Morph targets
  50753. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  50754. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  50755. var managerData = _a[_i];
  50756. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  50757. }
  50758. }
  50759. // Skeletons
  50760. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  50761. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  50762. var parsedSkeleton = parsedData.skeletons[index];
  50763. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  50764. log += (index === 0 ? "\n\tSkeletons:" : "");
  50765. log += "\n\t\t" + skeleton.toString(fullDetails);
  50766. }
  50767. }
  50768. // Geometries
  50769. var geometries = parsedData.geometries;
  50770. if (geometries !== undefined && geometries !== null) {
  50771. // Boxes
  50772. var boxes = geometries.boxes;
  50773. if (boxes !== undefined && boxes !== null) {
  50774. for (index = 0, cache = boxes.length; index < cache; index++) {
  50775. var parsedBox = boxes[index];
  50776. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  50777. }
  50778. }
  50779. // Spheres
  50780. var spheres = geometries.spheres;
  50781. if (spheres !== undefined && spheres !== null) {
  50782. for (index = 0, cache = spheres.length; index < cache; index++) {
  50783. var parsedSphere = spheres[index];
  50784. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  50785. }
  50786. }
  50787. // Cylinders
  50788. var cylinders = geometries.cylinders;
  50789. if (cylinders !== undefined && cylinders !== null) {
  50790. for (index = 0, cache = cylinders.length; index < cache; index++) {
  50791. var parsedCylinder = cylinders[index];
  50792. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  50793. }
  50794. }
  50795. // Toruses
  50796. var toruses = geometries.toruses;
  50797. if (toruses !== undefined && toruses !== null) {
  50798. for (index = 0, cache = toruses.length; index < cache; index++) {
  50799. var parsedTorus = toruses[index];
  50800. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  50801. }
  50802. }
  50803. // Grounds
  50804. var grounds = geometries.grounds;
  50805. if (grounds !== undefined && grounds !== null) {
  50806. for (index = 0, cache = grounds.length; index < cache; index++) {
  50807. var parsedGround = grounds[index];
  50808. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  50809. }
  50810. }
  50811. // Planes
  50812. var planes = geometries.planes;
  50813. if (planes !== undefined && planes !== null) {
  50814. for (index = 0, cache = planes.length; index < cache; index++) {
  50815. var parsedPlane = planes[index];
  50816. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  50817. }
  50818. }
  50819. // TorusKnots
  50820. var torusKnots = geometries.torusKnots;
  50821. if (torusKnots !== undefined && torusKnots !== null) {
  50822. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  50823. var parsedTorusKnot = torusKnots[index];
  50824. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  50825. }
  50826. }
  50827. // VertexData
  50828. var vertexData = geometries.vertexData;
  50829. if (vertexData !== undefined && vertexData !== null) {
  50830. for (index = 0, cache = vertexData.length; index < cache; index++) {
  50831. var parsedVertexData = vertexData[index];
  50832. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  50833. }
  50834. }
  50835. }
  50836. // Meshes
  50837. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  50838. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  50839. var parsedMesh = parsedData.meshes[index];
  50840. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  50841. log += (index === 0 ? "\n\tMeshes:" : "");
  50842. log += "\n\t\t" + mesh.toString(fullDetails);
  50843. }
  50844. }
  50845. // Cameras
  50846. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  50847. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  50848. var parsedCamera = parsedData.cameras[index];
  50849. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  50850. log += (index === 0 ? "\n\tCameras:" : "");
  50851. log += "\n\t\t" + camera.toString(fullDetails);
  50852. }
  50853. }
  50854. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  50855. scene.setActiveCameraByID(parsedData.activeCameraID);
  50856. }
  50857. // Browsing all the graph to connect the dots
  50858. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  50859. var camera = scene.cameras[index];
  50860. if (camera._waitingParentId) {
  50861. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  50862. camera._waitingParentId = undefined;
  50863. }
  50864. }
  50865. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  50866. var light = scene.lights[index];
  50867. if (light._waitingParentId) {
  50868. light.parent = scene.getLastEntryByID(light._waitingParentId);
  50869. light._waitingParentId = undefined;
  50870. }
  50871. }
  50872. // Sounds
  50873. var loadedSounds = [];
  50874. var loadedSound;
  50875. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  50876. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  50877. var parsedSound = parsedData.sounds[index];
  50878. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50879. if (!parsedSound.url)
  50880. parsedSound.url = parsedSound.name;
  50881. if (!loadedSounds[parsedSound.url]) {
  50882. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  50883. loadedSounds[parsedSound.url] = loadedSound;
  50884. }
  50885. else {
  50886. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  50887. }
  50888. }
  50889. else {
  50890. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  50891. }
  50892. }
  50893. }
  50894. loadedSounds = [];
  50895. // Connect parents & children and parse actions
  50896. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  50897. var mesh = scene.meshes[index];
  50898. if (mesh._waitingParentId) {
  50899. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  50900. mesh._waitingParentId = undefined;
  50901. }
  50902. if (mesh._waitingActions) {
  50903. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  50904. mesh._waitingActions = undefined;
  50905. }
  50906. }
  50907. // freeze world matrix application
  50908. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  50909. var currentMesh = scene.meshes[index];
  50910. if (currentMesh._waitingFreezeWorldMatrix) {
  50911. currentMesh.freezeWorldMatrix();
  50912. currentMesh._waitingFreezeWorldMatrix = undefined;
  50913. }
  50914. else {
  50915. currentMesh.computeWorldMatrix(true);
  50916. }
  50917. }
  50918. // Particles Systems
  50919. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  50920. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  50921. var parsedParticleSystem = parsedData.particleSystems[index];
  50922. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  50923. }
  50924. }
  50925. // Lens flares
  50926. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  50927. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  50928. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  50929. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  50930. }
  50931. }
  50932. // Shadows
  50933. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  50934. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  50935. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  50936. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  50937. }
  50938. }
  50939. // Lights exclusions / inclusions
  50940. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  50941. var light = scene.lights[index];
  50942. // Excluded check
  50943. if (light._excludedMeshesIds.length > 0) {
  50944. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  50945. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  50946. if (excludedMesh) {
  50947. light.excludedMeshes.push(excludedMesh);
  50948. }
  50949. }
  50950. light._excludedMeshesIds = [];
  50951. }
  50952. // Included check
  50953. if (light._includedOnlyMeshesIds.length > 0) {
  50954. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  50955. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  50956. if (includedOnlyMesh) {
  50957. light.includedOnlyMeshes.push(includedOnlyMesh);
  50958. }
  50959. }
  50960. light._includedOnlyMeshesIds = [];
  50961. }
  50962. }
  50963. // Actions (scene)
  50964. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  50965. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  50966. }
  50967. // Finish
  50968. return true;
  50969. }
  50970. catch (err) {
  50971. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  50972. if (onError) {
  50973. onError(msg, err);
  50974. }
  50975. else {
  50976. BABYLON.Tools.Log(msg);
  50977. log = null;
  50978. throw err;
  50979. }
  50980. }
  50981. finally {
  50982. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  50983. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  50984. }
  50985. }
  50986. }
  50987. });
  50988. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50989. })(BABYLON || (BABYLON = {}));
  50990. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  50991. var BABYLON;
  50992. (function (BABYLON) {
  50993. var FilesInput = (function () {
  50994. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  50995. this.onProcessFileCallback = function () { return true; };
  50996. this._engine = engine;
  50997. this._currentScene = scene;
  50998. this._sceneLoadedCallback = sceneLoadedCallback;
  50999. this._progressCallback = progressCallback;
  51000. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  51001. this._textureLoadingCallback = textureLoadingCallback;
  51002. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  51003. this._onReloadCallback = onReloadCallback;
  51004. this._errorCallback = errorCallback;
  51005. }
  51006. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  51007. var _this = this;
  51008. if (elementToMonitor) {
  51009. this._elementToMonitor = elementToMonitor;
  51010. this._dragEnterHandler = function (e) { _this.drag(e); };
  51011. this._dragOverHandler = function (e) { _this.drag(e); };
  51012. this._dropHandler = function (e) { _this.drop(e); };
  51013. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  51014. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  51015. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  51016. }
  51017. };
  51018. FilesInput.prototype.dispose = function () {
  51019. if (!this._elementToMonitor) {
  51020. return;
  51021. }
  51022. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  51023. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  51024. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  51025. };
  51026. FilesInput.prototype.renderFunction = function () {
  51027. if (this._additionalRenderLoopLogicCallback) {
  51028. this._additionalRenderLoopLogicCallback();
  51029. }
  51030. if (this._currentScene) {
  51031. if (this._textureLoadingCallback) {
  51032. var remaining = this._currentScene.getWaitingItemsCount();
  51033. if (remaining > 0) {
  51034. this._textureLoadingCallback(remaining);
  51035. }
  51036. }
  51037. this._currentScene.render();
  51038. }
  51039. };
  51040. FilesInput.prototype.drag = function (e) {
  51041. e.stopPropagation();
  51042. e.preventDefault();
  51043. };
  51044. FilesInput.prototype.drop = function (eventDrop) {
  51045. eventDrop.stopPropagation();
  51046. eventDrop.preventDefault();
  51047. this.loadFiles(eventDrop);
  51048. };
  51049. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  51050. var _this = this;
  51051. var reader = folder.createReader();
  51052. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  51053. reader.readEntries(function (entries) {
  51054. remaining.count += entries.length;
  51055. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  51056. var entry = entries_1[_i];
  51057. if (entry.isFile) {
  51058. entry.file(function (file) {
  51059. file.correctName = relativePath + file.name;
  51060. files.push(file);
  51061. if (--remaining.count === 0) {
  51062. callback();
  51063. }
  51064. });
  51065. }
  51066. else if (entry.isDirectory) {
  51067. _this._traverseFolder(entry, files, remaining, callback);
  51068. }
  51069. }
  51070. if (--remaining.count) {
  51071. callback();
  51072. }
  51073. });
  51074. };
  51075. FilesInput.prototype._processFiles = function (files) {
  51076. var skippedFiles = 0;
  51077. for (var i = 0; i < files.length; i++) {
  51078. var name = files[i].correctName.toLowerCase();
  51079. var extension = name.split('.').pop();
  51080. if (!this.onProcessFileCallback(files[i], name, extension)) {
  51081. skippedFiles++;
  51082. continue;
  51083. }
  51084. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  51085. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  51086. this._sceneFileToLoad = files[i];
  51087. }
  51088. else {
  51089. FilesInput.FilesToLoad[name] = files[i];
  51090. }
  51091. }
  51092. if (this._onReloadCallback) {
  51093. this._onReloadCallback(this._sceneFileToLoad);
  51094. }
  51095. else if (skippedFiles < files.length) {
  51096. this.reload();
  51097. }
  51098. };
  51099. FilesInput.prototype.loadFiles = function (event) {
  51100. var _this = this;
  51101. if (this._startingProcessingFilesCallback)
  51102. this._startingProcessingFilesCallback();
  51103. // Handling data transfer via drag'n'drop
  51104. if (event && event.dataTransfer && event.dataTransfer.files) {
  51105. this._filesToLoad = event.dataTransfer.files;
  51106. }
  51107. // Handling files from input files
  51108. if (event && event.target && event.target.files) {
  51109. this._filesToLoad = event.target.files;
  51110. }
  51111. if (this._filesToLoad && this._filesToLoad.length > 0) {
  51112. var files_1 = new Array();
  51113. var folders = [];
  51114. var items = event.dataTransfer ? event.dataTransfer.items : null;
  51115. for (var i = 0; i < this._filesToLoad.length; i++) {
  51116. var fileToLoad = this._filesToLoad[i];
  51117. var name_1 = fileToLoad.name.toLowerCase();
  51118. var type = fileToLoad.type;
  51119. var entry = void 0;
  51120. fileToLoad.correctName = name_1;
  51121. if (items) {
  51122. var item = items[i];
  51123. if (item.getAsEntry) {
  51124. entry = item.getAsEntry();
  51125. }
  51126. else if (item.webkitGetAsEntry) {
  51127. entry = item.webkitGetAsEntry();
  51128. }
  51129. }
  51130. if (!entry) {
  51131. files_1.push(fileToLoad);
  51132. }
  51133. else {
  51134. if (entry.isDirectory) {
  51135. folders.push(entry);
  51136. }
  51137. else {
  51138. files_1.push(fileToLoad);
  51139. }
  51140. }
  51141. }
  51142. if (folders.length === 0) {
  51143. this._processFiles(files_1);
  51144. }
  51145. else {
  51146. var remaining = { count: folders.length };
  51147. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  51148. var folder = folders_1[_i];
  51149. this._traverseFolder(folder, files_1, remaining, function () {
  51150. _this._processFiles(files_1);
  51151. });
  51152. }
  51153. }
  51154. }
  51155. };
  51156. FilesInput.prototype.reload = function () {
  51157. var _this = this;
  51158. // If a ".babylon" file has been provided
  51159. if (this._sceneFileToLoad) {
  51160. if (this._currentScene) {
  51161. if (BABYLON.Tools.errorsCount > 0) {
  51162. BABYLON.Tools.ClearLogCache();
  51163. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  51164. }
  51165. this._engine.stopRenderLoop();
  51166. this._currentScene.dispose();
  51167. }
  51168. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  51169. _this._currentScene = newScene;
  51170. if (_this._sceneLoadedCallback) {
  51171. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  51172. }
  51173. // Wait for textures and shaders to be ready
  51174. _this._currentScene.executeWhenReady(function () {
  51175. _this._engine.runRenderLoop(function () {
  51176. _this.renderFunction();
  51177. });
  51178. });
  51179. }, function (progress) {
  51180. if (_this._progressCallback) {
  51181. _this._progressCallback(progress);
  51182. }
  51183. }, function (scene, message) {
  51184. _this._currentScene = scene;
  51185. if (_this._errorCallback) {
  51186. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  51187. }
  51188. });
  51189. }
  51190. else {
  51191. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  51192. }
  51193. };
  51194. FilesInput.FilesToLoad = {};
  51195. return FilesInput;
  51196. }());
  51197. BABYLON.FilesInput = FilesInput;
  51198. })(BABYLON || (BABYLON = {}));
  51199. //# sourceMappingURL=babylon.filesInput.js.map
  51200. var BABYLON;
  51201. (function (BABYLON) {
  51202. /**
  51203. * This class implement a typical dictionary using a string as key and the generic type T as value.
  51204. * The underlying implementation relies on an associative array to ensure the best performances.
  51205. * The value can be anything including 'null' but except 'undefined'
  51206. */
  51207. var StringDictionary = (function () {
  51208. function StringDictionary() {
  51209. this._count = 0;
  51210. this._data = {};
  51211. }
  51212. /**
  51213. * This will clear this dictionary and copy the content from the 'source' one.
  51214. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  51215. * @param source the dictionary to take the content from and copy to this dictionary
  51216. */
  51217. StringDictionary.prototype.copyFrom = function (source) {
  51218. var _this = this;
  51219. this.clear();
  51220. source.forEach(function (t, v) { return _this.add(t, v); });
  51221. };
  51222. /**
  51223. * Get a value based from its key
  51224. * @param key the given key to get the matching value from
  51225. * @return the value if found, otherwise undefined is returned
  51226. */
  51227. StringDictionary.prototype.get = function (key) {
  51228. var val = this._data[key];
  51229. if (val !== undefined) {
  51230. return val;
  51231. }
  51232. return undefined;
  51233. };
  51234. /**
  51235. * Get a value from its key or add it if it doesn't exist.
  51236. * This method will ensure you that a given key/data will be present in the dictionary.
  51237. * @param key the given key to get the matching value from
  51238. * @param factory the factory that will create the value if the key is not present in the dictionary.
  51239. * The factory will only be invoked if there's no data for the given key.
  51240. * @return the value corresponding to the key.
  51241. */
  51242. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  51243. var val = this.get(key);
  51244. if (val !== undefined) {
  51245. return val;
  51246. }
  51247. val = factory(key);
  51248. if (val) {
  51249. this.add(key, val);
  51250. }
  51251. return val;
  51252. };
  51253. /**
  51254. * Get a value from its key if present in the dictionary otherwise add it
  51255. * @param key the key to get the value from
  51256. * @param val if there's no such key/value pair in the dictionary add it with this value
  51257. * @return the value corresponding to the key
  51258. */
  51259. StringDictionary.prototype.getOrAdd = function (key, val) {
  51260. var curVal = this.get(key);
  51261. if (curVal !== undefined) {
  51262. return curVal;
  51263. }
  51264. this.add(key, val);
  51265. return val;
  51266. };
  51267. /**
  51268. * Check if there's a given key in the dictionary
  51269. * @param key the key to check for
  51270. * @return true if the key is present, false otherwise
  51271. */
  51272. StringDictionary.prototype.contains = function (key) {
  51273. return this._data[key] !== undefined;
  51274. };
  51275. /**
  51276. * Add a new key and its corresponding value
  51277. * @param key the key to add
  51278. * @param value the value corresponding to the key
  51279. * @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
  51280. */
  51281. StringDictionary.prototype.add = function (key, value) {
  51282. if (this._data[key] !== undefined) {
  51283. return false;
  51284. }
  51285. this._data[key] = value;
  51286. ++this._count;
  51287. return true;
  51288. };
  51289. StringDictionary.prototype.set = function (key, value) {
  51290. if (this._data[key] === undefined) {
  51291. return false;
  51292. }
  51293. this._data[key] = value;
  51294. return true;
  51295. };
  51296. /**
  51297. * Get the element of the given key and remove it from the dictionary
  51298. * @param key
  51299. */
  51300. StringDictionary.prototype.getAndRemove = function (key) {
  51301. var val = this.get(key);
  51302. if (val !== undefined) {
  51303. delete this._data[key];
  51304. --this._count;
  51305. return val;
  51306. }
  51307. return null;
  51308. };
  51309. /**
  51310. * Remove a key/value from the dictionary.
  51311. * @param key the key to remove
  51312. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  51313. */
  51314. StringDictionary.prototype.remove = function (key) {
  51315. if (this.contains(key)) {
  51316. delete this._data[key];
  51317. --this._count;
  51318. return true;
  51319. }
  51320. return false;
  51321. };
  51322. /**
  51323. * Clear the whole content of the dictionary
  51324. */
  51325. StringDictionary.prototype.clear = function () {
  51326. this._data = {};
  51327. this._count = 0;
  51328. };
  51329. Object.defineProperty(StringDictionary.prototype, "count", {
  51330. get: function () {
  51331. return this._count;
  51332. },
  51333. enumerable: true,
  51334. configurable: true
  51335. });
  51336. /**
  51337. * Execute a callback on each key/val of the dictionary.
  51338. * Note that you can remove any element in this dictionary in the callback implementation
  51339. * @param callback the callback to execute on a given key/value pair
  51340. */
  51341. StringDictionary.prototype.forEach = function (callback) {
  51342. for (var cur in this._data) {
  51343. var val = this._data[cur];
  51344. callback(cur, val);
  51345. }
  51346. };
  51347. /**
  51348. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  51349. * If the callback returns null or undefined the method will iterate to the next key/value pair
  51350. * Note that you can remove any element in this dictionary in the callback implementation
  51351. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  51352. */
  51353. StringDictionary.prototype.first = function (callback) {
  51354. for (var cur in this._data) {
  51355. var val = this._data[cur];
  51356. var res = callback(cur, val);
  51357. if (res) {
  51358. return res;
  51359. }
  51360. }
  51361. return null;
  51362. };
  51363. return StringDictionary;
  51364. }());
  51365. BABYLON.StringDictionary = StringDictionary;
  51366. })(BABYLON || (BABYLON = {}));
  51367. //# sourceMappingURL=babylon.stringDictionary.js.map
  51368. var BABYLON;
  51369. (function (BABYLON) {
  51370. var Tags = (function () {
  51371. function Tags() {
  51372. }
  51373. Tags.EnableFor = function (obj) {
  51374. obj._tags = obj._tags || {};
  51375. obj.hasTags = function () {
  51376. return Tags.HasTags(obj);
  51377. };
  51378. obj.addTags = function (tagsString) {
  51379. return Tags.AddTagsTo(obj, tagsString);
  51380. };
  51381. obj.removeTags = function (tagsString) {
  51382. return Tags.RemoveTagsFrom(obj, tagsString);
  51383. };
  51384. obj.matchesTagsQuery = function (tagsQuery) {
  51385. return Tags.MatchesQuery(obj, tagsQuery);
  51386. };
  51387. };
  51388. Tags.DisableFor = function (obj) {
  51389. delete obj._tags;
  51390. delete obj.hasTags;
  51391. delete obj.addTags;
  51392. delete obj.removeTags;
  51393. delete obj.matchesTagsQuery;
  51394. };
  51395. Tags.HasTags = function (obj) {
  51396. if (!obj._tags) {
  51397. return false;
  51398. }
  51399. return !BABYLON.Tools.IsEmpty(obj._tags);
  51400. };
  51401. Tags.GetTags = function (obj, asString) {
  51402. if (asString === void 0) { asString = true; }
  51403. if (!obj._tags) {
  51404. return null;
  51405. }
  51406. if (asString) {
  51407. var tagsArray = [];
  51408. for (var tag in obj._tags) {
  51409. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  51410. tagsArray.push(tag);
  51411. }
  51412. }
  51413. return tagsArray.join(" ");
  51414. }
  51415. else {
  51416. return obj._tags;
  51417. }
  51418. };
  51419. // the tags 'true' and 'false' are reserved and cannot be used as tags
  51420. // a tag cannot start with '||', '&&', and '!'
  51421. // it cannot contain whitespaces
  51422. Tags.AddTagsTo = function (obj, tagsString) {
  51423. if (!tagsString) {
  51424. return;
  51425. }
  51426. if (typeof tagsString !== "string") {
  51427. return;
  51428. }
  51429. var tags = tagsString.split(" ");
  51430. tags.forEach(function (tag, index, array) {
  51431. Tags._AddTagTo(obj, tag);
  51432. });
  51433. };
  51434. Tags._AddTagTo = function (obj, tag) {
  51435. tag = tag.trim();
  51436. if (tag === "" || tag === "true" || tag === "false") {
  51437. return;
  51438. }
  51439. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  51440. return;
  51441. }
  51442. Tags.EnableFor(obj);
  51443. obj._tags[tag] = true;
  51444. };
  51445. Tags.RemoveTagsFrom = function (obj, tagsString) {
  51446. if (!Tags.HasTags(obj)) {
  51447. return;
  51448. }
  51449. var tags = tagsString.split(" ");
  51450. for (var t in tags) {
  51451. Tags._RemoveTagFrom(obj, tags[t]);
  51452. }
  51453. };
  51454. Tags._RemoveTagFrom = function (obj, tag) {
  51455. delete obj._tags[tag];
  51456. };
  51457. Tags.MatchesQuery = function (obj, tagsQuery) {
  51458. if (tagsQuery === undefined) {
  51459. return true;
  51460. }
  51461. if (tagsQuery === "") {
  51462. return Tags.HasTags(obj);
  51463. }
  51464. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  51465. };
  51466. return Tags;
  51467. }());
  51468. BABYLON.Tags = Tags;
  51469. })(BABYLON || (BABYLON = {}));
  51470. //# sourceMappingURL=babylon.tags.js.map
  51471. var BABYLON;
  51472. (function (BABYLON) {
  51473. var Internals;
  51474. (function (Internals) {
  51475. var AndOrNotEvaluator = (function () {
  51476. function AndOrNotEvaluator() {
  51477. }
  51478. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  51479. if (!query.match(/\([^\(\)]*\)/g)) {
  51480. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  51481. }
  51482. else {
  51483. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  51484. // remove parenthesis
  51485. r = r.slice(1, r.length - 1);
  51486. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  51487. });
  51488. }
  51489. if (query === "true") {
  51490. return true;
  51491. }
  51492. if (query === "false") {
  51493. return false;
  51494. }
  51495. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  51496. };
  51497. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  51498. evaluateCallback = evaluateCallback || (function (r) {
  51499. return r === "true" ? true : false;
  51500. });
  51501. var result;
  51502. var or = parenthesisContent.split("||");
  51503. for (var i in or) {
  51504. if (or.hasOwnProperty(i)) {
  51505. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  51506. var and = ori.split("&&");
  51507. if (and.length > 1) {
  51508. for (var j = 0; j < and.length; ++j) {
  51509. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  51510. if (andj !== "true" && andj !== "false") {
  51511. if (andj[0] === "!") {
  51512. result = !evaluateCallback(andj.substring(1));
  51513. }
  51514. else {
  51515. result = evaluateCallback(andj);
  51516. }
  51517. }
  51518. else {
  51519. result = andj === "true" ? true : false;
  51520. }
  51521. if (!result) {
  51522. ori = "false";
  51523. break;
  51524. }
  51525. }
  51526. }
  51527. if (result || ori === "true") {
  51528. result = true;
  51529. break;
  51530. }
  51531. // result equals false (or undefined)
  51532. if (ori !== "true" && ori !== "false") {
  51533. if (ori[0] === "!") {
  51534. result = !evaluateCallback(ori.substring(1));
  51535. }
  51536. else {
  51537. result = evaluateCallback(ori);
  51538. }
  51539. }
  51540. else {
  51541. result = ori === "true" ? true : false;
  51542. }
  51543. }
  51544. }
  51545. // the whole parenthesis scope is replaced by 'true' or 'false'
  51546. return result ? "true" : "false";
  51547. };
  51548. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  51549. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  51550. // remove whitespaces
  51551. r = r.replace(/[\s]/g, function () { return ""; });
  51552. return r.length % 2 ? "!" : "";
  51553. });
  51554. booleanString = booleanString.trim();
  51555. if (booleanString === "!true") {
  51556. booleanString = "false";
  51557. }
  51558. else if (booleanString === "!false") {
  51559. booleanString = "true";
  51560. }
  51561. return booleanString;
  51562. };
  51563. return AndOrNotEvaluator;
  51564. }());
  51565. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  51566. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51567. })(BABYLON || (BABYLON = {}));
  51568. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  51569. var BABYLON;
  51570. (function (BABYLON) {
  51571. var Database = (function () {
  51572. function Database(urlToScene, callbackManifestChecked) {
  51573. // Handling various flavors of prefixed version of IndexedDB
  51574. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  51575. this.callbackManifestChecked = callbackManifestChecked;
  51576. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  51577. this.db = null;
  51578. this.enableSceneOffline = false;
  51579. this.enableTexturesOffline = false;
  51580. this.manifestVersionFound = 0;
  51581. this.mustUpdateRessources = false;
  51582. this.hasReachedQuota = false;
  51583. if (!Database.IDBStorageEnabled) {
  51584. this.callbackManifestChecked(true);
  51585. }
  51586. else {
  51587. this.checkManifestFile();
  51588. }
  51589. }
  51590. Database.prototype.checkManifestFile = function () {
  51591. var _this = this;
  51592. function noManifestFile() {
  51593. that.enableSceneOffline = false;
  51594. that.enableTexturesOffline = false;
  51595. that.callbackManifestChecked(false);
  51596. }
  51597. var that = this;
  51598. var timeStampUsed = false;
  51599. var manifestURL = this.currentSceneUrl + ".manifest";
  51600. var xhr = new XMLHttpRequest();
  51601. if (navigator.onLine) {
  51602. // Adding a timestamp to by-pass browsers' cache
  51603. timeStampUsed = true;
  51604. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  51605. }
  51606. xhr.open("GET", manifestURL, true);
  51607. xhr.addEventListener("load", function () {
  51608. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  51609. try {
  51610. var manifestFile = JSON.parse(xhr.response);
  51611. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  51612. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  51613. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  51614. _this.manifestVersionFound = manifestFile.version;
  51615. }
  51616. if (_this.callbackManifestChecked) {
  51617. _this.callbackManifestChecked(true);
  51618. }
  51619. }
  51620. catch (ex) {
  51621. noManifestFile();
  51622. }
  51623. }
  51624. else {
  51625. noManifestFile();
  51626. }
  51627. }, false);
  51628. xhr.addEventListener("error", function (event) {
  51629. if (timeStampUsed) {
  51630. timeStampUsed = false;
  51631. // Let's retry without the timeStamp
  51632. // It could fail when coupled with HTML5 Offline API
  51633. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  51634. xhr.open("GET", retryManifestURL, true);
  51635. xhr.send();
  51636. }
  51637. else {
  51638. noManifestFile();
  51639. }
  51640. }, false);
  51641. try {
  51642. xhr.send();
  51643. }
  51644. catch (ex) {
  51645. BABYLON.Tools.Error("Error on XHR send request.");
  51646. that.callbackManifestChecked(false);
  51647. }
  51648. };
  51649. Database.prototype.openAsync = function (successCallback, errorCallback) {
  51650. var _this = this;
  51651. function handleError() {
  51652. that.isSupported = false;
  51653. if (errorCallback)
  51654. errorCallback();
  51655. }
  51656. var that = this;
  51657. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  51658. // Your browser doesn't support IndexedDB
  51659. this.isSupported = false;
  51660. if (errorCallback)
  51661. errorCallback();
  51662. }
  51663. else {
  51664. // If the DB hasn't been opened or created yet
  51665. if (!this.db) {
  51666. this.hasReachedQuota = false;
  51667. this.isSupported = true;
  51668. var request = this.idbFactory.open("babylonjs", 1);
  51669. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  51670. request.onerror = function (event) {
  51671. handleError();
  51672. };
  51673. // executes when a version change transaction cannot complete due to other active transactions
  51674. request.onblocked = function (event) {
  51675. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  51676. handleError();
  51677. };
  51678. // DB has been opened successfully
  51679. request.onsuccess = function (event) {
  51680. _this.db = request.result;
  51681. successCallback();
  51682. };
  51683. // Initialization of the DB. Creating Scenes & Textures stores
  51684. request.onupgradeneeded = function (event) {
  51685. _this.db = (event.target).result;
  51686. try {
  51687. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  51688. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  51689. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  51690. }
  51691. catch (ex) {
  51692. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  51693. handleError();
  51694. }
  51695. };
  51696. }
  51697. else {
  51698. if (successCallback)
  51699. successCallback();
  51700. }
  51701. }
  51702. };
  51703. Database.prototype.loadImageFromDB = function (url, image) {
  51704. var _this = this;
  51705. var completeURL = Database.ReturnFullUrlLocation(url);
  51706. var saveAndLoadImage = function () {
  51707. if (!_this.hasReachedQuota && _this.db !== null) {
  51708. // the texture is not yet in the DB, let's try to save it
  51709. _this._saveImageIntoDBAsync(completeURL, image);
  51710. }
  51711. else {
  51712. image.src = url;
  51713. }
  51714. };
  51715. if (!this.mustUpdateRessources) {
  51716. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  51717. }
  51718. else {
  51719. saveAndLoadImage();
  51720. }
  51721. };
  51722. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  51723. if (this.isSupported && this.db !== null) {
  51724. var texture;
  51725. var transaction = this.db.transaction(["textures"]);
  51726. transaction.onabort = function (event) {
  51727. image.src = url;
  51728. };
  51729. transaction.oncomplete = function (event) {
  51730. var blobTextureURL;
  51731. if (texture) {
  51732. var URL = window.URL || window.webkitURL;
  51733. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  51734. image.onerror = function () {
  51735. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  51736. image.src = url;
  51737. };
  51738. image.src = blobTextureURL;
  51739. }
  51740. else {
  51741. notInDBCallback();
  51742. }
  51743. };
  51744. var getRequest = transaction.objectStore("textures").get(url);
  51745. getRequest.onsuccess = function (event) {
  51746. texture = (event.target).result;
  51747. };
  51748. getRequest.onerror = function (event) {
  51749. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  51750. image.src = url;
  51751. };
  51752. }
  51753. else {
  51754. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  51755. image.src = url;
  51756. }
  51757. };
  51758. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  51759. var _this = this;
  51760. if (this.isSupported) {
  51761. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  51762. var generateBlobUrl = function () {
  51763. var blobTextureURL;
  51764. if (blob) {
  51765. var URL = window.URL || window.webkitURL;
  51766. try {
  51767. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  51768. }
  51769. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  51770. catch (ex) {
  51771. blobTextureURL = URL.createObjectURL(blob);
  51772. }
  51773. }
  51774. image.src = blobTextureURL;
  51775. };
  51776. if (Database.IsUASupportingBlobStorage) {
  51777. var xhr = new XMLHttpRequest(), blob;
  51778. xhr.open("GET", url, true);
  51779. xhr.responseType = "blob";
  51780. xhr.addEventListener("load", function () {
  51781. if (xhr.status === 200) {
  51782. // Blob as response (XHR2)
  51783. blob = xhr.response;
  51784. var transaction = _this.db.transaction(["textures"], "readwrite");
  51785. // the transaction could abort because of a QuotaExceededError error
  51786. transaction.onabort = function (event) {
  51787. try {
  51788. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  51789. var error = event.srcElement['error'];
  51790. if (error && error.name === "QuotaExceededError") {
  51791. _this.hasReachedQuota = true;
  51792. }
  51793. }
  51794. catch (ex) { }
  51795. generateBlobUrl();
  51796. };
  51797. transaction.oncomplete = function (event) {
  51798. generateBlobUrl();
  51799. };
  51800. var newTexture = { textureUrl: url, data: blob };
  51801. try {
  51802. // Put the blob into the dabase
  51803. var addRequest = transaction.objectStore("textures").put(newTexture);
  51804. addRequest.onsuccess = function (event) {
  51805. };
  51806. addRequest.onerror = function (event) {
  51807. generateBlobUrl();
  51808. };
  51809. }
  51810. catch (ex) {
  51811. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  51812. if (ex.code === 25) {
  51813. Database.IsUASupportingBlobStorage = false;
  51814. }
  51815. image.src = url;
  51816. }
  51817. }
  51818. else {
  51819. image.src = url;
  51820. }
  51821. }, false);
  51822. xhr.addEventListener("error", function (event) {
  51823. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  51824. image.src = url;
  51825. }, false);
  51826. xhr.send();
  51827. }
  51828. else {
  51829. image.src = url;
  51830. }
  51831. }
  51832. else {
  51833. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  51834. image.src = url;
  51835. }
  51836. };
  51837. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  51838. var _this = this;
  51839. var updateVersion = function () {
  51840. // the version is not yet in the DB or we need to update it
  51841. _this._saveVersionIntoDBAsync(url, versionLoaded);
  51842. };
  51843. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  51844. };
  51845. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  51846. var _this = this;
  51847. if (this.isSupported) {
  51848. var version;
  51849. try {
  51850. var transaction = this.db.transaction(["versions"]);
  51851. transaction.oncomplete = function (event) {
  51852. if (version) {
  51853. // If the version in the JSON file is > than the version in DB
  51854. if (_this.manifestVersionFound > version.data) {
  51855. _this.mustUpdateRessources = true;
  51856. updateInDBCallback();
  51857. }
  51858. else {
  51859. callback(version.data);
  51860. }
  51861. }
  51862. else {
  51863. _this.mustUpdateRessources = true;
  51864. updateInDBCallback();
  51865. }
  51866. };
  51867. transaction.onabort = function (event) {
  51868. callback(-1);
  51869. };
  51870. var getRequest = transaction.objectStore("versions").get(url);
  51871. getRequest.onsuccess = function (event) {
  51872. version = (event.target).result;
  51873. };
  51874. getRequest.onerror = function (event) {
  51875. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  51876. callback(-1);
  51877. };
  51878. }
  51879. catch (ex) {
  51880. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  51881. callback(-1);
  51882. }
  51883. }
  51884. else {
  51885. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  51886. callback(-1);
  51887. }
  51888. };
  51889. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  51890. var _this = this;
  51891. if (this.isSupported && !this.hasReachedQuota) {
  51892. try {
  51893. // Open a transaction to the database
  51894. var transaction = this.db.transaction(["versions"], "readwrite");
  51895. // the transaction could abort because of a QuotaExceededError error
  51896. transaction.onabort = function (event) {
  51897. try {
  51898. var error = event.srcElement['error'];
  51899. if (error && error.name === "QuotaExceededError") {
  51900. _this.hasReachedQuota = true;
  51901. }
  51902. }
  51903. catch (ex) { }
  51904. callback(-1);
  51905. };
  51906. transaction.oncomplete = function (event) {
  51907. callback(_this.manifestVersionFound);
  51908. };
  51909. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  51910. // Put the scene into the database
  51911. var addRequest = transaction.objectStore("versions").put(newVersion);
  51912. addRequest.onsuccess = function (event) {
  51913. };
  51914. addRequest.onerror = function (event) {
  51915. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  51916. };
  51917. }
  51918. catch (ex) {
  51919. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  51920. callback(-1);
  51921. }
  51922. }
  51923. else {
  51924. callback(-1);
  51925. }
  51926. };
  51927. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  51928. var _this = this;
  51929. var completeUrl = Database.ReturnFullUrlLocation(url);
  51930. var saveAndLoadFile = function () {
  51931. // the scene is not yet in the DB, let's try to save it
  51932. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  51933. };
  51934. this._checkVersionFromDB(completeUrl, function (version) {
  51935. if (version !== -1) {
  51936. if (!_this.mustUpdateRessources) {
  51937. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  51938. }
  51939. else {
  51940. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  51941. }
  51942. }
  51943. else {
  51944. errorCallback();
  51945. }
  51946. });
  51947. };
  51948. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  51949. if (this.isSupported) {
  51950. var targetStore;
  51951. if (url.indexOf(".babylon") !== -1) {
  51952. targetStore = "scenes";
  51953. }
  51954. else {
  51955. targetStore = "textures";
  51956. }
  51957. var file;
  51958. var transaction = this.db.transaction([targetStore]);
  51959. transaction.oncomplete = function (event) {
  51960. if (file) {
  51961. callback(file.data);
  51962. }
  51963. else {
  51964. notInDBCallback();
  51965. }
  51966. };
  51967. transaction.onabort = function (event) {
  51968. notInDBCallback();
  51969. };
  51970. var getRequest = transaction.objectStore(targetStore).get(url);
  51971. getRequest.onsuccess = function (event) {
  51972. file = (event.target).result;
  51973. };
  51974. getRequest.onerror = function (event) {
  51975. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  51976. notInDBCallback();
  51977. };
  51978. }
  51979. else {
  51980. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  51981. callback();
  51982. }
  51983. };
  51984. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  51985. var _this = this;
  51986. if (this.isSupported) {
  51987. var targetStore;
  51988. if (url.indexOf(".babylon") !== -1) {
  51989. targetStore = "scenes";
  51990. }
  51991. else {
  51992. targetStore = "textures";
  51993. }
  51994. // Create XHR
  51995. var xhr = new XMLHttpRequest();
  51996. var fileData;
  51997. xhr.open("GET", url, true);
  51998. if (useArrayBuffer) {
  51999. xhr.responseType = "arraybuffer";
  52000. }
  52001. xhr.onprogress = progressCallback;
  52002. xhr.addEventListener("load", function () {
  52003. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  52004. // Blob as response (XHR2)
  52005. //fileData = xhr.responseText;
  52006. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  52007. if (!_this.hasReachedQuota) {
  52008. // Open a transaction to the database
  52009. var transaction = _this.db.transaction([targetStore], "readwrite");
  52010. // the transaction could abort because of a QuotaExceededError error
  52011. transaction.onabort = function (event) {
  52012. try {
  52013. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  52014. var error = event.srcElement['error'];
  52015. if (error && error.name === "QuotaExceededError") {
  52016. _this.hasReachedQuota = true;
  52017. }
  52018. }
  52019. catch (ex) { }
  52020. callback(fileData);
  52021. };
  52022. transaction.oncomplete = function (event) {
  52023. callback(fileData);
  52024. };
  52025. var newFile;
  52026. if (targetStore === "scenes") {
  52027. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  52028. }
  52029. else {
  52030. newFile = { textureUrl: url, data: fileData };
  52031. }
  52032. try {
  52033. // Put the scene into the database
  52034. var addRequest = transaction.objectStore(targetStore).put(newFile);
  52035. addRequest.onsuccess = function (event) {
  52036. };
  52037. addRequest.onerror = function (event) {
  52038. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  52039. };
  52040. }
  52041. catch (ex) {
  52042. callback(fileData);
  52043. }
  52044. }
  52045. else {
  52046. callback(fileData);
  52047. }
  52048. }
  52049. else {
  52050. callback();
  52051. }
  52052. }, false);
  52053. xhr.addEventListener("error", function (event) {
  52054. BABYLON.Tools.Error("error on XHR request.");
  52055. callback();
  52056. }, false);
  52057. xhr.send();
  52058. }
  52059. else {
  52060. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  52061. callback();
  52062. }
  52063. };
  52064. Database.IsUASupportingBlobStorage = true;
  52065. Database.IDBStorageEnabled = true;
  52066. Database.parseURL = function (url) {
  52067. var a = document.createElement('a');
  52068. a.href = url;
  52069. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  52070. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  52071. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  52072. return absLocation;
  52073. };
  52074. Database.ReturnFullUrlLocation = function (url) {
  52075. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  52076. return (Database.parseURL(window.location.href) + url);
  52077. }
  52078. else {
  52079. return url;
  52080. }
  52081. };
  52082. return Database;
  52083. }());
  52084. BABYLON.Database = Database;
  52085. })(BABYLON || (BABYLON = {}));
  52086. //# sourceMappingURL=babylon.database.js.map
  52087. var BABYLON;
  52088. (function (BABYLON) {
  52089. var FresnelParameters = (function () {
  52090. function FresnelParameters() {
  52091. this._isEnabled = true;
  52092. this.leftColor = BABYLON.Color3.White();
  52093. this.rightColor = BABYLON.Color3.Black();
  52094. this.bias = 0;
  52095. this.power = 1;
  52096. }
  52097. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  52098. get: function () {
  52099. return this._isEnabled;
  52100. },
  52101. set: function (value) {
  52102. if (this._isEnabled === value) {
  52103. return;
  52104. }
  52105. this._isEnabled = value;
  52106. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  52107. },
  52108. enumerable: true,
  52109. configurable: true
  52110. });
  52111. FresnelParameters.prototype.clone = function () {
  52112. var newFresnelParameters = new FresnelParameters();
  52113. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  52114. return newFresnelParameters;
  52115. };
  52116. FresnelParameters.prototype.serialize = function () {
  52117. var serializationObject = {};
  52118. serializationObject.isEnabled = this.isEnabled;
  52119. serializationObject.leftColor = this.leftColor;
  52120. serializationObject.rightColor = this.rightColor;
  52121. serializationObject.bias = this.bias;
  52122. serializationObject.power = this.power;
  52123. return serializationObject;
  52124. };
  52125. FresnelParameters.Parse = function (parsedFresnelParameters) {
  52126. var fresnelParameters = new FresnelParameters();
  52127. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  52128. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  52129. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  52130. fresnelParameters.bias = parsedFresnelParameters.bias;
  52131. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  52132. return fresnelParameters;
  52133. };
  52134. return FresnelParameters;
  52135. }());
  52136. BABYLON.FresnelParameters = FresnelParameters;
  52137. })(BABYLON || (BABYLON = {}));
  52138. //# sourceMappingURL=babylon.fresnelParameters.js.map
  52139. var BABYLON;
  52140. (function (BABYLON) {
  52141. var MultiMaterial = (function (_super) {
  52142. __extends(MultiMaterial, _super);
  52143. function MultiMaterial(name, scene) {
  52144. var _this = _super.call(this, name, scene, true) || this;
  52145. scene.multiMaterials.push(_this);
  52146. _this.subMaterials = new Array();
  52147. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  52148. return _this;
  52149. }
  52150. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  52151. get: function () {
  52152. return this._subMaterials;
  52153. },
  52154. set: function (value) {
  52155. this._subMaterials = value;
  52156. this._hookArray(value);
  52157. },
  52158. enumerable: true,
  52159. configurable: true
  52160. });
  52161. MultiMaterial.prototype._hookArray = function (array) {
  52162. var _this = this;
  52163. var oldPush = array.push;
  52164. array.push = function () {
  52165. var items = [];
  52166. for (var _i = 0; _i < arguments.length; _i++) {
  52167. items[_i] = arguments[_i];
  52168. }
  52169. var result = oldPush.apply(array, items);
  52170. _this._markAllSubMeshesAsTexturesDirty();
  52171. return result;
  52172. };
  52173. var oldSplice = array.splice;
  52174. array.splice = function (index, deleteCount) {
  52175. var deleted = oldSplice.apply(array, [index, deleteCount]);
  52176. _this._markAllSubMeshesAsTexturesDirty();
  52177. return deleted;
  52178. };
  52179. };
  52180. // Properties
  52181. MultiMaterial.prototype.getSubMaterial = function (index) {
  52182. if (index < 0 || index >= this.subMaterials.length) {
  52183. return this.getScene().defaultMaterial;
  52184. }
  52185. return this.subMaterials[index];
  52186. };
  52187. MultiMaterial.prototype.getActiveTextures = function () {
  52188. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  52189. var _a;
  52190. };
  52191. // Methods
  52192. MultiMaterial.prototype.getClassName = function () {
  52193. return "MultiMaterial";
  52194. };
  52195. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  52196. for (var index = 0; index < this.subMaterials.length; index++) {
  52197. var subMaterial = this.subMaterials[index];
  52198. if (subMaterial) {
  52199. if (this.subMaterials[index].storeEffectOnSubMeshes) {
  52200. if (!this.subMaterials[index].isReadyForSubMesh(mesh, subMesh, useInstances)) {
  52201. return false;
  52202. }
  52203. continue;
  52204. }
  52205. if (!this.subMaterials[index].isReady(mesh)) {
  52206. return false;
  52207. }
  52208. }
  52209. }
  52210. return true;
  52211. };
  52212. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  52213. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  52214. for (var index = 0; index < this.subMaterials.length; index++) {
  52215. var subMaterial = null;
  52216. if (cloneChildren) {
  52217. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  52218. }
  52219. else {
  52220. subMaterial = this.subMaterials[index];
  52221. }
  52222. newMultiMaterial.subMaterials.push(subMaterial);
  52223. }
  52224. return newMultiMaterial;
  52225. };
  52226. MultiMaterial.prototype.serialize = function () {
  52227. var serializationObject = {};
  52228. serializationObject.name = this.name;
  52229. serializationObject.id = this.id;
  52230. serializationObject.tags = BABYLON.Tags.GetTags(this);
  52231. serializationObject.materials = [];
  52232. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  52233. var subMat = this.subMaterials[matIndex];
  52234. if (subMat) {
  52235. serializationObject.materials.push(subMat.id);
  52236. }
  52237. else {
  52238. serializationObject.materials.push(null);
  52239. }
  52240. }
  52241. return serializationObject;
  52242. };
  52243. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  52244. var scene = this.getScene();
  52245. if (!scene) {
  52246. return;
  52247. }
  52248. var index = scene.multiMaterials.indexOf(this);
  52249. if (index >= 0) {
  52250. scene.multiMaterials.splice(index, 1);
  52251. }
  52252. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  52253. };
  52254. return MultiMaterial;
  52255. }(BABYLON.Material));
  52256. BABYLON.MultiMaterial = MultiMaterial;
  52257. })(BABYLON || (BABYLON = {}));
  52258. //# sourceMappingURL=babylon.multiMaterial.js.map
  52259. var BABYLON;
  52260. (function (BABYLON) {
  52261. var FreeCameraTouchInput = (function () {
  52262. function FreeCameraTouchInput() {
  52263. this._offsetX = null;
  52264. this._offsetY = null;
  52265. this._pointerCount = 0;
  52266. this._pointerPressed = new Array();
  52267. this.touchAngularSensibility = 200000.0;
  52268. this.touchMoveSensibility = 250.0;
  52269. }
  52270. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  52271. var _this = this;
  52272. var previousPosition;
  52273. if (this._pointerInput === undefined) {
  52274. this._onLostFocus = function (evt) {
  52275. _this._offsetX = null;
  52276. _this._offsetY = null;
  52277. };
  52278. this._pointerInput = function (p, s) {
  52279. var evt = p.event;
  52280. if (evt.pointerType === "mouse") {
  52281. return;
  52282. }
  52283. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  52284. if (!noPreventDefault) {
  52285. evt.preventDefault();
  52286. }
  52287. _this._pointerPressed.push(evt.pointerId);
  52288. if (_this._pointerPressed.length !== 1) {
  52289. return;
  52290. }
  52291. previousPosition = {
  52292. x: evt.clientX,
  52293. y: evt.clientY
  52294. };
  52295. }
  52296. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  52297. if (!noPreventDefault) {
  52298. evt.preventDefault();
  52299. }
  52300. var index = _this._pointerPressed.indexOf(evt.pointerId);
  52301. if (index === -1) {
  52302. return;
  52303. }
  52304. _this._pointerPressed.splice(index, 1);
  52305. if (index != 0) {
  52306. return;
  52307. }
  52308. previousPosition = null;
  52309. _this._offsetX = null;
  52310. _this._offsetY = null;
  52311. }
  52312. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  52313. if (!noPreventDefault) {
  52314. evt.preventDefault();
  52315. }
  52316. if (!previousPosition) {
  52317. return;
  52318. }
  52319. var index = _this._pointerPressed.indexOf(evt.pointerId);
  52320. if (index != 0) {
  52321. return;
  52322. }
  52323. _this._offsetX = evt.clientX - previousPosition.x;
  52324. _this._offsetY = -(evt.clientY - previousPosition.y);
  52325. }
  52326. };
  52327. }
  52328. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  52329. element.addEventListener("blur", this._onLostFocus);
  52330. };
  52331. FreeCameraTouchInput.prototype.detachControl = function (element) {
  52332. if (this._pointerInput && element) {
  52333. this.camera.getScene().onPointerObservable.remove(this._observer);
  52334. this._observer = null;
  52335. element.removeEventListener("blur", this._onLostFocus);
  52336. this._onLostFocus = null;
  52337. this._pointerPressed = [];
  52338. this._offsetX = null;
  52339. this._offsetY = null;
  52340. this._pointerCount = 0;
  52341. }
  52342. };
  52343. FreeCameraTouchInput.prototype.checkInputs = function () {
  52344. if (this._offsetX) {
  52345. var camera = this.camera;
  52346. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  52347. if (this._pointerPressed.length > 1) {
  52348. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  52349. }
  52350. else {
  52351. var speed = camera._computeLocalCameraSpeed();
  52352. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  52353. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  52354. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  52355. }
  52356. }
  52357. };
  52358. FreeCameraTouchInput.prototype.getClassName = function () {
  52359. return "FreeCameraTouchInput";
  52360. };
  52361. FreeCameraTouchInput.prototype.getSimpleName = function () {
  52362. return "touch";
  52363. };
  52364. __decorate([
  52365. BABYLON.serialize()
  52366. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  52367. __decorate([
  52368. BABYLON.serialize()
  52369. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  52370. return FreeCameraTouchInput;
  52371. }());
  52372. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  52373. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  52374. })(BABYLON || (BABYLON = {}));
  52375. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  52376. /// <reference path="babylon.freeCamera.ts" />
  52377. var BABYLON;
  52378. (function (BABYLON) {
  52379. // We're mainly based on the logic defined into the FreeCamera code
  52380. var TouchCamera = (function (_super) {
  52381. __extends(TouchCamera, _super);
  52382. //-- end properties for backward compatibility for inputs
  52383. function TouchCamera(name, position, scene) {
  52384. var _this = _super.call(this, name, position, scene) || this;
  52385. _this.inputs.addTouch();
  52386. _this._setupInputs();
  52387. return _this;
  52388. }
  52389. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  52390. //-- Begin properties for backward compatibility for inputs
  52391. get: function () {
  52392. var touch = this.inputs.attached["touch"];
  52393. if (touch)
  52394. return touch.touchAngularSensibility;
  52395. },
  52396. set: function (value) {
  52397. var touch = this.inputs.attached["touch"];
  52398. if (touch)
  52399. touch.touchAngularSensibility = value;
  52400. },
  52401. enumerable: true,
  52402. configurable: true
  52403. });
  52404. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  52405. get: function () {
  52406. var touch = this.inputs.attached["touch"];
  52407. if (touch)
  52408. return touch.touchMoveSensibility;
  52409. },
  52410. set: function (value) {
  52411. var touch = this.inputs.attached["touch"];
  52412. if (touch)
  52413. touch.touchMoveSensibility = value;
  52414. },
  52415. enumerable: true,
  52416. configurable: true
  52417. });
  52418. TouchCamera.prototype.getClassName = function () {
  52419. return "TouchCamera";
  52420. };
  52421. TouchCamera.prototype._setupInputs = function () {
  52422. var mouse = this.inputs.attached["mouse"];
  52423. if (mouse) {
  52424. mouse.touchEnabled = false;
  52425. }
  52426. };
  52427. return TouchCamera;
  52428. }(BABYLON.FreeCamera));
  52429. BABYLON.TouchCamera = TouchCamera;
  52430. })(BABYLON || (BABYLON = {}));
  52431. //# sourceMappingURL=babylon.touchCamera.js.map
  52432. var BABYLON;
  52433. (function (BABYLON) {
  52434. var ProceduralTexture = (function (_super) {
  52435. __extends(ProceduralTexture, _super);
  52436. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  52437. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52438. if (isCube === void 0) { isCube = false; }
  52439. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  52440. _this.isCube = isCube;
  52441. _this.isEnabled = true;
  52442. _this._currentRefreshId = -1;
  52443. _this._refreshRate = 1;
  52444. _this._vertexBuffers = {};
  52445. _this._uniforms = new Array();
  52446. _this._samplers = new Array();
  52447. _this._textures = {};
  52448. _this._floats = {};
  52449. _this._floatsArrays = {};
  52450. _this._colors3 = {};
  52451. _this._colors4 = {};
  52452. _this._vectors2 = {};
  52453. _this._vectors3 = {};
  52454. _this._matrices = {};
  52455. _this._fallbackTextureUsed = false;
  52456. scene._proceduralTextures.push(_this);
  52457. _this.name = name;
  52458. _this.isRenderTarget = true;
  52459. _this._size = size;
  52460. _this._generateMipMaps = generateMipMaps;
  52461. _this.setFragment(fragment);
  52462. _this._fallbackTexture = fallbackTexture;
  52463. var engine = scene.getEngine();
  52464. if (isCube) {
  52465. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  52466. _this.setFloat("face", 0);
  52467. }
  52468. else {
  52469. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  52470. }
  52471. // VBO
  52472. var vertices = [];
  52473. vertices.push(1, 1);
  52474. vertices.push(-1, 1);
  52475. vertices.push(-1, -1);
  52476. vertices.push(1, -1);
  52477. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  52478. _this._createIndexBuffer();
  52479. return _this;
  52480. }
  52481. ProceduralTexture.prototype._createIndexBuffer = function () {
  52482. var engine = this.getScene().getEngine();
  52483. // Indices
  52484. var indices = [];
  52485. indices.push(0);
  52486. indices.push(1);
  52487. indices.push(2);
  52488. indices.push(0);
  52489. indices.push(2);
  52490. indices.push(3);
  52491. this._indexBuffer = engine.createIndexBuffer(indices);
  52492. };
  52493. ProceduralTexture.prototype._rebuild = function () {
  52494. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  52495. this._createIndexBuffer();
  52496. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  52497. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  52498. }
  52499. };
  52500. ProceduralTexture.prototype.reset = function () {
  52501. if (this._effect === undefined) {
  52502. return;
  52503. }
  52504. var engine = this.getScene().getEngine();
  52505. engine._releaseEffect(this._effect);
  52506. };
  52507. ProceduralTexture.prototype.isReady = function () {
  52508. var _this = this;
  52509. var engine = this.getScene().getEngine();
  52510. var shaders;
  52511. if (!this._fragment) {
  52512. return false;
  52513. }
  52514. if (this._fallbackTextureUsed) {
  52515. return true;
  52516. }
  52517. if (this._fragment.fragmentElement !== undefined) {
  52518. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  52519. }
  52520. else {
  52521. shaders = { vertex: "procedural", fragment: this._fragment };
  52522. }
  52523. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  52524. _this.releaseInternalTexture();
  52525. if (_this._fallbackTexture) {
  52526. _this._texture = _this._fallbackTexture._texture;
  52527. _this._texture.incrementReferences();
  52528. }
  52529. _this._fallbackTextureUsed = true;
  52530. });
  52531. return this._effect.isReady();
  52532. };
  52533. ProceduralTexture.prototype.resetRefreshCounter = function () {
  52534. this._currentRefreshId = -1;
  52535. };
  52536. ProceduralTexture.prototype.setFragment = function (fragment) {
  52537. this._fragment = fragment;
  52538. };
  52539. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  52540. get: function () {
  52541. return this._refreshRate;
  52542. },
  52543. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  52544. set: function (value) {
  52545. this._refreshRate = value;
  52546. this.resetRefreshCounter();
  52547. },
  52548. enumerable: true,
  52549. configurable: true
  52550. });
  52551. ProceduralTexture.prototype._shouldRender = function () {
  52552. if (!this.isEnabled || !this.isReady() || !this._texture) {
  52553. return false;
  52554. }
  52555. if (this._fallbackTextureUsed) {
  52556. return false;
  52557. }
  52558. if (this._currentRefreshId === -1) {
  52559. this._currentRefreshId = 1;
  52560. return true;
  52561. }
  52562. if (this.refreshRate === this._currentRefreshId) {
  52563. this._currentRefreshId = 1;
  52564. return true;
  52565. }
  52566. this._currentRefreshId++;
  52567. return false;
  52568. };
  52569. ProceduralTexture.prototype.getRenderSize = function () {
  52570. return this._size;
  52571. };
  52572. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  52573. if (this._fallbackTextureUsed) {
  52574. return;
  52575. }
  52576. this.releaseInternalTexture();
  52577. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  52578. };
  52579. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  52580. if (this._uniforms.indexOf(uniformName) === -1) {
  52581. this._uniforms.push(uniformName);
  52582. }
  52583. };
  52584. ProceduralTexture.prototype.setTexture = function (name, texture) {
  52585. if (this._samplers.indexOf(name) === -1) {
  52586. this._samplers.push(name);
  52587. }
  52588. this._textures[name] = texture;
  52589. return this;
  52590. };
  52591. ProceduralTexture.prototype.setFloat = function (name, value) {
  52592. this._checkUniform(name);
  52593. this._floats[name] = value;
  52594. return this;
  52595. };
  52596. ProceduralTexture.prototype.setFloats = function (name, value) {
  52597. this._checkUniform(name);
  52598. this._floatsArrays[name] = value;
  52599. return this;
  52600. };
  52601. ProceduralTexture.prototype.setColor3 = function (name, value) {
  52602. this._checkUniform(name);
  52603. this._colors3[name] = value;
  52604. return this;
  52605. };
  52606. ProceduralTexture.prototype.setColor4 = function (name, value) {
  52607. this._checkUniform(name);
  52608. this._colors4[name] = value;
  52609. return this;
  52610. };
  52611. ProceduralTexture.prototype.setVector2 = function (name, value) {
  52612. this._checkUniform(name);
  52613. this._vectors2[name] = value;
  52614. return this;
  52615. };
  52616. ProceduralTexture.prototype.setVector3 = function (name, value) {
  52617. this._checkUniform(name);
  52618. this._vectors3[name] = value;
  52619. return this;
  52620. };
  52621. ProceduralTexture.prototype.setMatrix = function (name, value) {
  52622. this._checkUniform(name);
  52623. this._matrices[name] = value;
  52624. return this;
  52625. };
  52626. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  52627. var scene = this.getScene();
  52628. var engine = scene.getEngine();
  52629. // Render
  52630. engine.enableEffect(this._effect);
  52631. engine.setState(false);
  52632. // Texture
  52633. for (var name in this._textures) {
  52634. this._effect.setTexture(name, this._textures[name]);
  52635. }
  52636. // Float
  52637. for (name in this._floats) {
  52638. this._effect.setFloat(name, this._floats[name]);
  52639. }
  52640. // Floats
  52641. for (name in this._floatsArrays) {
  52642. this._effect.setArray(name, this._floatsArrays[name]);
  52643. }
  52644. // Color3
  52645. for (name in this._colors3) {
  52646. this._effect.setColor3(name, this._colors3[name]);
  52647. }
  52648. // Color4
  52649. for (name in this._colors4) {
  52650. var color = this._colors4[name];
  52651. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  52652. }
  52653. // Vector2
  52654. for (name in this._vectors2) {
  52655. this._effect.setVector2(name, this._vectors2[name]);
  52656. }
  52657. // Vector3
  52658. for (name in this._vectors3) {
  52659. this._effect.setVector3(name, this._vectors3[name]);
  52660. }
  52661. // Matrix
  52662. for (name in this._matrices) {
  52663. this._effect.setMatrix(name, this._matrices[name]);
  52664. }
  52665. if (this.isCube) {
  52666. for (var face = 0; face < 6; face++) {
  52667. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  52668. // VBOs
  52669. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  52670. this._effect.setFloat("face", face);
  52671. // Clear
  52672. engine.clear(scene.clearColor, true, true, true);
  52673. // Draw order
  52674. engine.draw(true, 0, 6);
  52675. // Mipmaps
  52676. if (face === 5) {
  52677. engine.generateMipMapsForCubemap(this._texture);
  52678. }
  52679. }
  52680. }
  52681. else {
  52682. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  52683. // VBOs
  52684. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  52685. // Clear
  52686. engine.clear(scene.clearColor, true, true, true);
  52687. // Draw order
  52688. engine.draw(true, 0, 6);
  52689. }
  52690. // Unbind
  52691. engine.unBindFramebuffer(this._texture, this.isCube);
  52692. if (this.onGenerated) {
  52693. this.onGenerated();
  52694. }
  52695. };
  52696. ProceduralTexture.prototype.clone = function () {
  52697. var textureSize = this.getSize();
  52698. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  52699. // Base texture
  52700. newTexture.hasAlpha = this.hasAlpha;
  52701. newTexture.level = this.level;
  52702. // RenderTarget Texture
  52703. newTexture.coordinatesMode = this.coordinatesMode;
  52704. return newTexture;
  52705. };
  52706. ProceduralTexture.prototype.dispose = function () {
  52707. var index = this.getScene()._proceduralTextures.indexOf(this);
  52708. if (index >= 0) {
  52709. this.getScene()._proceduralTextures.splice(index, 1);
  52710. }
  52711. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  52712. if (vertexBuffer) {
  52713. vertexBuffer.dispose();
  52714. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  52715. }
  52716. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  52717. this._indexBuffer = null;
  52718. }
  52719. _super.prototype.dispose.call(this);
  52720. };
  52721. return ProceduralTexture;
  52722. }(BABYLON.Texture));
  52723. BABYLON.ProceduralTexture = ProceduralTexture;
  52724. })(BABYLON || (BABYLON = {}));
  52725. //# sourceMappingURL=babylon.proceduralTexture.js.map
  52726. /// <reference path="babylon.proceduralTexture.ts" />
  52727. var BABYLON;
  52728. (function (BABYLON) {
  52729. var CustomProceduralTexture = (function (_super) {
  52730. __extends(CustomProceduralTexture, _super);
  52731. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  52732. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  52733. _this._animate = true;
  52734. _this._time = 0;
  52735. _this._texturePath = texturePath;
  52736. //Try to load json
  52737. _this.loadJson(texturePath);
  52738. _this.refreshRate = 1;
  52739. return _this;
  52740. }
  52741. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  52742. var _this = this;
  52743. var that = this;
  52744. function noConfigFile() {
  52745. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  52746. try {
  52747. that.setFragment(that._texturePath);
  52748. }
  52749. catch (ex) {
  52750. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  52751. }
  52752. }
  52753. var configFileUrl = jsonUrl + "/config.json";
  52754. var xhr = new XMLHttpRequest();
  52755. xhr.open("GET", configFileUrl, true);
  52756. xhr.addEventListener("load", function () {
  52757. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  52758. try {
  52759. _this._config = JSON.parse(xhr.response);
  52760. _this.updateShaderUniforms();
  52761. _this.updateTextures();
  52762. _this.setFragment(_this._texturePath + "/custom");
  52763. _this._animate = _this._config.animate;
  52764. _this.refreshRate = _this._config.refreshrate;
  52765. }
  52766. catch (ex) {
  52767. noConfigFile();
  52768. }
  52769. }
  52770. else {
  52771. noConfigFile();
  52772. }
  52773. }, false);
  52774. xhr.addEventListener("error", function () {
  52775. noConfigFile();
  52776. }, false);
  52777. try {
  52778. xhr.send();
  52779. }
  52780. catch (ex) {
  52781. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  52782. }
  52783. };
  52784. CustomProceduralTexture.prototype.isReady = function () {
  52785. if (!_super.prototype.isReady.call(this)) {
  52786. return false;
  52787. }
  52788. for (var name in this._textures) {
  52789. var texture = this._textures[name];
  52790. if (!texture.isReady()) {
  52791. return false;
  52792. }
  52793. }
  52794. return true;
  52795. };
  52796. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  52797. if (this._animate) {
  52798. this._time += this.getScene().getAnimationRatio() * 0.03;
  52799. this.updateShaderUniforms();
  52800. }
  52801. _super.prototype.render.call(this, useCameraPostProcess);
  52802. };
  52803. CustomProceduralTexture.prototype.updateTextures = function () {
  52804. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  52805. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  52806. }
  52807. };
  52808. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  52809. if (this._config) {
  52810. for (var j = 0; j < this._config.uniforms.length; j++) {
  52811. var uniform = this._config.uniforms[j];
  52812. switch (uniform.type) {
  52813. case "float":
  52814. this.setFloat(uniform.name, uniform.value);
  52815. break;
  52816. case "color3":
  52817. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  52818. break;
  52819. case "color4":
  52820. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  52821. break;
  52822. case "vector2":
  52823. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  52824. break;
  52825. case "vector3":
  52826. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  52827. break;
  52828. }
  52829. }
  52830. }
  52831. this.setFloat("time", this._time);
  52832. };
  52833. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  52834. get: function () {
  52835. return this._animate;
  52836. },
  52837. set: function (value) {
  52838. this._animate = value;
  52839. },
  52840. enumerable: true,
  52841. configurable: true
  52842. });
  52843. return CustomProceduralTexture;
  52844. }(BABYLON.ProceduralTexture));
  52845. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  52846. })(BABYLON || (BABYLON = {}));
  52847. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  52848. var BABYLON;
  52849. (function (BABYLON) {
  52850. var FreeCameraGamepadInput = (function () {
  52851. function FreeCameraGamepadInput() {
  52852. this.gamepadAngularSensibility = 200;
  52853. this.gamepadMoveSensibility = 40;
  52854. // private members
  52855. this._cameraTransform = BABYLON.Matrix.Identity();
  52856. this._deltaTransform = BABYLON.Vector3.Zero();
  52857. this._vector3 = BABYLON.Vector3.Zero();
  52858. this._vector2 = BABYLON.Vector2.Zero();
  52859. }
  52860. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  52861. var _this = this;
  52862. var manager = this.camera.getScene().gamepadManager;
  52863. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  52864. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  52865. // prioritize XBOX gamepads.
  52866. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  52867. _this.gamepad = gamepad;
  52868. }
  52869. }
  52870. });
  52871. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  52872. if (_this.gamepad === gamepad) {
  52873. _this.gamepad = null;
  52874. }
  52875. });
  52876. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  52877. };
  52878. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  52879. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  52880. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  52881. this.gamepad = null;
  52882. };
  52883. FreeCameraGamepadInput.prototype.checkInputs = function () {
  52884. if (this.gamepad && this.gamepad.leftStick) {
  52885. var camera = this.camera;
  52886. var LSValues = this.gamepad.leftStick;
  52887. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  52888. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  52889. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  52890. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  52891. var RSValues = this.gamepad.rightStick;
  52892. if (RSValues) {
  52893. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  52894. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  52895. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  52896. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  52897. }
  52898. else {
  52899. RSValues = { x: 0, y: 0 };
  52900. }
  52901. if (!camera.rotationQuaternion) {
  52902. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  52903. }
  52904. else {
  52905. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  52906. }
  52907. var speed = camera._computeLocalCameraSpeed() * 50.0;
  52908. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  52909. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  52910. camera.cameraDirection.addInPlace(this._deltaTransform);
  52911. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  52912. camera.cameraRotation.addInPlace(this._vector2);
  52913. }
  52914. };
  52915. FreeCameraGamepadInput.prototype.getClassName = function () {
  52916. return "FreeCameraGamepadInput";
  52917. };
  52918. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  52919. return "gamepad";
  52920. };
  52921. __decorate([
  52922. BABYLON.serialize()
  52923. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  52924. __decorate([
  52925. BABYLON.serialize()
  52926. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  52927. return FreeCameraGamepadInput;
  52928. }());
  52929. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  52930. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  52931. })(BABYLON || (BABYLON = {}));
  52932. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  52933. var BABYLON;
  52934. (function (BABYLON) {
  52935. var ArcRotateCameraGamepadInput = (function () {
  52936. function ArcRotateCameraGamepadInput() {
  52937. this.gamepadRotationSensibility = 80;
  52938. this.gamepadMoveSensibility = 40;
  52939. }
  52940. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  52941. var _this = this;
  52942. var manager = this.camera.getScene().gamepadManager;
  52943. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  52944. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  52945. // prioritize XBOX gamepads.
  52946. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  52947. _this.gamepad = gamepad;
  52948. }
  52949. }
  52950. });
  52951. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  52952. if (_this.gamepad === gamepad) {
  52953. _this.gamepad = null;
  52954. }
  52955. });
  52956. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  52957. };
  52958. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  52959. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  52960. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  52961. this.gamepad = null;
  52962. };
  52963. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  52964. if (this.gamepad) {
  52965. var camera = this.camera;
  52966. var RSValues = this.gamepad.rightStick;
  52967. if (RSValues) {
  52968. if (RSValues.x != 0) {
  52969. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  52970. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  52971. camera.inertialAlphaOffset += normalizedRX;
  52972. }
  52973. }
  52974. if (RSValues.y != 0) {
  52975. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  52976. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  52977. camera.inertialBetaOffset += normalizedRY;
  52978. }
  52979. }
  52980. }
  52981. var LSValues = this.gamepad.leftStick;
  52982. if (LSValues && LSValues.y != 0) {
  52983. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  52984. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  52985. this.camera.inertialRadiusOffset -= normalizedLY;
  52986. }
  52987. }
  52988. }
  52989. };
  52990. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  52991. return "ArcRotateCameraGamepadInput";
  52992. };
  52993. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  52994. return "gamepad";
  52995. };
  52996. __decorate([
  52997. BABYLON.serialize()
  52998. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  52999. __decorate([
  53000. BABYLON.serialize()
  53001. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  53002. return ArcRotateCameraGamepadInput;
  53003. }());
  53004. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  53005. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  53006. })(BABYLON || (BABYLON = {}));
  53007. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  53008. var BABYLON;
  53009. (function (BABYLON) {
  53010. var GamepadManager = (function () {
  53011. function GamepadManager() {
  53012. var _this = this;
  53013. this._babylonGamepads = [];
  53014. this._oneGamepadConnected = false;
  53015. this._isMonitoring = false;
  53016. this._gamepadEventSupported = 'GamepadEvent' in window;
  53017. this._gamepadSupport = (navigator.getGamepads ||
  53018. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  53019. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  53020. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  53021. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  53022. for (var i in _this._babylonGamepads) {
  53023. var gamepad = _this._babylonGamepads[i];
  53024. if (gamepad && gamepad._isConnected) {
  53025. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  53026. }
  53027. }
  53028. });
  53029. this._onGamepadConnectedEvent = function (evt) {
  53030. var gamepad = evt.gamepad;
  53031. if (gamepad.index in _this._babylonGamepads) {
  53032. if (_this._babylonGamepads[gamepad.index].isConnected) {
  53033. return;
  53034. }
  53035. }
  53036. var newGamepad;
  53037. if (_this._babylonGamepads[gamepad.index]) {
  53038. newGamepad = _this._babylonGamepads[gamepad.index];
  53039. newGamepad.browserGamepad = gamepad;
  53040. newGamepad._isConnected = true;
  53041. }
  53042. else {
  53043. newGamepad = _this._addNewGamepad(gamepad);
  53044. }
  53045. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  53046. _this._startMonitoringGamepads();
  53047. };
  53048. this._onGamepadDisconnectedEvent = function (evt) {
  53049. var gamepad = evt.gamepad;
  53050. // Remove the gamepad from the list of gamepads to monitor.
  53051. for (var i in _this._babylonGamepads) {
  53052. if (_this._babylonGamepads[i].index === gamepad.index) {
  53053. var disconnectedGamepad = _this._babylonGamepads[i];
  53054. disconnectedGamepad._isConnected = false;
  53055. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  53056. break;
  53057. }
  53058. }
  53059. };
  53060. if (this._gamepadSupport) {
  53061. //first add already-connected gamepads
  53062. this._updateGamepadObjects();
  53063. if (this._babylonGamepads.length) {
  53064. this._startMonitoringGamepads();
  53065. }
  53066. // Checking if the gamepad connected event is supported (like in Firefox)
  53067. if (this._gamepadEventSupported) {
  53068. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  53069. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  53070. }
  53071. else {
  53072. this._startMonitoringGamepads();
  53073. }
  53074. }
  53075. }
  53076. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  53077. get: function () {
  53078. return this._babylonGamepads;
  53079. },
  53080. enumerable: true,
  53081. configurable: true
  53082. });
  53083. GamepadManager.prototype.getGamepadByType = function (type) {
  53084. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  53085. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  53086. var gamepad = _a[_i];
  53087. if (gamepad && gamepad.type === type) {
  53088. return gamepad;
  53089. }
  53090. }
  53091. return null;
  53092. };
  53093. GamepadManager.prototype.dispose = function () {
  53094. if (this._gamepadEventSupported) {
  53095. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  53096. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  53097. this._onGamepadConnectedEvent = null;
  53098. this._onGamepadDisconnectedEvent = null;
  53099. }
  53100. this._babylonGamepads.forEach(function (gamepad) {
  53101. gamepad.dispose();
  53102. });
  53103. this.onGamepadConnectedObservable.clear();
  53104. this.onGamepadDisconnectedObservable.clear();
  53105. this._oneGamepadConnected = false;
  53106. this._stopMonitoringGamepads();
  53107. this._babylonGamepads = [];
  53108. };
  53109. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  53110. if (!this._oneGamepadConnected) {
  53111. this._oneGamepadConnected = true;
  53112. }
  53113. var newGamepad;
  53114. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  53115. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  53116. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  53117. }
  53118. else if (gamepad.pose) {
  53119. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  53120. }
  53121. else {
  53122. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  53123. }
  53124. this._babylonGamepads[newGamepad.index] = newGamepad;
  53125. return newGamepad;
  53126. };
  53127. GamepadManager.prototype._startMonitoringGamepads = function () {
  53128. if (!this._isMonitoring) {
  53129. this._isMonitoring = true;
  53130. this._checkGamepadsStatus();
  53131. }
  53132. };
  53133. GamepadManager.prototype._stopMonitoringGamepads = function () {
  53134. this._isMonitoring = false;
  53135. };
  53136. GamepadManager.prototype._checkGamepadsStatus = function () {
  53137. var _this = this;
  53138. // Hack to be compatible Chrome
  53139. this._updateGamepadObjects();
  53140. for (var i in this._babylonGamepads) {
  53141. var gamepad = this._babylonGamepads[i];
  53142. if (!gamepad || !gamepad.isConnected) {
  53143. continue;
  53144. }
  53145. gamepad.update();
  53146. }
  53147. if (this._isMonitoring) {
  53148. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  53149. }
  53150. };
  53151. // This function is called only on Chrome, which does not properly support
  53152. // connection/disconnection events and forces you to recopy again the gamepad object
  53153. GamepadManager.prototype._updateGamepadObjects = function () {
  53154. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  53155. for (var i = 0; i < gamepads.length; i++) {
  53156. if (gamepads[i]) {
  53157. if (!this._babylonGamepads[gamepads[i].index]) {
  53158. var newGamepad = this._addNewGamepad(gamepads[i]);
  53159. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  53160. }
  53161. else {
  53162. // Forced to copy again this object for Chrome for unknown reason
  53163. this._babylonGamepads[i].browserGamepad = gamepads[i];
  53164. if (!this._babylonGamepads[i].isConnected) {
  53165. this._babylonGamepads[i]._isConnected = true;
  53166. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  53167. }
  53168. }
  53169. }
  53170. }
  53171. };
  53172. return GamepadManager;
  53173. }());
  53174. BABYLON.GamepadManager = GamepadManager;
  53175. })(BABYLON || (BABYLON = {}));
  53176. //# sourceMappingURL=babylon.gamepadManager.js.map
  53177. var BABYLON;
  53178. (function (BABYLON) {
  53179. var StickValues = (function () {
  53180. function StickValues(x, y) {
  53181. this.x = x;
  53182. this.y = y;
  53183. }
  53184. return StickValues;
  53185. }());
  53186. BABYLON.StickValues = StickValues;
  53187. var Gamepad = (function () {
  53188. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  53189. if (leftStickX === void 0) { leftStickX = 0; }
  53190. if (leftStickY === void 0) { leftStickY = 1; }
  53191. if (rightStickX === void 0) { rightStickX = 2; }
  53192. if (rightStickY === void 0) { rightStickY = 3; }
  53193. this.id = id;
  53194. this.index = index;
  53195. this.browserGamepad = browserGamepad;
  53196. this._isConnected = true;
  53197. this.type = Gamepad.GAMEPAD;
  53198. this._leftStickAxisX = leftStickX;
  53199. this._leftStickAxisY = leftStickY;
  53200. this._rightStickAxisX = rightStickX;
  53201. this._rightStickAxisY = rightStickY;
  53202. if (this.browserGamepad.axes.length >= 2) {
  53203. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  53204. }
  53205. if (this.browserGamepad.axes.length >= 4) {
  53206. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  53207. }
  53208. }
  53209. Object.defineProperty(Gamepad.prototype, "isConnected", {
  53210. get: function () {
  53211. return this._isConnected;
  53212. },
  53213. enumerable: true,
  53214. configurable: true
  53215. });
  53216. Gamepad.prototype.onleftstickchanged = function (callback) {
  53217. this._onleftstickchanged = callback;
  53218. };
  53219. Gamepad.prototype.onrightstickchanged = function (callback) {
  53220. this._onrightstickchanged = callback;
  53221. };
  53222. Object.defineProperty(Gamepad.prototype, "leftStick", {
  53223. get: function () {
  53224. return this._leftStick;
  53225. },
  53226. set: function (newValues) {
  53227. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  53228. this._onleftstickchanged(newValues);
  53229. }
  53230. this._leftStick = newValues;
  53231. },
  53232. enumerable: true,
  53233. configurable: true
  53234. });
  53235. Object.defineProperty(Gamepad.prototype, "rightStick", {
  53236. get: function () {
  53237. return this._rightStick;
  53238. },
  53239. set: function (newValues) {
  53240. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  53241. this._onrightstickchanged(newValues);
  53242. }
  53243. this._rightStick = newValues;
  53244. },
  53245. enumerable: true,
  53246. configurable: true
  53247. });
  53248. Gamepad.prototype.update = function () {
  53249. if (this._leftStick) {
  53250. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  53251. }
  53252. if (this._rightStick) {
  53253. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  53254. }
  53255. };
  53256. Gamepad.prototype.dispose = function () {
  53257. };
  53258. Gamepad.GAMEPAD = 0;
  53259. Gamepad.GENERIC = 1;
  53260. Gamepad.XBOX = 2;
  53261. Gamepad.POSE_ENABLED = 3;
  53262. return Gamepad;
  53263. }());
  53264. BABYLON.Gamepad = Gamepad;
  53265. var GenericPad = (function (_super) {
  53266. __extends(GenericPad, _super);
  53267. function GenericPad(id, index, browserGamepad) {
  53268. var _this = _super.call(this, id, index, browserGamepad) || this;
  53269. _this.onButtonDownObservable = new BABYLON.Observable();
  53270. _this.onButtonUpObservable = new BABYLON.Observable();
  53271. _this.type = Gamepad.GENERIC;
  53272. _this._buttons = new Array(browserGamepad.buttons.length);
  53273. return _this;
  53274. }
  53275. GenericPad.prototype.onbuttondown = function (callback) {
  53276. this._onbuttondown = callback;
  53277. };
  53278. GenericPad.prototype.onbuttonup = function (callback) {
  53279. this._onbuttonup = callback;
  53280. };
  53281. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  53282. if (newValue !== currentValue) {
  53283. if (newValue === 1) {
  53284. if (this._onbuttondown) {
  53285. this._onbuttondown(buttonIndex);
  53286. }
  53287. this.onButtonDownObservable.notifyObservers(buttonIndex);
  53288. }
  53289. if (newValue === 0) {
  53290. if (this._onbuttonup) {
  53291. this._onbuttonup(buttonIndex);
  53292. }
  53293. this.onButtonUpObservable.notifyObservers(buttonIndex);
  53294. }
  53295. }
  53296. return newValue;
  53297. };
  53298. GenericPad.prototype.update = function () {
  53299. _super.prototype.update.call(this);
  53300. for (var index = 0; index < this._buttons.length; index++) {
  53301. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  53302. }
  53303. };
  53304. return GenericPad;
  53305. }(Gamepad));
  53306. BABYLON.GenericPad = GenericPad;
  53307. })(BABYLON || (BABYLON = {}));
  53308. //# sourceMappingURL=babylon.gamepad.js.map
  53309. var BABYLON;
  53310. (function (BABYLON) {
  53311. var Xbox360Button;
  53312. (function (Xbox360Button) {
  53313. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  53314. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  53315. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  53316. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  53317. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  53318. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  53319. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  53320. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  53321. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  53322. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  53323. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  53324. var Xbox360Dpad;
  53325. (function (Xbox360Dpad) {
  53326. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  53327. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  53328. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  53329. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  53330. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  53331. var Xbox360Pad = (function (_super) {
  53332. __extends(Xbox360Pad, _super);
  53333. function Xbox360Pad(id, index, gamepad, xboxOne) {
  53334. if (xboxOne === void 0) { xboxOne = false; }
  53335. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  53336. _this._leftTrigger = 0;
  53337. _this._rightTrigger = 0;
  53338. _this.onButtonDownObservable = new BABYLON.Observable();
  53339. _this.onButtonUpObservable = new BABYLON.Observable();
  53340. _this.onPadDownObservable = new BABYLON.Observable();
  53341. _this.onPadUpObservable = new BABYLON.Observable();
  53342. _this._buttonA = 0;
  53343. _this._buttonB = 0;
  53344. _this._buttonX = 0;
  53345. _this._buttonY = 0;
  53346. _this._buttonBack = 0;
  53347. _this._buttonStart = 0;
  53348. _this._buttonLB = 0;
  53349. _this._buttonRB = 0;
  53350. _this._buttonLeftStick = 0;
  53351. _this._buttonRightStick = 0;
  53352. _this._dPadUp = 0;
  53353. _this._dPadDown = 0;
  53354. _this._dPadLeft = 0;
  53355. _this._dPadRight = 0;
  53356. _this._isXboxOnePad = false;
  53357. _this.type = BABYLON.Gamepad.XBOX;
  53358. _this._isXboxOnePad = xboxOne;
  53359. return _this;
  53360. }
  53361. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  53362. this._onlefttriggerchanged = callback;
  53363. };
  53364. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  53365. this._onrighttriggerchanged = callback;
  53366. };
  53367. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  53368. get: function () {
  53369. return this._leftTrigger;
  53370. },
  53371. set: function (newValue) {
  53372. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  53373. this._onlefttriggerchanged(newValue);
  53374. }
  53375. this._leftTrigger = newValue;
  53376. },
  53377. enumerable: true,
  53378. configurable: true
  53379. });
  53380. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  53381. get: function () {
  53382. return this._rightTrigger;
  53383. },
  53384. set: function (newValue) {
  53385. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  53386. this._onrighttriggerchanged(newValue);
  53387. }
  53388. this._rightTrigger = newValue;
  53389. },
  53390. enumerable: true,
  53391. configurable: true
  53392. });
  53393. Xbox360Pad.prototype.onbuttondown = function (callback) {
  53394. this._onbuttondown = callback;
  53395. };
  53396. Xbox360Pad.prototype.onbuttonup = function (callback) {
  53397. this._onbuttonup = callback;
  53398. };
  53399. Xbox360Pad.prototype.ondpaddown = function (callback) {
  53400. this._ondpaddown = callback;
  53401. };
  53402. Xbox360Pad.prototype.ondpadup = function (callback) {
  53403. this._ondpadup = callback;
  53404. };
  53405. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  53406. if (newValue !== currentValue) {
  53407. if (newValue === 1) {
  53408. if (this._onbuttondown) {
  53409. this._onbuttondown(buttonType);
  53410. }
  53411. this.onButtonDownObservable.notifyObservers(buttonType);
  53412. }
  53413. if (newValue === 0) {
  53414. if (this._onbuttonup) {
  53415. this._onbuttonup(buttonType);
  53416. }
  53417. this.onButtonUpObservable.notifyObservers(buttonType);
  53418. }
  53419. }
  53420. return newValue;
  53421. };
  53422. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  53423. if (newValue !== currentValue) {
  53424. if (newValue === 1) {
  53425. if (this._ondpaddown) {
  53426. this._ondpaddown(buttonType);
  53427. }
  53428. this.onPadDownObservable.notifyObservers(buttonType);
  53429. }
  53430. if (newValue === 0) {
  53431. if (this._ondpadup) {
  53432. this._ondpadup(buttonType);
  53433. }
  53434. this.onPadUpObservable.notifyObservers(buttonType);
  53435. }
  53436. }
  53437. return newValue;
  53438. };
  53439. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  53440. get: function () {
  53441. return this._buttonA;
  53442. },
  53443. set: function (value) {
  53444. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  53445. },
  53446. enumerable: true,
  53447. configurable: true
  53448. });
  53449. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  53450. get: function () {
  53451. return this._buttonB;
  53452. },
  53453. set: function (value) {
  53454. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  53455. },
  53456. enumerable: true,
  53457. configurable: true
  53458. });
  53459. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  53460. get: function () {
  53461. return this._buttonX;
  53462. },
  53463. set: function (value) {
  53464. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  53465. },
  53466. enumerable: true,
  53467. configurable: true
  53468. });
  53469. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  53470. get: function () {
  53471. return this._buttonY;
  53472. },
  53473. set: function (value) {
  53474. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  53475. },
  53476. enumerable: true,
  53477. configurable: true
  53478. });
  53479. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  53480. get: function () {
  53481. return this._buttonStart;
  53482. },
  53483. set: function (value) {
  53484. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  53485. },
  53486. enumerable: true,
  53487. configurable: true
  53488. });
  53489. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  53490. get: function () {
  53491. return this._buttonBack;
  53492. },
  53493. set: function (value) {
  53494. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  53495. },
  53496. enumerable: true,
  53497. configurable: true
  53498. });
  53499. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  53500. get: function () {
  53501. return this._buttonLB;
  53502. },
  53503. set: function (value) {
  53504. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  53505. },
  53506. enumerable: true,
  53507. configurable: true
  53508. });
  53509. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  53510. get: function () {
  53511. return this._buttonRB;
  53512. },
  53513. set: function (value) {
  53514. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  53515. },
  53516. enumerable: true,
  53517. configurable: true
  53518. });
  53519. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  53520. get: function () {
  53521. return this._buttonLeftStick;
  53522. },
  53523. set: function (value) {
  53524. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  53525. },
  53526. enumerable: true,
  53527. configurable: true
  53528. });
  53529. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  53530. get: function () {
  53531. return this._buttonRightStick;
  53532. },
  53533. set: function (value) {
  53534. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  53535. },
  53536. enumerable: true,
  53537. configurable: true
  53538. });
  53539. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  53540. get: function () {
  53541. return this._dPadUp;
  53542. },
  53543. set: function (value) {
  53544. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  53545. },
  53546. enumerable: true,
  53547. configurable: true
  53548. });
  53549. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  53550. get: function () {
  53551. return this._dPadDown;
  53552. },
  53553. set: function (value) {
  53554. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  53555. },
  53556. enumerable: true,
  53557. configurable: true
  53558. });
  53559. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  53560. get: function () {
  53561. return this._dPadLeft;
  53562. },
  53563. set: function (value) {
  53564. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  53565. },
  53566. enumerable: true,
  53567. configurable: true
  53568. });
  53569. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  53570. get: function () {
  53571. return this._dPadRight;
  53572. },
  53573. set: function (value) {
  53574. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  53575. },
  53576. enumerable: true,
  53577. configurable: true
  53578. });
  53579. Xbox360Pad.prototype.update = function () {
  53580. _super.prototype.update.call(this);
  53581. if (this._isXboxOnePad) {
  53582. this.buttonA = this.browserGamepad.buttons[0].value;
  53583. this.buttonB = this.browserGamepad.buttons[1].value;
  53584. this.buttonX = this.browserGamepad.buttons[2].value;
  53585. this.buttonY = this.browserGamepad.buttons[3].value;
  53586. this.buttonLB = this.browserGamepad.buttons[4].value;
  53587. this.buttonRB = this.browserGamepad.buttons[5].value;
  53588. this.leftTrigger = this.browserGamepad.axes[2];
  53589. this.rightTrigger = this.browserGamepad.axes[5];
  53590. this.buttonBack = this.browserGamepad.buttons[9].value;
  53591. this.buttonStart = this.browserGamepad.buttons[8].value;
  53592. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  53593. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  53594. this.dPadUp = this.browserGamepad.buttons[11].value;
  53595. this.dPadDown = this.browserGamepad.buttons[12].value;
  53596. this.dPadLeft = this.browserGamepad.buttons[13].value;
  53597. this.dPadRight = this.browserGamepad.buttons[14].value;
  53598. }
  53599. else {
  53600. this.buttonA = this.browserGamepad.buttons[0].value;
  53601. this.buttonB = this.browserGamepad.buttons[1].value;
  53602. this.buttonX = this.browserGamepad.buttons[2].value;
  53603. this.buttonY = this.browserGamepad.buttons[3].value;
  53604. this.buttonLB = this.browserGamepad.buttons[4].value;
  53605. this.buttonRB = this.browserGamepad.buttons[5].value;
  53606. this.leftTrigger = this.browserGamepad.buttons[6].value;
  53607. this.rightTrigger = this.browserGamepad.buttons[7].value;
  53608. this.buttonBack = this.browserGamepad.buttons[8].value;
  53609. this.buttonStart = this.browserGamepad.buttons[9].value;
  53610. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  53611. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  53612. this.dPadUp = this.browserGamepad.buttons[12].value;
  53613. this.dPadDown = this.browserGamepad.buttons[13].value;
  53614. this.dPadLeft = this.browserGamepad.buttons[14].value;
  53615. this.dPadRight = this.browserGamepad.buttons[15].value;
  53616. }
  53617. };
  53618. return Xbox360Pad;
  53619. }(BABYLON.Gamepad));
  53620. BABYLON.Xbox360Pad = Xbox360Pad;
  53621. })(BABYLON || (BABYLON = {}));
  53622. //# sourceMappingURL=babylon.xboxGamepad.js.map
  53623. var BABYLON;
  53624. (function (BABYLON) {
  53625. var PoseEnabledControllerType;
  53626. (function (PoseEnabledControllerType) {
  53627. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  53628. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  53629. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  53630. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  53631. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  53632. var PoseEnabledControllerHelper = (function () {
  53633. function PoseEnabledControllerHelper() {
  53634. }
  53635. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  53636. // Oculus Touch
  53637. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  53638. return new BABYLON.OculusTouchController(vrGamepad);
  53639. }
  53640. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  53641. return new BABYLON.WindowsMotionController(vrGamepad);
  53642. }
  53643. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  53644. return new BABYLON.ViveController(vrGamepad);
  53645. }
  53646. else {
  53647. return new BABYLON.GenericController(vrGamepad);
  53648. }
  53649. };
  53650. return PoseEnabledControllerHelper;
  53651. }());
  53652. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  53653. var PoseEnabledController = (function (_super) {
  53654. __extends(PoseEnabledController, _super);
  53655. function PoseEnabledController(browserGamepad) {
  53656. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  53657. _this.deviceScaleFactor = 1;
  53658. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  53659. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  53660. _this.controllerType = PoseEnabledControllerType.GENERIC;
  53661. _this.position = BABYLON.Vector3.Zero();
  53662. _this.rotationQuaternion = new BABYLON.Quaternion();
  53663. _this.devicePosition = BABYLON.Vector3.Zero();
  53664. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  53665. _this._calculatedPosition = BABYLON.Vector3.Zero();
  53666. _this._calculatedRotation = new BABYLON.Quaternion();
  53667. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  53668. return _this;
  53669. }
  53670. PoseEnabledController.prototype.update = function () {
  53671. _super.prototype.update.call(this);
  53672. var pose = this.browserGamepad.pose;
  53673. this.updateFromDevice(pose);
  53674. if (this._mesh) {
  53675. this._mesh.position.copyFrom(this._calculatedPosition);
  53676. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  53677. }
  53678. };
  53679. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  53680. if (poseData) {
  53681. this.rawPose = poseData;
  53682. if (poseData.position) {
  53683. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  53684. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  53685. this.devicePosition.z *= -1;
  53686. }
  53687. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  53688. this._calculatedPosition.addInPlace(this.position);
  53689. }
  53690. if (poseData.orientation) {
  53691. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  53692. if (this._mesh) {
  53693. if (this._mesh.getScene().useRightHandedSystem) {
  53694. this.deviceRotationQuaternion.z *= -1;
  53695. this.deviceRotationQuaternion.w *= -1;
  53696. }
  53697. else {
  53698. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  53699. }
  53700. }
  53701. // if the camera is set, rotate to the camera's rotation
  53702. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  53703. }
  53704. }
  53705. };
  53706. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  53707. if (this._mesh) {
  53708. this._mesh.parent = undefined;
  53709. }
  53710. this._mesh = mesh;
  53711. if (this._poseControlledCamera) {
  53712. this._mesh.parent = this._poseControlledCamera;
  53713. }
  53714. if (!this._mesh.rotationQuaternion) {
  53715. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  53716. }
  53717. };
  53718. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  53719. this._poseControlledCamera = camera;
  53720. if (this._mesh) {
  53721. this._mesh.parent = this._poseControlledCamera;
  53722. }
  53723. };
  53724. PoseEnabledController.prototype.dispose = function () {
  53725. if (this._mesh) {
  53726. this._mesh.dispose();
  53727. }
  53728. this._mesh = undefined;
  53729. _super.prototype.dispose.call(this);
  53730. };
  53731. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  53732. get: function () {
  53733. return this._mesh;
  53734. },
  53735. enumerable: true,
  53736. configurable: true
  53737. });
  53738. PoseEnabledController.prototype.getForwardRay = function (length) {
  53739. if (length === void 0) { length = 100; }
  53740. if (!this.mesh) {
  53741. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  53742. }
  53743. var m = this.mesh.getWorldMatrix();
  53744. var origin = m.getTranslation();
  53745. var forward = new BABYLON.Vector3(0, 0, -1);
  53746. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  53747. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  53748. return new BABYLON.Ray(origin, direction, length);
  53749. };
  53750. return PoseEnabledController;
  53751. }(BABYLON.Gamepad));
  53752. BABYLON.PoseEnabledController = PoseEnabledController;
  53753. })(BABYLON || (BABYLON = {}));
  53754. //# sourceMappingURL=babylon.poseEnabledController.js.map
  53755. var BABYLON;
  53756. (function (BABYLON) {
  53757. var WebVRController = (function (_super) {
  53758. __extends(WebVRController, _super);
  53759. function WebVRController(vrGamepad) {
  53760. var _this = _super.call(this, vrGamepad) || this;
  53761. // Observables
  53762. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  53763. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  53764. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  53765. _this.onPadStateChangedObservable = new BABYLON.Observable();
  53766. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  53767. _this.pad = { x: 0, y: 0 };
  53768. // avoid GC, store state in a tmp object
  53769. _this._changes = {
  53770. pressChanged: false,
  53771. touchChanged: false,
  53772. valueChanged: false,
  53773. changed: false
  53774. };
  53775. _this._buttons = new Array(vrGamepad.buttons.length);
  53776. _this.hand = vrGamepad.hand;
  53777. return _this;
  53778. }
  53779. WebVRController.prototype.onButtonStateChange = function (callback) {
  53780. this._onButtonStateChange = callback;
  53781. };
  53782. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  53783. get: function () {
  53784. return this._defaultModel;
  53785. },
  53786. enumerable: true,
  53787. configurable: true
  53788. });
  53789. WebVRController.prototype.update = function () {
  53790. _super.prototype.update.call(this);
  53791. for (var index = 0; index < this._buttons.length; index++) {
  53792. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  53793. }
  53794. ;
  53795. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  53796. this.pad.x = this.leftStick.x;
  53797. this.pad.y = this.leftStick.y;
  53798. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  53799. }
  53800. };
  53801. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  53802. if (!newState) {
  53803. newState = {
  53804. pressed: false,
  53805. touched: false,
  53806. value: 0
  53807. };
  53808. }
  53809. if (!currentState) {
  53810. this._buttons[buttonIndex] = {
  53811. pressed: newState.pressed,
  53812. touched: newState.touched,
  53813. value: newState.value
  53814. };
  53815. return;
  53816. }
  53817. this._checkChanges(newState, currentState);
  53818. if (this._changes.changed) {
  53819. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  53820. this.handleButtonChange(buttonIndex, newState, this._changes);
  53821. }
  53822. this._buttons[buttonIndex].pressed = newState.pressed;
  53823. this._buttons[buttonIndex].touched = newState.touched;
  53824. // oculus triggers are never 0, thou not touched.
  53825. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  53826. };
  53827. WebVRController.prototype._checkChanges = function (newState, currentState) {
  53828. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  53829. this._changes.touchChanged = newState.touched !== currentState.touched;
  53830. this._changes.valueChanged = newState.value !== currentState.value;
  53831. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  53832. return this._changes;
  53833. };
  53834. WebVRController.prototype.dispose = function () {
  53835. _super.prototype.dispose.call(this);
  53836. this.onTriggerStateChangedObservable.clear();
  53837. this.onMainButtonStateChangedObservable.clear();
  53838. this.onSecondaryButtonStateChangedObservable.clear();
  53839. this.onPadStateChangedObservable.clear();
  53840. this.onPadValuesChangedObservable.clear();
  53841. };
  53842. return WebVRController;
  53843. }(BABYLON.PoseEnabledController));
  53844. BABYLON.WebVRController = WebVRController;
  53845. })(BABYLON || (BABYLON = {}));
  53846. //# sourceMappingURL=babylon.webVRController.js.map
  53847. var BABYLON;
  53848. (function (BABYLON) {
  53849. var OculusTouchController = (function (_super) {
  53850. __extends(OculusTouchController, _super);
  53851. function OculusTouchController(vrGamepad) {
  53852. var _this = _super.call(this, vrGamepad) || this;
  53853. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  53854. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  53855. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  53856. return _this;
  53857. }
  53858. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  53859. var _this = this;
  53860. var meshName;
  53861. // Hand
  53862. if (this.hand === 'left') {
  53863. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  53864. }
  53865. else {
  53866. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  53867. }
  53868. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  53869. /*
  53870. Parent Mesh name: oculus_touch_left
  53871. - body
  53872. - trigger
  53873. - thumbstick
  53874. - grip
  53875. - button_y
  53876. - button_x
  53877. - button_enter
  53878. */
  53879. _this._defaultModel = newMeshes[1];
  53880. if (meshLoaded) {
  53881. meshLoaded(_this._defaultModel);
  53882. }
  53883. _this.attachToMesh(_this._defaultModel);
  53884. });
  53885. };
  53886. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  53887. // helper getters for left and right hand.
  53888. get: function () {
  53889. if (this.hand === 'right') {
  53890. return this.onMainButtonStateChangedObservable;
  53891. }
  53892. else {
  53893. throw new Error('No A button on left hand');
  53894. }
  53895. },
  53896. enumerable: true,
  53897. configurable: true
  53898. });
  53899. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  53900. get: function () {
  53901. if (this.hand === 'right') {
  53902. return this.onSecondaryButtonStateChangedObservable;
  53903. }
  53904. else {
  53905. throw new Error('No B button on left hand');
  53906. }
  53907. },
  53908. enumerable: true,
  53909. configurable: true
  53910. });
  53911. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  53912. get: function () {
  53913. if (this.hand === 'left') {
  53914. return this.onMainButtonStateChangedObservable;
  53915. }
  53916. else {
  53917. throw new Error('No X button on right hand');
  53918. }
  53919. },
  53920. enumerable: true,
  53921. configurable: true
  53922. });
  53923. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  53924. get: function () {
  53925. if (this.hand === 'left') {
  53926. return this.onSecondaryButtonStateChangedObservable;
  53927. }
  53928. else {
  53929. throw new Error('No Y button on right hand');
  53930. }
  53931. },
  53932. enumerable: true,
  53933. configurable: true
  53934. });
  53935. /*
  53936. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  53937. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  53938. 2) secondary trigger (same)
  53939. 3) A (right) X (left), touch, pressed = value
  53940. 4) B / Y
  53941. 5) thumb rest
  53942. */
  53943. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  53944. var notifyObject = state; //{ state: state, changes: changes };
  53945. var triggerDirection = this.hand === 'right' ? -1 : 1;
  53946. switch (buttonIdx) {
  53947. case 0:
  53948. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  53949. return;
  53950. case 1:// index trigger
  53951. if (this._defaultModel) {
  53952. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  53953. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  53954. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  53955. }
  53956. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  53957. return;
  53958. case 2:// secondary trigger
  53959. if (this._defaultModel) {
  53960. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  53961. }
  53962. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  53963. return;
  53964. case 3:
  53965. if (this._defaultModel) {
  53966. if (notifyObject.pressed) {
  53967. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  53968. }
  53969. else {
  53970. (this._defaultModel.getChildren()[1]).position.y = 0;
  53971. }
  53972. }
  53973. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  53974. return;
  53975. case 4:
  53976. if (this._defaultModel) {
  53977. if (notifyObject.pressed) {
  53978. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  53979. }
  53980. else {
  53981. (this._defaultModel.getChildren()[2]).position.y = 0;
  53982. }
  53983. }
  53984. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  53985. return;
  53986. case 5:
  53987. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  53988. return;
  53989. }
  53990. };
  53991. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  53992. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  53993. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  53994. return OculusTouchController;
  53995. }(BABYLON.WebVRController));
  53996. BABYLON.OculusTouchController = OculusTouchController;
  53997. })(BABYLON || (BABYLON = {}));
  53998. //# sourceMappingURL=babylon.oculusTouchController.js.map
  53999. var BABYLON;
  54000. (function (BABYLON) {
  54001. var ViveController = (function (_super) {
  54002. __extends(ViveController, _super);
  54003. function ViveController(vrGamepad) {
  54004. var _this = _super.call(this, vrGamepad) || this;
  54005. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  54006. return _this;
  54007. }
  54008. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  54009. var _this = this;
  54010. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  54011. /*
  54012. Parent Mesh name: ViveWand
  54013. - body
  54014. - r_gripper
  54015. - l_gripper
  54016. - menu_button
  54017. - system_button
  54018. - trackpad
  54019. - trigger
  54020. - LED
  54021. */
  54022. _this._defaultModel = newMeshes[1];
  54023. if (meshLoaded) {
  54024. meshLoaded(_this._defaultModel);
  54025. }
  54026. _this.attachToMesh(_this._defaultModel);
  54027. });
  54028. };
  54029. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  54030. get: function () {
  54031. return this.onMainButtonStateChangedObservable;
  54032. },
  54033. enumerable: true,
  54034. configurable: true
  54035. });
  54036. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  54037. get: function () {
  54038. return this.onMainButtonStateChangedObservable;
  54039. },
  54040. enumerable: true,
  54041. configurable: true
  54042. });
  54043. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  54044. get: function () {
  54045. return this.onSecondaryButtonStateChangedObservable;
  54046. },
  54047. enumerable: true,
  54048. configurable: true
  54049. });
  54050. /**
  54051. * Vive mapping:
  54052. * 0: touchpad
  54053. * 1: trigger
  54054. * 2: left AND right buttons
  54055. * 3: menu button
  54056. */
  54057. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  54058. var notifyObject = state; //{ state: state, changes: changes };
  54059. switch (buttonIdx) {
  54060. case 0:
  54061. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  54062. return;
  54063. case 1:// index trigger
  54064. if (this._defaultModel) {
  54065. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  54066. }
  54067. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  54068. return;
  54069. case 2:// left AND right button
  54070. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  54071. return;
  54072. case 3:
  54073. if (this._defaultModel) {
  54074. if (notifyObject.pressed) {
  54075. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  54076. }
  54077. else {
  54078. (this._defaultModel.getChildren()[2]).position.y = 0;
  54079. }
  54080. }
  54081. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  54082. return;
  54083. }
  54084. };
  54085. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  54086. ViveController.MODEL_FILENAME = 'wand.babylon';
  54087. return ViveController;
  54088. }(BABYLON.WebVRController));
  54089. BABYLON.ViveController = ViveController;
  54090. })(BABYLON || (BABYLON = {}));
  54091. //# sourceMappingURL=babylon.viveController.js.map
  54092. var BABYLON;
  54093. (function (BABYLON) {
  54094. var GenericController = (function (_super) {
  54095. __extends(GenericController, _super);
  54096. function GenericController(vrGamepad) {
  54097. return _super.call(this, vrGamepad) || this;
  54098. }
  54099. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  54100. var _this = this;
  54101. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  54102. _this._defaultModel = newMeshes[1];
  54103. if (meshLoaded) {
  54104. meshLoaded(_this._defaultModel);
  54105. }
  54106. _this.attachToMesh(_this._defaultModel);
  54107. });
  54108. };
  54109. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  54110. console.log("Button id: " + buttonIdx + "state: ");
  54111. console.dir(state);
  54112. };
  54113. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  54114. GenericController.MODEL_FILENAME = 'generic.babylon';
  54115. return GenericController;
  54116. }(BABYLON.WebVRController));
  54117. BABYLON.GenericController = GenericController;
  54118. })(BABYLON || (BABYLON = {}));
  54119. //# sourceMappingURL=babylon.genericController.js.map
  54120. var BABYLON;
  54121. (function (BABYLON) {
  54122. var LoadedMeshInfo = (function () {
  54123. function LoadedMeshInfo() {
  54124. this.buttonMeshes = {};
  54125. this.axisMeshes = {};
  54126. }
  54127. return LoadedMeshInfo;
  54128. }());
  54129. var WindowsMotionController = (function (_super) {
  54130. __extends(WindowsMotionController, _super);
  54131. function WindowsMotionController(vrGamepad) {
  54132. var _this = _super.call(this, vrGamepad) || this;
  54133. _this._mapping = {
  54134. // Semantic button names
  54135. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  54136. // A mapping of the button name to glTF model node name
  54137. // that should be transformed by button value.
  54138. buttonMeshNames: {
  54139. 'trigger': 'SELECT',
  54140. 'menu': 'MENU',
  54141. 'grip': 'GRASP',
  54142. 'thumbstick': 'THUMBSTICK_PRESS',
  54143. 'trackpad': 'TOUCHPAD_PRESS'
  54144. },
  54145. // This mapping is used to translate from the Motion Controller to Babylon semantics
  54146. buttonObservableNames: {
  54147. 'trigger': 'onTriggerStateChangedObservable',
  54148. 'menu': 'onSecondaryButtonStateChangedObservable',
  54149. 'grip': 'onMainButtonStateChangedObservable',
  54150. 'thumbstick': 'onPadStateChangedObservable',
  54151. 'trackpad': 'onTrackpadChangedObservable'
  54152. },
  54153. // A mapping of the axis name to glTF model node name
  54154. // that should be transformed by axis value.
  54155. // This array mirrors the browserGamepad.axes array, such that
  54156. // the mesh corresponding to axis 0 is in this array index 0.
  54157. axisMeshNames: [
  54158. 'THUMBSTICK_X',
  54159. 'THUMBSTICK_Y',
  54160. 'TOUCHPAD_TOUCH_X',
  54161. 'TOUCHPAD_TOUCH_Y'
  54162. ],
  54163. pointingPoseMeshName: 'POINTING_POSE'
  54164. };
  54165. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  54166. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  54167. _this._loadedMeshInfo = null;
  54168. return _this;
  54169. }
  54170. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  54171. get: function () {
  54172. return this.onTriggerStateChangedObservable;
  54173. },
  54174. enumerable: true,
  54175. configurable: true
  54176. });
  54177. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  54178. get: function () {
  54179. return this.onSecondaryButtonStateChangedObservable;
  54180. },
  54181. enumerable: true,
  54182. configurable: true
  54183. });
  54184. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  54185. get: function () {
  54186. return this.onMainButtonStateChangedObservable;
  54187. },
  54188. enumerable: true,
  54189. configurable: true
  54190. });
  54191. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  54192. get: function () {
  54193. return this.onPadStateChangedObservable;
  54194. },
  54195. enumerable: true,
  54196. configurable: true
  54197. });
  54198. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  54199. get: function () {
  54200. return this.onTrackpadChangedObservable;
  54201. },
  54202. enumerable: true,
  54203. configurable: true
  54204. });
  54205. /**
  54206. * Called once per frame by the engine.
  54207. */
  54208. WindowsMotionController.prototype.update = function () {
  54209. _super.prototype.update.call(this);
  54210. // Only need to animate axes if there is a loaded mesh
  54211. if (this._loadedMeshInfo) {
  54212. if (this.browserGamepad.axes) {
  54213. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  54214. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  54215. }
  54216. }
  54217. }
  54218. };
  54219. /**
  54220. * Called once for each button that changed state since the last frame
  54221. * @param buttonIdx Which button index changed
  54222. * @param state New state of the button
  54223. * @param changes Which properties on the state changed since last frame
  54224. */
  54225. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  54226. var buttonName = this._mapping.buttons[buttonIdx];
  54227. if (!buttonName) {
  54228. return;
  54229. }
  54230. // Only emit events for buttons that we know how to map from index to name
  54231. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  54232. if (observable) {
  54233. observable.notifyObservers(state);
  54234. }
  54235. this.lerpButtonTransform(buttonName, state.value);
  54236. };
  54237. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  54238. // If there is no loaded mesh, there is nothing to transform.
  54239. if (!this._loadedMeshInfo) {
  54240. return;
  54241. }
  54242. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  54243. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  54244. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  54245. };
  54246. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  54247. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  54248. if (!meshInfo) {
  54249. return;
  54250. }
  54251. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  54252. var lerpValue = axisValue * 0.5 + 0.5;
  54253. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  54254. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  54255. };
  54256. /**
  54257. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  54258. * @param scene scene in which to add meshes
  54259. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  54260. */
  54261. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  54262. var _this = this;
  54263. if (forceDefault === void 0) { forceDefault = false; }
  54264. var path;
  54265. var filename;
  54266. // Checking if GLB loader is present
  54267. if (BABYLON.SceneLoader.GetPluginForExtension("glb")) {
  54268. // Determine the device specific folder based on the ID suffix
  54269. var device = 'default';
  54270. if (this.id && !forceDefault) {
  54271. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  54272. device = ((match && match[0]) || device);
  54273. }
  54274. // Hand
  54275. if (this.hand === 'left') {
  54276. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  54277. }
  54278. else {
  54279. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  54280. }
  54281. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  54282. }
  54283. else {
  54284. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  54285. path = BABYLON.GenericController.MODEL_BASE_URL;
  54286. filename = BABYLON.GenericController.MODEL_FILENAME;
  54287. }
  54288. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  54289. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  54290. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  54291. if (!_this._loadedMeshInfo) {
  54292. return;
  54293. }
  54294. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  54295. _this.attachToMesh(_this._defaultModel);
  54296. if (meshLoaded) {
  54297. meshLoaded(_this._defaultModel);
  54298. }
  54299. }, null, function (scene, message) {
  54300. BABYLON.Tools.Log(message);
  54301. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  54302. if (!forceDefault) {
  54303. _this.initControllerMesh(scene, meshLoaded, true);
  54304. }
  54305. });
  54306. };
  54307. /**
  54308. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  54309. * can be transformed by button presses and axes values, based on this._mapping.
  54310. *
  54311. * @param scene scene in which the meshes exist
  54312. * @param meshes list of meshes that make up the controller model to process
  54313. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  54314. */
  54315. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  54316. var loadedMeshInfo = null;
  54317. // Create a new mesh to contain the glTF hierarchy
  54318. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  54319. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  54320. var childMesh = null;
  54321. for (var i = 0; i < meshes.length; i++) {
  54322. var mesh = meshes[i];
  54323. if (!mesh.parent) {
  54324. // Exclude controller meshes from picking results
  54325. mesh.isPickable = false;
  54326. // Handle root node, attach to the new parentMesh
  54327. childMesh = mesh;
  54328. break;
  54329. }
  54330. }
  54331. if (childMesh) {
  54332. childMesh.setParent(parentMesh);
  54333. // Create our mesh info. Note that this method will always return non-null.
  54334. loadedMeshInfo = this.createMeshInfo(parentMesh);
  54335. }
  54336. else {
  54337. BABYLON.Tools.Warn('Could not find root node in model file.');
  54338. }
  54339. return loadedMeshInfo;
  54340. };
  54341. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  54342. var loadedMeshInfo = new LoadedMeshInfo();
  54343. var i;
  54344. loadedMeshInfo.rootNode = rootNode;
  54345. // Reset the caches
  54346. loadedMeshInfo.buttonMeshes = {};
  54347. loadedMeshInfo.axisMeshes = {};
  54348. // Button Meshes
  54349. for (i = 0; i < this._mapping.buttons.length; i++) {
  54350. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  54351. if (!buttonMeshName) {
  54352. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  54353. continue;
  54354. }
  54355. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  54356. if (!buttonMesh) {
  54357. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  54358. continue;
  54359. }
  54360. var buttonMeshInfo = {
  54361. index: i,
  54362. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  54363. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  54364. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  54365. };
  54366. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  54367. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  54368. }
  54369. else {
  54370. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  54371. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  54372. '(VALUE: ' + !!buttonMeshInfo.value +
  54373. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  54374. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  54375. ')');
  54376. }
  54377. }
  54378. // Axis Meshes
  54379. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  54380. var axisMeshName = this._mapping.axisMeshNames[i];
  54381. if (!axisMeshName) {
  54382. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  54383. continue;
  54384. }
  54385. var axisMesh = getChildByName(rootNode, axisMeshName);
  54386. if (!axisMesh) {
  54387. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  54388. continue;
  54389. }
  54390. var axisMeshInfo = {
  54391. index: i,
  54392. value: getImmediateChildByName(axisMesh, 'VALUE'),
  54393. min: getImmediateChildByName(axisMesh, 'MIN'),
  54394. max: getImmediateChildByName(axisMesh, 'MAX')
  54395. };
  54396. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  54397. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  54398. }
  54399. else {
  54400. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  54401. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  54402. '(VALUE: ' + !!axisMeshInfo.value +
  54403. ', MIN: ' + !!axisMeshInfo.min +
  54404. ', MAX:' + !!axisMeshInfo.max +
  54405. ')');
  54406. }
  54407. }
  54408. // Pointing Ray
  54409. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  54410. if (!loadedMeshInfo.pointingPoseNode) {
  54411. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  54412. }
  54413. return loadedMeshInfo;
  54414. // Look through all children recursively. This will return null if no mesh exists with the given name.
  54415. function getChildByName(node, name) {
  54416. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  54417. }
  54418. // Look through only immediate children. This will return null if no mesh exists with the given name.
  54419. function getImmediateChildByName(node, name) {
  54420. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  54421. }
  54422. };
  54423. WindowsMotionController.prototype.getForwardRay = function (length) {
  54424. if (length === void 0) { length = 100; }
  54425. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  54426. return _super.prototype.getForwardRay.call(this, length);
  54427. }
  54428. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  54429. var origin = m.getTranslation();
  54430. var forward = new BABYLON.Vector3(0, 0, -1);
  54431. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  54432. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  54433. return new BABYLON.Ray(origin, direction, length);
  54434. };
  54435. WindowsMotionController.prototype.dispose = function () {
  54436. _super.prototype.dispose.call(this);
  54437. this.onTrackpadChangedObservable.clear();
  54438. };
  54439. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  54440. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  54441. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  54442. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  54443. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  54444. return WindowsMotionController;
  54445. }(BABYLON.WebVRController));
  54446. BABYLON.WindowsMotionController = WindowsMotionController;
  54447. })(BABYLON || (BABYLON = {}));
  54448. //# sourceMappingURL=babylon.windowsMotionController.js.map
  54449. /// <reference path="babylon.targetCamera.ts" />
  54450. var BABYLON;
  54451. (function (BABYLON) {
  54452. var FollowCamera = (function (_super) {
  54453. __extends(FollowCamera, _super);
  54454. function FollowCamera(name, position, scene, lockedTarget) {
  54455. var _this = _super.call(this, name, position, scene) || this;
  54456. _this.radius = 12;
  54457. _this.rotationOffset = 0;
  54458. _this.heightOffset = 4;
  54459. _this.cameraAcceleration = 0.05;
  54460. _this.maxCameraSpeed = 20;
  54461. _this.lockedTarget = lockedTarget;
  54462. return _this;
  54463. }
  54464. FollowCamera.prototype.getRadians = function (degrees) {
  54465. return degrees * Math.PI / 180;
  54466. };
  54467. FollowCamera.prototype.follow = function (cameraTarget) {
  54468. if (!cameraTarget)
  54469. return;
  54470. var yRotation;
  54471. if (cameraTarget.rotationQuaternion) {
  54472. var rotMatrix = new BABYLON.Matrix();
  54473. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  54474. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  54475. }
  54476. else {
  54477. yRotation = cameraTarget.rotation.y;
  54478. }
  54479. var radians = this.getRadians(this.rotationOffset) + yRotation;
  54480. var targetPosition = cameraTarget.getAbsolutePosition();
  54481. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  54482. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  54483. var dx = targetX - this.position.x;
  54484. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  54485. var dz = (targetZ) - this.position.z;
  54486. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  54487. var vy = dy * this.cameraAcceleration;
  54488. var vz = dz * this.cameraAcceleration * 2;
  54489. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  54490. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  54491. }
  54492. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  54493. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  54494. }
  54495. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  54496. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  54497. }
  54498. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  54499. this.setTarget(targetPosition);
  54500. };
  54501. FollowCamera.prototype._checkInputs = function () {
  54502. _super.prototype._checkInputs.call(this);
  54503. this.follow(this.lockedTarget);
  54504. };
  54505. FollowCamera.prototype.getClassName = function () {
  54506. return "FollowCamera";
  54507. };
  54508. __decorate([
  54509. BABYLON.serialize()
  54510. ], FollowCamera.prototype, "radius", void 0);
  54511. __decorate([
  54512. BABYLON.serialize()
  54513. ], FollowCamera.prototype, "rotationOffset", void 0);
  54514. __decorate([
  54515. BABYLON.serialize()
  54516. ], FollowCamera.prototype, "heightOffset", void 0);
  54517. __decorate([
  54518. BABYLON.serialize()
  54519. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  54520. __decorate([
  54521. BABYLON.serialize()
  54522. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  54523. __decorate([
  54524. BABYLON.serializeAsMeshReference("lockedTargetId")
  54525. ], FollowCamera.prototype, "lockedTarget", void 0);
  54526. return FollowCamera;
  54527. }(BABYLON.TargetCamera));
  54528. BABYLON.FollowCamera = FollowCamera;
  54529. var ArcFollowCamera = (function (_super) {
  54530. __extends(ArcFollowCamera, _super);
  54531. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  54532. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  54533. _this.alpha = alpha;
  54534. _this.beta = beta;
  54535. _this.radius = radius;
  54536. _this.target = target;
  54537. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  54538. _this.follow();
  54539. return _this;
  54540. }
  54541. ArcFollowCamera.prototype.follow = function () {
  54542. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  54543. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  54544. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  54545. var targetPosition = this.target.getAbsolutePosition();
  54546. this.position = targetPosition.add(this._cartesianCoordinates);
  54547. this.setTarget(targetPosition);
  54548. };
  54549. ArcFollowCamera.prototype._checkInputs = function () {
  54550. _super.prototype._checkInputs.call(this);
  54551. this.follow();
  54552. };
  54553. ArcFollowCamera.prototype.getClassName = function () {
  54554. return "ArcFollowCamera";
  54555. };
  54556. return ArcFollowCamera;
  54557. }(BABYLON.TargetCamera));
  54558. BABYLON.ArcFollowCamera = ArcFollowCamera;
  54559. })(BABYLON || (BABYLON = {}));
  54560. //# sourceMappingURL=babylon.followCamera.js.map
  54561. /// <reference path="babylon.touchCamera.ts" />
  54562. var BABYLON;
  54563. (function (BABYLON) {
  54564. // We're mainly based on the logic defined into the FreeCamera code
  54565. var UniversalCamera = (function (_super) {
  54566. __extends(UniversalCamera, _super);
  54567. //-- end properties for backward compatibility for inputs
  54568. function UniversalCamera(name, position, scene) {
  54569. var _this = _super.call(this, name, position, scene) || this;
  54570. _this.inputs.addGamepad();
  54571. return _this;
  54572. }
  54573. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  54574. //-- Begin properties for backward compatibility for inputs
  54575. get: function () {
  54576. var gamepad = this.inputs.attached["gamepad"];
  54577. if (gamepad)
  54578. return gamepad.gamepadAngularSensibility;
  54579. },
  54580. set: function (value) {
  54581. var gamepad = this.inputs.attached["gamepad"];
  54582. if (gamepad)
  54583. gamepad.gamepadAngularSensibility = value;
  54584. },
  54585. enumerable: true,
  54586. configurable: true
  54587. });
  54588. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  54589. get: function () {
  54590. var gamepad = this.inputs.attached["gamepad"];
  54591. if (gamepad)
  54592. return gamepad.gamepadMoveSensibility;
  54593. },
  54594. set: function (value) {
  54595. var gamepad = this.inputs.attached["gamepad"];
  54596. if (gamepad)
  54597. gamepad.gamepadMoveSensibility = value;
  54598. },
  54599. enumerable: true,
  54600. configurable: true
  54601. });
  54602. UniversalCamera.prototype.getClassName = function () {
  54603. return "UniversalCamera";
  54604. };
  54605. return UniversalCamera;
  54606. }(BABYLON.TouchCamera));
  54607. BABYLON.UniversalCamera = UniversalCamera;
  54608. })(BABYLON || (BABYLON = {}));
  54609. //# sourceMappingURL=babylon.universalCamera.js.map
  54610. /// <reference path="babylon.universalCamera.ts" />
  54611. var BABYLON;
  54612. (function (BABYLON) {
  54613. // We're mainly based on the logic defined into the FreeCamera code
  54614. var GamepadCamera = (function (_super) {
  54615. __extends(GamepadCamera, _super);
  54616. //-- end properties for backward compatibility for inputs
  54617. function GamepadCamera(name, position, scene) {
  54618. return _super.call(this, name, position, scene) || this;
  54619. }
  54620. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  54621. //-- Begin properties for backward compatibility for inputs
  54622. get: function () {
  54623. var gamepad = this.inputs.attached["gamepad"];
  54624. if (gamepad)
  54625. return gamepad.gamepadAngularSensibility;
  54626. },
  54627. set: function (value) {
  54628. var gamepad = this.inputs.attached["gamepad"];
  54629. if (gamepad)
  54630. gamepad.gamepadAngularSensibility = value;
  54631. },
  54632. enumerable: true,
  54633. configurable: true
  54634. });
  54635. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  54636. get: function () {
  54637. var gamepad = this.inputs.attached["gamepad"];
  54638. if (gamepad)
  54639. return gamepad.gamepadMoveSensibility;
  54640. },
  54641. set: function (value) {
  54642. var gamepad = this.inputs.attached["gamepad"];
  54643. if (gamepad)
  54644. gamepad.gamepadMoveSensibility = value;
  54645. },
  54646. enumerable: true,
  54647. configurable: true
  54648. });
  54649. GamepadCamera.prototype.getClassName = function () {
  54650. return "GamepadCamera";
  54651. };
  54652. return GamepadCamera;
  54653. }(BABYLON.UniversalCamera));
  54654. BABYLON.GamepadCamera = GamepadCamera;
  54655. })(BABYLON || (BABYLON = {}));
  54656. //# sourceMappingURL=babylon.gamepadCamera.js.map
  54657. var BABYLON;
  54658. (function (BABYLON) {
  54659. var PostProcessRenderPipelineManager = (function () {
  54660. function PostProcessRenderPipelineManager() {
  54661. this._renderPipelines = {};
  54662. }
  54663. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  54664. this._renderPipelines[renderPipeline._name] = renderPipeline;
  54665. };
  54666. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  54667. var renderPipeline = this._renderPipelines[renderPipelineName];
  54668. if (!renderPipeline) {
  54669. return;
  54670. }
  54671. renderPipeline._attachCameras(cameras, unique);
  54672. };
  54673. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  54674. var renderPipeline = this._renderPipelines[renderPipelineName];
  54675. if (!renderPipeline) {
  54676. return;
  54677. }
  54678. renderPipeline._detachCameras(cameras);
  54679. };
  54680. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  54681. var renderPipeline = this._renderPipelines[renderPipelineName];
  54682. if (!renderPipeline) {
  54683. return;
  54684. }
  54685. renderPipeline._enableEffect(renderEffectName, cameras);
  54686. };
  54687. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  54688. var renderPipeline = this._renderPipelines[renderPipelineName];
  54689. if (!renderPipeline) {
  54690. return;
  54691. }
  54692. renderPipeline._disableEffect(renderEffectName, cameras);
  54693. };
  54694. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  54695. var renderPipeline = this._renderPipelines[renderPipelineName];
  54696. if (!renderPipeline) {
  54697. return;
  54698. }
  54699. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  54700. };
  54701. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  54702. var renderPipeline = this._renderPipelines[renderPipelineName];
  54703. if (!renderPipeline) {
  54704. return;
  54705. }
  54706. renderPipeline._disableDisplayOnlyPass(cameras);
  54707. };
  54708. PostProcessRenderPipelineManager.prototype.update = function () {
  54709. for (var renderPipelineName in this._renderPipelines) {
  54710. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  54711. var pipeline = this._renderPipelines[renderPipelineName];
  54712. if (!pipeline.isSupported) {
  54713. pipeline.dispose();
  54714. delete this._renderPipelines[renderPipelineName];
  54715. }
  54716. else {
  54717. pipeline._update();
  54718. }
  54719. }
  54720. }
  54721. };
  54722. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  54723. for (var renderPipelineName in this._renderPipelines) {
  54724. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  54725. var pipeline = this._renderPipelines[renderPipelineName];
  54726. pipeline._rebuild();
  54727. }
  54728. }
  54729. };
  54730. PostProcessRenderPipelineManager.prototype.dispose = function () {
  54731. for (var renderPipelineName in this._renderPipelines) {
  54732. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  54733. var pipeline = this._renderPipelines[renderPipelineName];
  54734. pipeline.dispose();
  54735. }
  54736. }
  54737. };
  54738. return PostProcessRenderPipelineManager;
  54739. }());
  54740. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  54741. })(BABYLON || (BABYLON = {}));
  54742. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  54743. var BABYLON;
  54744. (function (BABYLON) {
  54745. var PostProcessRenderPass = (function () {
  54746. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  54747. this._enabled = true;
  54748. this._refCount = 0;
  54749. this._name = name;
  54750. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  54751. this.setRenderList(renderList);
  54752. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  54753. this._renderTexture.onAfterRenderObservable.add(afterRender);
  54754. this._scene = scene;
  54755. this._renderList = renderList;
  54756. }
  54757. // private
  54758. PostProcessRenderPass.prototype._incRefCount = function () {
  54759. if (this._refCount === 0) {
  54760. this._scene.customRenderTargets.push(this._renderTexture);
  54761. }
  54762. return ++this._refCount;
  54763. };
  54764. PostProcessRenderPass.prototype._decRefCount = function () {
  54765. this._refCount--;
  54766. if (this._refCount <= 0) {
  54767. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  54768. }
  54769. return this._refCount;
  54770. };
  54771. PostProcessRenderPass.prototype._update = function () {
  54772. this.setRenderList(this._renderList);
  54773. };
  54774. // public
  54775. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  54776. this._renderTexture.renderList = renderList;
  54777. };
  54778. PostProcessRenderPass.prototype.getRenderTexture = function () {
  54779. return this._renderTexture;
  54780. };
  54781. return PostProcessRenderPass;
  54782. }());
  54783. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  54784. })(BABYLON || (BABYLON = {}));
  54785. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  54786. var BABYLON;
  54787. (function (BABYLON) {
  54788. var PostProcessRenderEffect = (function () {
  54789. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  54790. this._engine = engine;
  54791. this._name = name;
  54792. this._singleInstance = singleInstance || true;
  54793. this._getPostProcess = getPostProcess;
  54794. this._cameras = [];
  54795. this._indicesForCamera = [];
  54796. this._postProcesses = {};
  54797. this._renderPasses = {};
  54798. this._renderEffectAsPasses = {};
  54799. }
  54800. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  54801. get: function () {
  54802. for (var index in this._postProcesses) {
  54803. if (!this._postProcesses[index].isSupported) {
  54804. return false;
  54805. }
  54806. }
  54807. return true;
  54808. },
  54809. enumerable: true,
  54810. configurable: true
  54811. });
  54812. PostProcessRenderEffect.prototype._update = function () {
  54813. for (var renderPassName in this._renderPasses) {
  54814. this._renderPasses[renderPassName]._update();
  54815. }
  54816. };
  54817. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  54818. this._renderPasses[renderPass._name] = renderPass;
  54819. this._linkParameters();
  54820. };
  54821. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  54822. delete this._renderPasses[renderPass._name];
  54823. this._linkParameters();
  54824. };
  54825. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  54826. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  54827. this._linkParameters();
  54828. };
  54829. PostProcessRenderEffect.prototype.getPass = function (passName) {
  54830. for (var renderPassName in this._renderPasses) {
  54831. if (renderPassName === passName) {
  54832. return this._renderPasses[passName];
  54833. }
  54834. }
  54835. };
  54836. PostProcessRenderEffect.prototype.emptyPasses = function () {
  54837. this._renderPasses = {};
  54838. this._linkParameters();
  54839. };
  54840. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  54841. var cameraKey;
  54842. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  54843. for (var i = 0; i < _cam.length; i++) {
  54844. var camera = _cam[i];
  54845. var cameraName = camera.name;
  54846. if (this._singleInstance) {
  54847. cameraKey = 0;
  54848. }
  54849. else {
  54850. cameraKey = cameraName;
  54851. }
  54852. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  54853. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  54854. if (!this._indicesForCamera[cameraName]) {
  54855. this._indicesForCamera[cameraName] = [];
  54856. }
  54857. this._indicesForCamera[cameraName].push(index);
  54858. if (this._cameras.indexOf(camera) === -1) {
  54859. this._cameras[cameraName] = camera;
  54860. }
  54861. for (var passName in this._renderPasses) {
  54862. this._renderPasses[passName]._incRefCount();
  54863. }
  54864. }
  54865. this._linkParameters();
  54866. };
  54867. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  54868. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  54869. for (var i = 0; i < _cam.length; i++) {
  54870. var camera = _cam[i];
  54871. var cameraName = camera.name;
  54872. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  54873. var index = this._cameras.indexOf(cameraName);
  54874. this._indicesForCamera.splice(index, 1);
  54875. this._cameras.splice(index, 1);
  54876. for (var passName in this._renderPasses) {
  54877. this._renderPasses[passName]._decRefCount();
  54878. }
  54879. }
  54880. };
  54881. PostProcessRenderEffect.prototype._enable = function (cameras) {
  54882. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  54883. for (var i = 0; i < _cam.length; i++) {
  54884. var camera = _cam[i];
  54885. var cameraName = camera.name;
  54886. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  54887. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  54888. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  54889. }
  54890. }
  54891. for (var passName in this._renderPasses) {
  54892. this._renderPasses[passName]._incRefCount();
  54893. }
  54894. }
  54895. };
  54896. PostProcessRenderEffect.prototype._disable = function (cameras) {
  54897. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  54898. for (var i = 0; i < _cam.length; i++) {
  54899. var camera = _cam[i];
  54900. var cameraName = camera.Name;
  54901. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  54902. for (var passName in this._renderPasses) {
  54903. this._renderPasses[passName]._decRefCount();
  54904. }
  54905. }
  54906. };
  54907. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  54908. if (this._singleInstance) {
  54909. return this._postProcesses[0];
  54910. }
  54911. else {
  54912. return this._postProcesses[camera.name];
  54913. }
  54914. };
  54915. PostProcessRenderEffect.prototype._linkParameters = function () {
  54916. var _this = this;
  54917. for (var index in this._postProcesses) {
  54918. if (this.applyParameters) {
  54919. this.applyParameters(this._postProcesses[index]);
  54920. }
  54921. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  54922. _this._linkTextures(effect);
  54923. });
  54924. }
  54925. };
  54926. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  54927. for (var renderPassName in this._renderPasses) {
  54928. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  54929. }
  54930. for (var renderEffectName in this._renderEffectAsPasses) {
  54931. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  54932. }
  54933. };
  54934. return PostProcessRenderEffect;
  54935. }());
  54936. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  54937. })(BABYLON || (BABYLON = {}));
  54938. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  54939. var BABYLON;
  54940. (function (BABYLON) {
  54941. var PostProcessRenderPipeline = (function () {
  54942. function PostProcessRenderPipeline(engine, name) {
  54943. this._engine = engine;
  54944. this._name = name;
  54945. this._renderEffects = new Array();
  54946. this._renderEffectsForIsolatedPass = new Array();
  54947. this._cameras = [];
  54948. }
  54949. PostProcessRenderPipeline.prototype.getClassName = function () {
  54950. return "PostProcessRenderPipeline";
  54951. };
  54952. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  54953. get: function () {
  54954. for (var renderEffectName in this._renderEffects) {
  54955. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  54956. if (!this._renderEffects[renderEffectName].isSupported) {
  54957. return false;
  54958. }
  54959. }
  54960. }
  54961. return true;
  54962. },
  54963. enumerable: true,
  54964. configurable: true
  54965. });
  54966. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  54967. this._renderEffects[renderEffect._name] = renderEffect;
  54968. };
  54969. // private
  54970. PostProcessRenderPipeline.prototype._rebuild = function () {
  54971. };
  54972. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  54973. var renderEffects = this._renderEffects[renderEffectName];
  54974. if (!renderEffects) {
  54975. return;
  54976. }
  54977. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  54978. };
  54979. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  54980. var renderEffects = this._renderEffects[renderEffectName];
  54981. if (!renderEffects) {
  54982. return;
  54983. }
  54984. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  54985. };
  54986. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  54987. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  54988. var indicesToDelete = [];
  54989. var i;
  54990. for (i = 0; i < _cam.length; i++) {
  54991. var camera = _cam[i];
  54992. var cameraName = camera.name;
  54993. if (this._cameras.indexOf(camera) === -1) {
  54994. this._cameras[cameraName] = camera;
  54995. }
  54996. else if (unique) {
  54997. indicesToDelete.push(i);
  54998. }
  54999. }
  55000. for (i = 0; i < indicesToDelete.length; i++) {
  55001. cameras.splice(indicesToDelete[i], 1);
  55002. }
  55003. for (var renderEffectName in this._renderEffects) {
  55004. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  55005. this._renderEffects[renderEffectName]._attachCameras(_cam);
  55006. }
  55007. }
  55008. };
  55009. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  55010. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  55011. for (var renderEffectName in this._renderEffects) {
  55012. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  55013. this._renderEffects[renderEffectName]._detachCameras(_cam);
  55014. }
  55015. }
  55016. for (var i = 0; i < _cam.length; i++) {
  55017. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  55018. }
  55019. };
  55020. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  55021. var _this = this;
  55022. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  55023. var pass = null;
  55024. var renderEffectName;
  55025. for (renderEffectName in this._renderEffects) {
  55026. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  55027. pass = this._renderEffects[renderEffectName].getPass(passName);
  55028. if (pass != null) {
  55029. break;
  55030. }
  55031. }
  55032. }
  55033. if (pass === null) {
  55034. return;
  55035. }
  55036. for (renderEffectName in this._renderEffects) {
  55037. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  55038. this._renderEffects[renderEffectName]._disable(_cam);
  55039. }
  55040. }
  55041. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  55042. for (var i = 0; i < _cam.length; i++) {
  55043. var camera = _cam[i];
  55044. var cameraName = camera.name;
  55045. 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); });
  55046. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  55047. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  55048. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  55049. }
  55050. };
  55051. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  55052. var _this = this;
  55053. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  55054. for (var i = 0; i < _cam.length; i++) {
  55055. var camera = _cam[i];
  55056. var cameraName = camera.name;
  55057. 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); });
  55058. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  55059. }
  55060. for (var renderEffectName in this._renderEffects) {
  55061. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  55062. this._renderEffects[renderEffectName]._enable(_cam);
  55063. }
  55064. }
  55065. };
  55066. PostProcessRenderPipeline.prototype._update = function () {
  55067. for (var renderEffectName in this._renderEffects) {
  55068. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  55069. this._renderEffects[renderEffectName]._update();
  55070. }
  55071. }
  55072. for (var i = 0; i < this._cameras.length; i++) {
  55073. var cameraName = this._cameras[i].name;
  55074. if (this._renderEffectsForIsolatedPass[cameraName]) {
  55075. this._renderEffectsForIsolatedPass[cameraName]._update();
  55076. }
  55077. }
  55078. };
  55079. PostProcessRenderPipeline.prototype._reset = function () {
  55080. this._renderEffects = new Array();
  55081. this._renderEffectsForIsolatedPass = new Array();
  55082. };
  55083. PostProcessRenderPipeline.prototype.dispose = function () {
  55084. // Must be implemented by children
  55085. };
  55086. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  55087. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  55088. __decorate([
  55089. BABYLON.serialize()
  55090. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  55091. return PostProcessRenderPipeline;
  55092. }());
  55093. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  55094. })(BABYLON || (BABYLON = {}));
  55095. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  55096. var BABYLON;
  55097. (function (BABYLON) {
  55098. var DepthRenderer = (function () {
  55099. function DepthRenderer(scene, type) {
  55100. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  55101. var _this = this;
  55102. this._viewMatrix = BABYLON.Matrix.Zero();
  55103. this._projectionMatrix = BABYLON.Matrix.Zero();
  55104. this._transformMatrix = BABYLON.Matrix.Zero();
  55105. this._worldViewProjection = BABYLON.Matrix.Zero();
  55106. this._scene = scene;
  55107. var engine = scene.getEngine();
  55108. // Render target
  55109. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  55110. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55111. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55112. this._depthMap.refreshRate = 1;
  55113. this._depthMap.renderParticles = false;
  55114. this._depthMap.renderList = null;
  55115. // set default depth value to 1.0 (far away)
  55116. this._depthMap.onClearObservable.add(function (engine) {
  55117. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  55118. });
  55119. // Custom render function
  55120. var renderSubMesh = function (subMesh) {
  55121. var mesh = subMesh.getRenderingMesh();
  55122. var scene = _this._scene;
  55123. var engine = scene.getEngine();
  55124. // Culling
  55125. engine.setState(subMesh.getMaterial().backFaceCulling);
  55126. // Managing instances
  55127. var batch = mesh._getInstancesRenderList(subMesh._id);
  55128. if (batch.mustReturn) {
  55129. return;
  55130. }
  55131. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  55132. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  55133. engine.enableEffect(_this._effect);
  55134. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  55135. var material = subMesh.getMaterial();
  55136. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  55137. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  55138. // Alpha test
  55139. if (material && material.needAlphaTesting()) {
  55140. var alphaTexture = material.getAlphaTestTexture();
  55141. _this._effect.setTexture("diffuseSampler", alphaTexture);
  55142. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  55143. }
  55144. // Bones
  55145. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55146. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  55147. }
  55148. // Draw
  55149. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  55150. }
  55151. };
  55152. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  55153. var index;
  55154. if (depthOnlySubMeshes.length) {
  55155. engine.setColorWrite(false);
  55156. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  55157. renderSubMesh(depthOnlySubMeshes.data[index]);
  55158. }
  55159. engine.setColorWrite(true);
  55160. }
  55161. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55162. renderSubMesh(opaqueSubMeshes.data[index]);
  55163. }
  55164. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55165. renderSubMesh(alphaTestSubMeshes.data[index]);
  55166. }
  55167. };
  55168. }
  55169. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  55170. var material = subMesh.getMaterial();
  55171. if (material.disableDepthWrite) {
  55172. return false;
  55173. }
  55174. var defines = [];
  55175. var attribs = [BABYLON.VertexBuffer.PositionKind];
  55176. var mesh = subMesh.getMesh();
  55177. var scene = mesh.getScene();
  55178. // Alpha test
  55179. if (material && material.needAlphaTesting()) {
  55180. defines.push("#define ALPHATEST");
  55181. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55182. attribs.push(BABYLON.VertexBuffer.UVKind);
  55183. defines.push("#define UV1");
  55184. }
  55185. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55186. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55187. defines.push("#define UV2");
  55188. }
  55189. }
  55190. // Bones
  55191. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55192. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55193. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55194. if (mesh.numBoneInfluencers > 4) {
  55195. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55196. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55197. }
  55198. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55199. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55200. }
  55201. else {
  55202. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55203. }
  55204. // Instances
  55205. if (useInstances) {
  55206. defines.push("#define INSTANCES");
  55207. attribs.push("world0");
  55208. attribs.push("world1");
  55209. attribs.push("world2");
  55210. attribs.push("world3");
  55211. }
  55212. // Get correct effect
  55213. var join = defines.join("\n");
  55214. if (this._cachedDefines !== join) {
  55215. this._cachedDefines = join;
  55216. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  55217. }
  55218. return this._effect.isReady();
  55219. };
  55220. DepthRenderer.prototype.getDepthMap = function () {
  55221. return this._depthMap;
  55222. };
  55223. // Methods
  55224. DepthRenderer.prototype.dispose = function () {
  55225. this._depthMap.dispose();
  55226. };
  55227. return DepthRenderer;
  55228. }());
  55229. BABYLON.DepthRenderer = DepthRenderer;
  55230. })(BABYLON || (BABYLON = {}));
  55231. //# sourceMappingURL=babylon.depthRenderer.js.map
  55232. var BABYLON;
  55233. (function (BABYLON) {
  55234. var SSAORenderingPipeline = (function (_super) {
  55235. __extends(SSAORenderingPipeline, _super);
  55236. /**
  55237. * @constructor
  55238. * @param {string} name - The rendering pipeline name
  55239. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55240. * @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 }
  55241. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55242. */
  55243. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  55244. var _this = _super.call(this, scene.getEngine(), name) || this;
  55245. // Members
  55246. /**
  55247. * The PassPostProcess id in the pipeline that contains the original scene color
  55248. * @type {string}
  55249. */
  55250. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  55251. /**
  55252. * The SSAO PostProcess id in the pipeline
  55253. * @type {string}
  55254. */
  55255. _this.SSAORenderEffect = "SSAORenderEffect";
  55256. /**
  55257. * The horizontal blur PostProcess id in the pipeline
  55258. * @type {string}
  55259. */
  55260. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  55261. /**
  55262. * The vertical blur PostProcess id in the pipeline
  55263. * @type {string}
  55264. */
  55265. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  55266. /**
  55267. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  55268. * @type {string}
  55269. */
  55270. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  55271. /**
  55272. * The output strength of the SSAO post-process. Default value is 1.0.
  55273. * @type {number}
  55274. */
  55275. _this.totalStrength = 1.0;
  55276. /**
  55277. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  55278. * @type {number}
  55279. */
  55280. _this.radius = 0.0001;
  55281. /**
  55282. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  55283. * Must not be equal to fallOff and superior to fallOff.
  55284. * Default value is 0.975
  55285. * @type {number}
  55286. */
  55287. _this.area = 0.0075;
  55288. /**
  55289. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  55290. * Must not be equal to area and inferior to area.
  55291. * Default value is 0.0
  55292. * @type {number}
  55293. */
  55294. _this.fallOff = 0.000001;
  55295. /**
  55296. * The base color of the SSAO post-process
  55297. * The final result is "base + ssao" between [0, 1]
  55298. * @type {number}
  55299. */
  55300. _this.base = 0.5;
  55301. _this._firstUpdate = true;
  55302. _this._scene = scene;
  55303. // Set up assets
  55304. _this._createRandomTexture();
  55305. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  55306. var ssaoRatio = ratio.ssaoRatio || ratio;
  55307. var combineRatio = ratio.combineRatio || ratio;
  55308. _this._ratio = {
  55309. ssaoRatio: ssaoRatio,
  55310. combineRatio: combineRatio
  55311. };
  55312. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  55313. _this._createSSAOPostProcess(ssaoRatio);
  55314. _this._createBlurPostProcess(ssaoRatio);
  55315. _this._createSSAOCombinePostProcess(combineRatio);
  55316. // Set up pipeline
  55317. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  55318. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  55319. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  55320. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  55321. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  55322. // Finish
  55323. scene.postProcessRenderPipelineManager.addPipeline(_this);
  55324. if (cameras)
  55325. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  55326. return _this;
  55327. }
  55328. // Public Methods
  55329. /**
  55330. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  55331. */
  55332. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  55333. if (disableDepthRender === void 0) { disableDepthRender = false; }
  55334. for (var i = 0; i < this._scene.cameras.length; i++) {
  55335. var camera = this._scene.cameras[i];
  55336. this._originalColorPostProcess.dispose(camera);
  55337. this._ssaoPostProcess.dispose(camera);
  55338. this._blurHPostProcess.dispose(camera);
  55339. this._blurVPostProcess.dispose(camera);
  55340. this._ssaoCombinePostProcess.dispose(camera);
  55341. }
  55342. this._randomTexture.dispose();
  55343. if (disableDepthRender)
  55344. this._scene.disableDepthRenderer();
  55345. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  55346. _super.prototype.dispose.call(this);
  55347. };
  55348. // Private Methods
  55349. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  55350. var _this = this;
  55351. /*
  55352. var samplerOffsets = [
  55353. -8.0, -6.0, -4.0, -2.0,
  55354. 0.0,
  55355. 2.0, 4.0, 6.0, 8.0
  55356. ];
  55357. */
  55358. var samples = 16;
  55359. var samplerOffsets = new Array();
  55360. for (var i = -8; i < 8; i++) {
  55361. samplerOffsets.push(i * 2);
  55362. }
  55363. 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");
  55364. this._blurHPostProcess.onApply = function (effect) {
  55365. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  55366. effect.setTexture("depthSampler", _this._depthTexture);
  55367. if (_this._firstUpdate) {
  55368. effect.setArray("samplerOffsets", samplerOffsets);
  55369. }
  55370. };
  55371. 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");
  55372. this._blurVPostProcess.onApply = function (effect) {
  55373. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  55374. effect.setTexture("depthSampler", _this._depthTexture);
  55375. if (_this._firstUpdate) {
  55376. effect.setArray("samplerOffsets", samplerOffsets);
  55377. _this._firstUpdate = false;
  55378. }
  55379. };
  55380. };
  55381. SSAORenderingPipeline.prototype._rebuild = function () {
  55382. this._firstUpdate = true;
  55383. _super.prototype._rebuild.call(this);
  55384. };
  55385. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  55386. var _this = this;
  55387. var numSamples = 16;
  55388. var sampleSphere = [
  55389. 0.5381, 0.1856, -0.4319,
  55390. 0.1379, 0.2486, 0.4430,
  55391. 0.3371, 0.5679, -0.0057,
  55392. -0.6999, -0.0451, -0.0019,
  55393. 0.0689, -0.1598, -0.8547,
  55394. 0.0560, 0.0069, -0.1843,
  55395. -0.0146, 0.1402, 0.0762,
  55396. 0.0100, -0.1924, -0.0344,
  55397. -0.3577, -0.5301, -0.4358,
  55398. -0.3169, 0.1063, 0.0158,
  55399. 0.0103, -0.5869, 0.0046,
  55400. -0.0897, -0.4940, 0.3287,
  55401. 0.7119, -0.0154, -0.0918,
  55402. -0.0533, 0.0596, -0.5411,
  55403. 0.0352, -0.0631, 0.5460,
  55404. -0.4776, 0.2847, -0.0271
  55405. ];
  55406. var samplesFactor = 1.0 / numSamples;
  55407. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  55408. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  55409. "area", "fallOff", "base", "range", "viewport"
  55410. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  55411. var viewport = new BABYLON.Vector2(0, 0);
  55412. this._ssaoPostProcess.onApply = function (effect) {
  55413. if (_this._firstUpdate) {
  55414. effect.setArray3("sampleSphere", sampleSphere);
  55415. effect.setFloat("samplesFactor", samplesFactor);
  55416. effect.setFloat("randTextureTiles", 4.0);
  55417. }
  55418. effect.setFloat("totalStrength", _this.totalStrength);
  55419. effect.setFloat("radius", _this.radius);
  55420. effect.setFloat("area", _this.area);
  55421. effect.setFloat("fallOff", _this.fallOff);
  55422. effect.setFloat("base", _this.base);
  55423. effect.setTexture("textureSampler", _this._depthTexture);
  55424. effect.setTexture("randomSampler", _this._randomTexture);
  55425. };
  55426. };
  55427. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  55428. var _this = this;
  55429. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  55430. this._ssaoCombinePostProcess.onApply = function (effect) {
  55431. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  55432. };
  55433. };
  55434. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  55435. var size = 512;
  55436. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  55437. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55438. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55439. var context = this._randomTexture.getContext();
  55440. var rand = function (min, max) {
  55441. return Math.random() * (max - min) + min;
  55442. };
  55443. var randVector = BABYLON.Vector3.Zero();
  55444. for (var x = 0; x < size; x++) {
  55445. for (var y = 0; y < size; y++) {
  55446. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  55447. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  55448. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  55449. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  55450. context.fillRect(x, y, 1, 1);
  55451. }
  55452. }
  55453. this._randomTexture.update(false);
  55454. };
  55455. __decorate([
  55456. BABYLON.serialize()
  55457. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  55458. __decorate([
  55459. BABYLON.serialize()
  55460. ], SSAORenderingPipeline.prototype, "radius", void 0);
  55461. __decorate([
  55462. BABYLON.serialize()
  55463. ], SSAORenderingPipeline.prototype, "area", void 0);
  55464. __decorate([
  55465. BABYLON.serialize()
  55466. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  55467. __decorate([
  55468. BABYLON.serialize()
  55469. ], SSAORenderingPipeline.prototype, "base", void 0);
  55470. __decorate([
  55471. BABYLON.serialize()
  55472. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  55473. return SSAORenderingPipeline;
  55474. }(BABYLON.PostProcessRenderPipeline));
  55475. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  55476. })(BABYLON || (BABYLON = {}));
  55477. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  55478. var BABYLON;
  55479. (function (BABYLON) {
  55480. var SSAO2RenderingPipeline = (function (_super) {
  55481. __extends(SSAO2RenderingPipeline, _super);
  55482. /**
  55483. * @constructor
  55484. * @param {string} name - The rendering pipeline name
  55485. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55486. * @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 }
  55487. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55488. */
  55489. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  55490. var _this = _super.call(this, scene.getEngine(), name) || this;
  55491. // Members
  55492. /**
  55493. * The PassPostProcess id in the pipeline that contains the original scene color
  55494. * @type {string}
  55495. */
  55496. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  55497. /**
  55498. * The SSAO PostProcess id in the pipeline
  55499. * @type {string}
  55500. */
  55501. _this.SSAORenderEffect = "SSAORenderEffect";
  55502. /**
  55503. * The horizontal blur PostProcess id in the pipeline
  55504. * @type {string}
  55505. */
  55506. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  55507. /**
  55508. * The vertical blur PostProcess id in the pipeline
  55509. * @type {string}
  55510. */
  55511. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  55512. /**
  55513. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  55514. * @type {string}
  55515. */
  55516. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  55517. /**
  55518. * The output strength of the SSAO post-process. Default value is 1.0.
  55519. * @type {number}
  55520. */
  55521. _this.totalStrength = 1.0;
  55522. /**
  55523. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  55524. * @type {number}
  55525. */
  55526. _this.maxZ = 100.0;
  55527. /**
  55528. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  55529. * @type {number}
  55530. */
  55531. _this.minZAspect = 0.2;
  55532. /**
  55533. * Number of samples used for the SSAO calculations. Default value is 8
  55534. * @type {number}
  55535. */
  55536. _this._samples = 8;
  55537. /**
  55538. * Are we using bilateral blur ?
  55539. * @type {boolean}
  55540. */
  55541. _this._expensiveBlur = true;
  55542. /**
  55543. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  55544. * @type {number}
  55545. */
  55546. _this.radius = 2.0;
  55547. /**
  55548. * The base color of the SSAO post-process
  55549. * The final result is "base + ssao" between [0, 1]
  55550. * @type {number}
  55551. */
  55552. _this.base = 0.1;
  55553. _this._firstUpdate = true;
  55554. _this._scene = scene;
  55555. if (!_this.isSupported) {
  55556. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  55557. return _this;
  55558. }
  55559. var ssaoRatio = ratio.ssaoRatio || ratio;
  55560. var blurRatio = ratio.blurRatio || ratio;
  55561. _this._ratio = {
  55562. ssaoRatio: ssaoRatio,
  55563. blurRatio: blurRatio
  55564. };
  55565. // Set up assets
  55566. _this._createRandomTexture();
  55567. _this._depthTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  55568. _this._normalTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[1];
  55569. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  55570. _this._createSSAOPostProcess(1.0);
  55571. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  55572. _this._createSSAOCombinePostProcess(blurRatio);
  55573. // Set up pipeline
  55574. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  55575. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  55576. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  55577. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  55578. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  55579. // Finish
  55580. scene.postProcessRenderPipelineManager.addPipeline(_this);
  55581. if (cameras)
  55582. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  55583. return _this;
  55584. }
  55585. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  55586. get: function () {
  55587. return this._samples;
  55588. },
  55589. set: function (n) {
  55590. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  55591. this._samples = n;
  55592. this._sampleSphere = this._generateHemisphere();
  55593. this._firstUpdate = true;
  55594. },
  55595. enumerable: true,
  55596. configurable: true
  55597. });
  55598. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  55599. get: function () {
  55600. return this._expensiveBlur;
  55601. },
  55602. set: function (b) {
  55603. 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"]);
  55604. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  55605. this._expensiveBlur = b;
  55606. this._firstUpdate = true;
  55607. },
  55608. enumerable: true,
  55609. configurable: true
  55610. });
  55611. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  55612. /**
  55613. * Support test.
  55614. * @type {boolean}
  55615. */
  55616. get: function () {
  55617. var engine = BABYLON.Engine.LastCreatedEngine;
  55618. return engine.getCaps().drawBuffersExtension;
  55619. },
  55620. enumerable: true,
  55621. configurable: true
  55622. });
  55623. // Public Methods
  55624. /**
  55625. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  55626. */
  55627. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  55628. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  55629. for (var i = 0; i < this._scene.cameras.length; i++) {
  55630. var camera = this._scene.cameras[i];
  55631. this._originalColorPostProcess.dispose(camera);
  55632. this._ssaoPostProcess.dispose(camera);
  55633. this._blurHPostProcess.dispose(camera);
  55634. this._blurVPostProcess.dispose(camera);
  55635. this._ssaoCombinePostProcess.dispose(camera);
  55636. }
  55637. this._randomTexture.dispose();
  55638. if (disableGeometryBufferRenderer)
  55639. this._scene.disableGeometryBufferRenderer();
  55640. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  55641. _super.prototype.dispose.call(this);
  55642. };
  55643. // Private Methods
  55644. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  55645. var _this = this;
  55646. var samples = 16;
  55647. this._samplerOffsets = [];
  55648. var expensive = this.expensiveBlur;
  55649. for (var i = -8; i < 8; i++) {
  55650. this._samplerOffsets.push(i * 2 + 0.5);
  55651. }
  55652. 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");
  55653. this._blurHPostProcess.onApply = function (effect) {
  55654. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  55655. effect.setFloat("near", _this._scene.activeCamera.minZ);
  55656. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  55657. effect.setFloat("radius", _this.radius);
  55658. effect.setTexture("depthSampler", _this._depthTexture);
  55659. if (_this._firstUpdate) {
  55660. effect.setArray("samplerOffsets", _this._samplerOffsets);
  55661. }
  55662. };
  55663. 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");
  55664. this._blurVPostProcess.onApply = function (effect) {
  55665. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  55666. effect.setFloat("near", _this._scene.activeCamera.minZ);
  55667. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  55668. effect.setFloat("radius", _this.radius);
  55669. effect.setTexture("depthSampler", _this._depthTexture);
  55670. if (_this._firstUpdate) {
  55671. effect.setArray("samplerOffsets", _this._samplerOffsets);
  55672. _this._firstUpdate = false;
  55673. }
  55674. };
  55675. };
  55676. SSAO2RenderingPipeline.prototype._rebuild = function () {
  55677. this._firstUpdate = true;
  55678. _super.prototype._rebuild.call(this);
  55679. };
  55680. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  55681. var numSamples = this.samples;
  55682. var result = [];
  55683. var vector, scale;
  55684. var rand = function (min, max) {
  55685. return Math.random() * (max - min) + min;
  55686. };
  55687. var i = 0;
  55688. var normal = new BABYLON.Vector3(0, 0, 1);
  55689. while (i < numSamples) {
  55690. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  55691. vector.normalize();
  55692. scale = i / numSamples;
  55693. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  55694. vector.scaleInPlace(scale);
  55695. result.push(vector.x, vector.y, vector.z);
  55696. i++;
  55697. }
  55698. return result;
  55699. };
  55700. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  55701. var _this = this;
  55702. var numSamples = this.samples;
  55703. this._sampleSphere = this._generateHemisphere();
  55704. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  55705. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  55706. "base", "range", "projection", "near", "far", "texelSize",
  55707. "xViewport", "yViewport", "maxZ", "minZAspect"
  55708. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  55709. this._ssaoPostProcess.onApply = function (effect) {
  55710. if (_this._firstUpdate) {
  55711. effect.setArray3("sampleSphere", _this._sampleSphere);
  55712. effect.setFloat("randTextureTiles", 4.0);
  55713. }
  55714. effect.setFloat("samplesFactor", 1 / _this.samples);
  55715. effect.setFloat("totalStrength", _this.totalStrength);
  55716. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  55717. effect.setFloat("radius", _this.radius);
  55718. effect.setFloat("maxZ", _this.maxZ);
  55719. effect.setFloat("minZAspect", _this.minZAspect);
  55720. effect.setFloat("base", _this.base);
  55721. effect.setFloat("near", _this._scene.activeCamera.minZ);
  55722. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  55723. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  55724. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  55725. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  55726. effect.setTexture("textureSampler", _this._depthTexture);
  55727. effect.setTexture("normalSampler", _this._normalTexture);
  55728. effect.setTexture("randomSampler", _this._randomTexture);
  55729. };
  55730. };
  55731. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  55732. var _this = this;
  55733. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  55734. this._ssaoCombinePostProcess.onApply = function (effect) {
  55735. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  55736. };
  55737. };
  55738. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  55739. var size = 512;
  55740. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  55741. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55742. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55743. var context = this._randomTexture.getContext();
  55744. var rand = function (min, max) {
  55745. return Math.random() * (max - min) + min;
  55746. };
  55747. var randVector = BABYLON.Vector3.Zero();
  55748. for (var x = 0; x < size; x++) {
  55749. for (var y = 0; y < size; y++) {
  55750. randVector.x = rand(0.0, 1.0);
  55751. randVector.y = rand(0.0, 1.0);
  55752. randVector.z = 0.0;
  55753. randVector.normalize();
  55754. randVector.scaleInPlace(255);
  55755. randVector.x = Math.floor(randVector.x);
  55756. randVector.y = Math.floor(randVector.y);
  55757. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  55758. context.fillRect(x, y, 1, 1);
  55759. }
  55760. }
  55761. this._randomTexture.update(false);
  55762. };
  55763. __decorate([
  55764. BABYLON.serialize()
  55765. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  55766. __decorate([
  55767. BABYLON.serialize()
  55768. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  55769. __decorate([
  55770. BABYLON.serialize()
  55771. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  55772. __decorate([
  55773. BABYLON.serialize("samples")
  55774. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  55775. __decorate([
  55776. BABYLON.serialize("expensiveBlur")
  55777. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  55778. __decorate([
  55779. BABYLON.serialize()
  55780. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  55781. __decorate([
  55782. BABYLON.serialize()
  55783. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  55784. __decorate([
  55785. BABYLON.serialize()
  55786. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  55787. return SSAO2RenderingPipeline;
  55788. }(BABYLON.PostProcessRenderPipeline));
  55789. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  55790. })(BABYLON || (BABYLON = {}));
  55791. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  55792. // BABYLON.JS Chromatic Aberration GLSL Shader
  55793. // Author: Olivier Guyot
  55794. // Separates very slightly R, G and B colors on the edges of the screen
  55795. // Inspired by Francois Tarlier & Martins Upitis
  55796. var BABYLON;
  55797. (function (BABYLON) {
  55798. var LensRenderingPipeline = (function (_super) {
  55799. __extends(LensRenderingPipeline, _super);
  55800. /**
  55801. * @constructor
  55802. *
  55803. * Effect parameters are as follow:
  55804. * {
  55805. * chromatic_aberration: number; // from 0 to x (1 for realism)
  55806. * edge_blur: number; // from 0 to x (1 for realism)
  55807. * distortion: number; // from 0 to x (1 for realism)
  55808. * grain_amount: number; // from 0 to 1
  55809. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  55810. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  55811. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  55812. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  55813. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  55814. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  55815. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  55816. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  55817. * }
  55818. * Note: if an effect parameter is unset, effect is disabled
  55819. *
  55820. * @param {string} name - The rendering pipeline name
  55821. * @param {object} parameters - An object containing all parameters (see above)
  55822. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55823. * @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)
  55824. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55825. */
  55826. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  55827. if (ratio === void 0) { ratio = 1.0; }
  55828. var _this = _super.call(this, scene.getEngine(), name) || this;
  55829. // Lens effects can be of the following:
  55830. // - chromatic aberration (slight shift of RGB colors)
  55831. // - blur on the edge of the lens
  55832. // - lens distortion
  55833. // - depth-of-field blur & highlights enhancing
  55834. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  55835. // - grain effect (noise or custom texture)
  55836. // Two additional texture samplers are needed:
  55837. // - depth map (for depth-of-field)
  55838. // - grain texture
  55839. /**
  55840. * The chromatic aberration PostProcess id in the pipeline
  55841. * @type {string}
  55842. */
  55843. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  55844. /**
  55845. * The highlights enhancing PostProcess id in the pipeline
  55846. * @type {string}
  55847. */
  55848. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  55849. /**
  55850. * The depth-of-field PostProcess id in the pipeline
  55851. * @type {string}
  55852. */
  55853. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  55854. _this._scene = scene;
  55855. // Fetch texture samplers
  55856. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  55857. if (parameters.grain_texture) {
  55858. _this._grainTexture = parameters.grain_texture;
  55859. }
  55860. else {
  55861. _this._createGrainTexture();
  55862. }
  55863. // save parameters
  55864. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  55865. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  55866. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  55867. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  55868. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  55869. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  55870. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  55871. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  55872. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  55873. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  55874. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  55875. // Create effects
  55876. _this._createChromaticAberrationPostProcess(ratio);
  55877. _this._createHighlightsPostProcess(ratio);
  55878. _this._createDepthOfFieldPostProcess(ratio / 4);
  55879. // Set up pipeline
  55880. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  55881. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  55882. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  55883. if (_this._highlightsGain === -1) {
  55884. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  55885. }
  55886. // Finish
  55887. scene.postProcessRenderPipelineManager.addPipeline(_this);
  55888. if (cameras) {
  55889. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  55890. }
  55891. return _this;
  55892. }
  55893. // public methods (self explanatory)
  55894. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  55895. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  55896. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  55897. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  55898. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  55899. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  55900. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  55901. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  55902. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  55903. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  55904. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  55905. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  55906. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  55907. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  55908. };
  55909. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  55910. this._highlightsPostProcess.updateEffect();
  55911. };
  55912. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  55913. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  55914. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  55915. this._highlightsGain = amount;
  55916. };
  55917. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  55918. if (this._highlightsGain === -1) {
  55919. this._highlightsGain = 1.0;
  55920. }
  55921. this._highlightsThreshold = amount;
  55922. };
  55923. LensRenderingPipeline.prototype.disableHighlights = function () {
  55924. this._highlightsGain = -1;
  55925. };
  55926. /**
  55927. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  55928. */
  55929. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  55930. if (disableDepthRender === void 0) { disableDepthRender = false; }
  55931. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  55932. this._chromaticAberrationPostProcess = undefined;
  55933. this._highlightsPostProcess = undefined;
  55934. this._depthOfFieldPostProcess = undefined;
  55935. this._grainTexture.dispose();
  55936. if (disableDepthRender)
  55937. this._scene.disableDepthRenderer();
  55938. };
  55939. // colors shifting and distortion
  55940. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  55941. var _this = this;
  55942. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  55943. [], // samplers
  55944. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  55945. this._chromaticAberrationPostProcess.onApply = function (effect) {
  55946. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  55947. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  55948. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  55949. };
  55950. };
  55951. // highlights enhancing
  55952. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  55953. var _this = this;
  55954. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  55955. [], // samplers
  55956. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  55957. this._highlightsPostProcess.onApply = function (effect) {
  55958. effect.setFloat('gain', _this._highlightsGain);
  55959. effect.setFloat('threshold', _this._highlightsThreshold);
  55960. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  55961. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  55962. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  55963. };
  55964. };
  55965. // colors shifting and distortion
  55966. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  55967. var _this = this;
  55968. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  55969. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  55970. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  55971. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  55972. this._depthOfFieldPostProcess.onApply = function (effect) {
  55973. effect.setTexture("depthSampler", _this._depthTexture);
  55974. effect.setTexture("grainSampler", _this._grainTexture);
  55975. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  55976. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  55977. effect.setFloat('grain_amount', _this._grainAmount);
  55978. effect.setBool('blur_noise', _this._blurNoise);
  55979. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  55980. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  55981. effect.setFloat('distortion', _this._distortion);
  55982. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  55983. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  55984. effect.setFloat('aperture', _this._dofAperture);
  55985. effect.setFloat('darken', _this._dofDarken);
  55986. effect.setFloat('edge_blur', _this._edgeBlur);
  55987. effect.setBool('highlights', (_this._highlightsGain !== -1));
  55988. effect.setFloat('near', _this._scene.activeCamera.minZ);
  55989. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  55990. };
  55991. };
  55992. // creates a black and white random noise texture, 512x512
  55993. LensRenderingPipeline.prototype._createGrainTexture = function () {
  55994. var size = 512;
  55995. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55996. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55997. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55998. var context = this._grainTexture.getContext();
  55999. var rand = function (min, max) {
  56000. return Math.random() * (max - min) + min;
  56001. };
  56002. var value;
  56003. for (var x = 0; x < size; x++) {
  56004. for (var y = 0; y < size; y++) {
  56005. value = Math.floor(rand(0.42, 0.58) * 255);
  56006. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  56007. context.fillRect(x, y, 1, 1);
  56008. }
  56009. }
  56010. this._grainTexture.update(false);
  56011. };
  56012. return LensRenderingPipeline;
  56013. }(BABYLON.PostProcessRenderPipeline));
  56014. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  56015. })(BABYLON || (BABYLON = {}));
  56016. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  56017. var BABYLON;
  56018. (function (BABYLON) {
  56019. var StandardRenderingPipeline = (function (_super) {
  56020. __extends(StandardRenderingPipeline, _super);
  56021. /**
  56022. * @constructor
  56023. * @param {string} name - The rendering pipeline name
  56024. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  56025. * @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)
  56026. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  56027. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  56028. */
  56029. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  56030. if (originalPostProcess === void 0) { originalPostProcess = null; }
  56031. var _this = _super.call(this, scene.getEngine(), name) || this;
  56032. _this.downSampleX4PostProcess = null;
  56033. _this.brightPassPostProcess = null;
  56034. _this.blurHPostProcesses = [];
  56035. _this.blurVPostProcesses = [];
  56036. _this.textureAdderPostProcess = null;
  56037. _this.volumetricLightPostProcess = null;
  56038. _this.volumetricLightSmoothXPostProcess = null;
  56039. _this.volumetricLightSmoothYPostProcess = null;
  56040. _this.volumetricLightMergePostProces = null;
  56041. _this.volumetricLightFinalPostProcess = null;
  56042. _this.luminancePostProcess = null;
  56043. _this.luminanceDownSamplePostProcesses = [];
  56044. _this.hdrPostProcess = null;
  56045. _this.textureAdderFinalPostProcess = null;
  56046. _this.lensFlareFinalPostProcess = null;
  56047. _this.hdrFinalPostProcess = null;
  56048. _this.lensFlarePostProcess = null;
  56049. _this.lensFlareComposePostProcess = null;
  56050. _this.motionBlurPostProcess = null;
  56051. _this.depthOfFieldPostProcess = null;
  56052. // Values
  56053. _this.brightThreshold = 1.0;
  56054. _this.blurWidth = 512.0;
  56055. _this.horizontalBlur = false;
  56056. _this.exposure = 1.0;
  56057. _this.lensTexture = null;
  56058. _this.volumetricLightCoefficient = 0.2;
  56059. _this.volumetricLightPower = 4.0;
  56060. _this.volumetricLightBlurScale = 64.0;
  56061. _this.sourceLight = null;
  56062. _this.hdrMinimumLuminance = 1.0;
  56063. _this.hdrDecreaseRate = 0.5;
  56064. _this.hdrIncreaseRate = 0.5;
  56065. _this.lensColorTexture = null;
  56066. _this.lensFlareStrength = 20.0;
  56067. _this.lensFlareGhostDispersal = 1.4;
  56068. _this.lensFlareHaloWidth = 0.7;
  56069. _this.lensFlareDistortionStrength = 16.0;
  56070. _this.lensStarTexture = null;
  56071. _this.lensFlareDirtTexture = null;
  56072. _this.depthOfFieldDistance = 10.0;
  56073. _this.depthOfFieldBlurWidth = 64.0;
  56074. _this.motionStrength = 1.0;
  56075. // IAnimatable
  56076. _this.animations = [];
  56077. _this._currentDepthOfFieldSource = null;
  56078. _this._hdrCurrentLuminance = 1.0;
  56079. // Getters and setters
  56080. _this._bloomEnabled = true;
  56081. _this._depthOfFieldEnabled = false;
  56082. _this._vlsEnabled = false;
  56083. _this._lensFlareEnabled = false;
  56084. _this._hdrEnabled = false;
  56085. _this._motionBlurEnabled = false;
  56086. _this._motionBlurSamples = 64.0;
  56087. _this._volumetricLightStepsCount = 50.0;
  56088. _this._cameras = cameras || [];
  56089. // Initialize
  56090. _this._scene = scene;
  56091. _this._basePostProcess = originalPostProcess;
  56092. _this._ratio = ratio;
  56093. // Misc
  56094. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  56095. // Finish
  56096. scene.postProcessRenderPipelineManager.addPipeline(_this);
  56097. _this._buildPipeline();
  56098. return _this;
  56099. }
  56100. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  56101. get: function () {
  56102. return this._bloomEnabled;
  56103. },
  56104. set: function (enabled) {
  56105. if (this._bloomEnabled === enabled) {
  56106. return;
  56107. }
  56108. this._bloomEnabled = enabled;
  56109. this._buildPipeline();
  56110. },
  56111. enumerable: true,
  56112. configurable: true
  56113. });
  56114. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  56115. get: function () {
  56116. return this._depthOfFieldEnabled;
  56117. },
  56118. set: function (enabled) {
  56119. if (this._depthOfFieldEnabled === enabled) {
  56120. return;
  56121. }
  56122. this._depthOfFieldEnabled = enabled;
  56123. this._buildPipeline();
  56124. },
  56125. enumerable: true,
  56126. configurable: true
  56127. });
  56128. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  56129. get: function () {
  56130. return this._lensFlareEnabled;
  56131. },
  56132. set: function (enabled) {
  56133. if (this._lensFlareEnabled === enabled) {
  56134. return;
  56135. }
  56136. this._lensFlareEnabled = enabled;
  56137. this._buildPipeline();
  56138. },
  56139. enumerable: true,
  56140. configurable: true
  56141. });
  56142. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  56143. get: function () {
  56144. return this._hdrEnabled;
  56145. },
  56146. set: function (enabled) {
  56147. if (this._hdrEnabled === enabled) {
  56148. return;
  56149. }
  56150. this._hdrEnabled = enabled;
  56151. this._buildPipeline();
  56152. },
  56153. enumerable: true,
  56154. configurable: true
  56155. });
  56156. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  56157. get: function () {
  56158. return this._vlsEnabled;
  56159. },
  56160. set: function (enabled) {
  56161. if (this._vlsEnabled === enabled) {
  56162. return;
  56163. }
  56164. if (enabled) {
  56165. var geometry = this._scene.enableGeometryBufferRenderer();
  56166. if (!geometry) {
  56167. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  56168. return;
  56169. }
  56170. }
  56171. this._vlsEnabled = enabled;
  56172. this._buildPipeline();
  56173. },
  56174. enumerable: true,
  56175. configurable: true
  56176. });
  56177. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  56178. get: function () {
  56179. return this._motionBlurEnabled;
  56180. },
  56181. set: function (enabled) {
  56182. if (this._motionBlurEnabled === enabled) {
  56183. return;
  56184. }
  56185. this._motionBlurEnabled = enabled;
  56186. this._buildPipeline();
  56187. },
  56188. enumerable: true,
  56189. configurable: true
  56190. });
  56191. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  56192. get: function () {
  56193. return this._volumetricLightStepsCount;
  56194. },
  56195. set: function (count) {
  56196. if (this.volumetricLightPostProcess) {
  56197. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  56198. }
  56199. this._volumetricLightStepsCount = count;
  56200. },
  56201. enumerable: true,
  56202. configurable: true
  56203. });
  56204. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  56205. get: function () {
  56206. return this._motionBlurSamples;
  56207. },
  56208. set: function (samples) {
  56209. if (this.motionBlurPostProcess) {
  56210. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  56211. }
  56212. this._motionBlurSamples = samples;
  56213. },
  56214. enumerable: true,
  56215. configurable: true
  56216. });
  56217. StandardRenderingPipeline.prototype._buildPipeline = function () {
  56218. var _this = this;
  56219. var ratio = this._ratio;
  56220. var scene = this._scene;
  56221. this._disposePostProcesses();
  56222. this._reset();
  56223. // Create pass post-process
  56224. if (!this._basePostProcess) {
  56225. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  56226. this.originalPostProcess.onApply = function (effect) {
  56227. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  56228. };
  56229. }
  56230. else {
  56231. this.originalPostProcess = this._basePostProcess;
  56232. }
  56233. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  56234. this._currentDepthOfFieldSource = this.originalPostProcess;
  56235. if (this._vlsEnabled) {
  56236. // Create volumetric light
  56237. this._createVolumetricLightPostProcess(scene, ratio);
  56238. // Create volumetric light final post-process
  56239. 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);
  56240. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  56241. }
  56242. if (this._bloomEnabled) {
  56243. // Create down sample X4 post-process
  56244. this._createDownSampleX4PostProcess(scene, ratio / 2);
  56245. // Create bright pass post-process
  56246. this._createBrightPassPostProcess(scene, ratio / 2);
  56247. // Create gaussian blur post-processes (down sampling blurs)
  56248. this._createBlurPostProcesses(scene, ratio / 4, 1);
  56249. // Create texture adder post-process
  56250. this._createTextureAdderPostProcess(scene, ratio);
  56251. // Create depth-of-field source post-process
  56252. 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);
  56253. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  56254. }
  56255. if (this._lensFlareEnabled) {
  56256. // Create lens flare post-process
  56257. this._createLensFlarePostProcess(scene, ratio);
  56258. // Create depth-of-field source post-process post lens-flare and disable it now
  56259. 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);
  56260. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  56261. }
  56262. if (this._hdrEnabled) {
  56263. // Create luminance
  56264. this._createLuminancePostProcesses(scene, this._floatTextureType);
  56265. // Create HDR
  56266. this._createHdrPostProcess(scene, ratio);
  56267. // Create depth-of-field source post-process post hdr and disable it now
  56268. 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);
  56269. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  56270. }
  56271. if (this._depthOfFieldEnabled) {
  56272. // Create gaussian blur used by depth-of-field
  56273. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  56274. // Create depth-of-field post-process
  56275. this._createDepthOfFieldPostProcess(scene, ratio);
  56276. }
  56277. if (this._motionBlurEnabled) {
  56278. // Create motion blur post-process
  56279. this._createMotionBlurPostProcess(scene, ratio);
  56280. }
  56281. if (this._cameras !== null) {
  56282. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  56283. }
  56284. };
  56285. // Down Sample X4 Post-Processs
  56286. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  56287. var _this = this;
  56288. var downSampleX4Offsets = new Array(32);
  56289. 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);
  56290. this.downSampleX4PostProcess.onApply = function (effect) {
  56291. var id = 0;
  56292. for (var i = -2; i < 2; i++) {
  56293. for (var j = -2; j < 2; j++) {
  56294. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  56295. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  56296. id += 2;
  56297. }
  56298. }
  56299. effect.setArray2("dsOffsets", downSampleX4Offsets);
  56300. };
  56301. // Add to pipeline
  56302. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  56303. };
  56304. // Brightpass Post-Process
  56305. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  56306. var _this = this;
  56307. var brightOffsets = new Array(8);
  56308. 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);
  56309. this.brightPassPostProcess.onApply = function (effect) {
  56310. var sU = (1.0 / _this.brightPassPostProcess.width);
  56311. var sV = (1.0 / _this.brightPassPostProcess.height);
  56312. brightOffsets[0] = -0.5 * sU;
  56313. brightOffsets[1] = 0.5 * sV;
  56314. brightOffsets[2] = 0.5 * sU;
  56315. brightOffsets[3] = 0.5 * sV;
  56316. brightOffsets[4] = -0.5 * sU;
  56317. brightOffsets[5] = -0.5 * sV;
  56318. brightOffsets[6] = 0.5 * sU;
  56319. brightOffsets[7] = -0.5 * sV;
  56320. effect.setArray2("dsOffsets", brightOffsets);
  56321. effect.setFloat("brightThreshold", _this.brightThreshold);
  56322. };
  56323. // Add to pipeline
  56324. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  56325. };
  56326. // Create blur H&V post-processes
  56327. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  56328. var _this = this;
  56329. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  56330. var engine = scene.getEngine();
  56331. 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);
  56332. 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);
  56333. blurX.onActivateObservable.add(function () {
  56334. var dw = blurX.width / engine.getRenderingCanvas().width;
  56335. blurX.kernel = _this[blurWidthKey] * dw;
  56336. });
  56337. blurY.onActivateObservable.add(function () {
  56338. var dw = blurY.height / engine.getRenderingCanvas().height;
  56339. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  56340. });
  56341. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  56342. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  56343. this.blurHPostProcesses.push(blurX);
  56344. this.blurVPostProcesses.push(blurY);
  56345. };
  56346. // Create texture adder post-process
  56347. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  56348. var _this = this;
  56349. 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);
  56350. this.textureAdderPostProcess.onApply = function (effect) {
  56351. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  56352. effect.setTexture("lensSampler", _this.lensTexture);
  56353. effect.setFloat("exposure", _this.exposure);
  56354. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  56355. };
  56356. // Add to pipeline
  56357. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  56358. };
  56359. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  56360. var _this = this;
  56361. var geometryRenderer = scene.enableGeometryBufferRenderer();
  56362. geometryRenderer.enablePosition = true;
  56363. var geometry = geometryRenderer.getGBuffer();
  56364. // Base post-process
  56365. 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));
  56366. var depthValues = BABYLON.Vector2.Zero();
  56367. this.volumetricLightPostProcess.onApply = function (effect) {
  56368. if (_this.sourceLight && _this.sourceLight.getShadowGenerator()) {
  56369. var generator = _this.sourceLight.getShadowGenerator();
  56370. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  56371. effect.setTexture("positionSampler", geometry.textures[2]);
  56372. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  56373. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  56374. effect.setVector3("cameraPosition", scene.activeCamera.globalPosition);
  56375. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  56376. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  56377. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  56378. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  56379. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  56380. effect.setVector2("depthValues", depthValues);
  56381. }
  56382. };
  56383. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  56384. // Smooth
  56385. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  56386. // Merge
  56387. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  56388. this.volumetricLightMergePostProces.onApply = function (effect) {
  56389. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  56390. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  56391. };
  56392. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  56393. };
  56394. // Create luminance
  56395. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  56396. var _this = this;
  56397. // Create luminance
  56398. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  56399. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  56400. var offsets = [];
  56401. this.luminancePostProcess.onApply = function (effect) {
  56402. var sU = (1.0 / _this.luminancePostProcess.width);
  56403. var sV = (1.0 / _this.luminancePostProcess.height);
  56404. offsets[0] = -0.5 * sU;
  56405. offsets[1] = 0.5 * sV;
  56406. offsets[2] = 0.5 * sU;
  56407. offsets[3] = 0.5 * sV;
  56408. offsets[4] = -0.5 * sU;
  56409. offsets[5] = -0.5 * sV;
  56410. offsets[6] = 0.5 * sU;
  56411. offsets[7] = -0.5 * sV;
  56412. effect.setArray2("lumOffsets", offsets);
  56413. };
  56414. // Add to pipeline
  56415. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  56416. // Create down sample luminance
  56417. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  56418. var size = Math.pow(3, i);
  56419. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  56420. if (i === 0) {
  56421. defines += "#define FINAL_DOWN_SAMPLER";
  56422. }
  56423. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  56424. this.luminanceDownSamplePostProcesses.push(postProcess);
  56425. }
  56426. // Create callbacks and add effects
  56427. var lastLuminance = this.luminancePostProcess;
  56428. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  56429. var downSampleOffsets = new Array(18);
  56430. pp.onApply = function (effect) {
  56431. var id = 0;
  56432. for (var x = -1; x < 2; x++) {
  56433. for (var y = -1; y < 2; y++) {
  56434. downSampleOffsets[id] = x / lastLuminance.width;
  56435. downSampleOffsets[id + 1] = y / lastLuminance.height;
  56436. id += 2;
  56437. }
  56438. }
  56439. effect.setArray2("dsOffsets", downSampleOffsets);
  56440. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  56441. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  56442. lastLuminance = _this.luminancePostProcess;
  56443. }
  56444. else {
  56445. lastLuminance = pp;
  56446. }
  56447. };
  56448. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  56449. pp.onAfterRender = function (effect) {
  56450. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  56451. 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);
  56452. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  56453. };
  56454. }
  56455. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  56456. });
  56457. };
  56458. // Create HDR post-process
  56459. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  56460. var _this = this;
  56461. 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);
  56462. var outputLiminance = 1;
  56463. var time = 0;
  56464. var lastTime = 0;
  56465. this.hdrPostProcess.onApply = function (effect) {
  56466. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  56467. time += scene.getEngine().getDeltaTime();
  56468. if (outputLiminance < 0) {
  56469. outputLiminance = _this._hdrCurrentLuminance;
  56470. }
  56471. else {
  56472. var dt = (lastTime - time) / 1000.0;
  56473. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  56474. outputLiminance += _this.hdrDecreaseRate * dt;
  56475. }
  56476. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  56477. outputLiminance -= _this.hdrIncreaseRate * dt;
  56478. }
  56479. else {
  56480. outputLiminance = _this._hdrCurrentLuminance;
  56481. }
  56482. }
  56483. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  56484. effect.setFloat("averageLuminance", outputLiminance);
  56485. lastTime = time;
  56486. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  56487. };
  56488. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  56489. };
  56490. // Create lens flare post-process
  56491. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  56492. var _this = this;
  56493. 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);
  56494. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  56495. this._createBlurPostProcesses(scene, ratio / 4, 2);
  56496. 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);
  56497. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  56498. var resolution = new BABYLON.Vector2(0, 0);
  56499. // Lens flare
  56500. this.lensFlarePostProcess.onApply = function (effect) {
  56501. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  56502. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  56503. effect.setFloat("strength", _this.lensFlareStrength);
  56504. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  56505. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  56506. // Shift
  56507. resolution.x = _this.lensFlarePostProcess.width;
  56508. resolution.y = _this.lensFlarePostProcess.height;
  56509. effect.setVector2("resolution", resolution);
  56510. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  56511. };
  56512. // Compose
  56513. 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);
  56514. 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);
  56515. this.lensFlareComposePostProcess.onApply = function (effect) {
  56516. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  56517. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  56518. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  56519. // Lens start rotation matrix
  56520. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  56521. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  56522. 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));
  56523. camRot *= 4.0;
  56524. 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);
  56525. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  56526. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  56527. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  56528. };
  56529. };
  56530. // Create depth-of-field post-process
  56531. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  56532. var _this = this;
  56533. 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);
  56534. this.depthOfFieldPostProcess.onApply = function (effect) {
  56535. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  56536. effect.setTexture("depthSampler", _this._getDepthTexture());
  56537. effect.setFloat("distance", _this.depthOfFieldDistance);
  56538. };
  56539. // Add to pipeline
  56540. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  56541. };
  56542. // Create motion blur post-process
  56543. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  56544. var _this = this;
  56545. 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);
  56546. var motionScale = 0;
  56547. var prevViewProjection = BABYLON.Matrix.Identity();
  56548. var invViewProjection = BABYLON.Matrix.Identity();
  56549. var viewProjection = BABYLON.Matrix.Identity();
  56550. var screenSize = BABYLON.Vector2.Zero();
  56551. this.motionBlurPostProcess.onApply = function (effect) {
  56552. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  56553. viewProjection.invertToRef(invViewProjection);
  56554. effect.setMatrix("inverseViewProjection", invViewProjection);
  56555. effect.setMatrix("prevViewProjection", prevViewProjection);
  56556. prevViewProjection = viewProjection;
  56557. screenSize.x = _this.motionBlurPostProcess.width;
  56558. screenSize.y = _this.motionBlurPostProcess.height;
  56559. effect.setVector2("screenSize", screenSize);
  56560. motionScale = scene.getEngine().getFps() / 60.0;
  56561. effect.setFloat("motionScale", motionScale);
  56562. effect.setFloat("motionStrength", _this.motionStrength);
  56563. effect.setTexture("depthSampler", _this._getDepthTexture());
  56564. };
  56565. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  56566. };
  56567. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  56568. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  56569. return this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  56570. }
  56571. return this._scene.enableDepthRenderer().getDepthMap();
  56572. };
  56573. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  56574. for (var i = 0; i < this._cameras.length; i++) {
  56575. var camera = this._cameras[i];
  56576. if (this.originalPostProcess) {
  56577. this.originalPostProcess.dispose(camera);
  56578. }
  56579. if (this.downSampleX4PostProcess) {
  56580. this.downSampleX4PostProcess.dispose(camera);
  56581. }
  56582. if (this.brightPassPostProcess) {
  56583. this.brightPassPostProcess.dispose(camera);
  56584. }
  56585. if (this.textureAdderPostProcess) {
  56586. this.textureAdderPostProcess.dispose(camera);
  56587. }
  56588. if (this.textureAdderFinalPostProcess) {
  56589. this.textureAdderFinalPostProcess.dispose(camera);
  56590. }
  56591. if (this.volumetricLightPostProcess) {
  56592. this.volumetricLightPostProcess.dispose(camera);
  56593. }
  56594. if (this.volumetricLightSmoothXPostProcess) {
  56595. this.volumetricLightSmoothXPostProcess.dispose(camera);
  56596. }
  56597. if (this.volumetricLightSmoothYPostProcess) {
  56598. this.volumetricLightSmoothYPostProcess.dispose(camera);
  56599. }
  56600. if (this.volumetricLightMergePostProces) {
  56601. this.volumetricLightMergePostProces.dispose(camera);
  56602. }
  56603. if (this.volumetricLightFinalPostProcess) {
  56604. this.volumetricLightFinalPostProcess.dispose(camera);
  56605. }
  56606. if (this.lensFlarePostProcess) {
  56607. this.lensFlarePostProcess.dispose(camera);
  56608. }
  56609. if (this.lensFlareComposePostProcess) {
  56610. this.lensFlareComposePostProcess.dispose(camera);
  56611. }
  56612. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  56613. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  56614. }
  56615. if (this.luminancePostProcess) {
  56616. this.luminancePostProcess.dispose(camera);
  56617. }
  56618. if (this.hdrPostProcess) {
  56619. this.hdrPostProcess.dispose(camera);
  56620. }
  56621. if (this.hdrFinalPostProcess) {
  56622. this.hdrFinalPostProcess.dispose(camera);
  56623. }
  56624. if (this.depthOfFieldPostProcess) {
  56625. this.depthOfFieldPostProcess.dispose(camera);
  56626. }
  56627. if (this.motionBlurPostProcess) {
  56628. this.motionBlurPostProcess.dispose(camera);
  56629. }
  56630. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  56631. this.blurHPostProcesses[j].dispose(camera);
  56632. }
  56633. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  56634. this.blurVPostProcesses[j].dispose(camera);
  56635. }
  56636. }
  56637. this.originalPostProcess = null;
  56638. this.downSampleX4PostProcess = null;
  56639. this.brightPassPostProcess = null;
  56640. this.textureAdderPostProcess = null;
  56641. this.textureAdderFinalPostProcess = null;
  56642. this.volumetricLightPostProcess = null;
  56643. this.volumetricLightSmoothXPostProcess = null;
  56644. this.volumetricLightSmoothYPostProcess = null;
  56645. this.volumetricLightMergePostProces = null;
  56646. this.volumetricLightFinalPostProcess = null;
  56647. this.lensFlarePostProcess = null;
  56648. this.lensFlareComposePostProcess = null;
  56649. this.luminancePostProcess = null;
  56650. this.hdrPostProcess = null;
  56651. this.hdrFinalPostProcess = null;
  56652. this.depthOfFieldPostProcess = null;
  56653. this.motionBlurPostProcess = null;
  56654. this.luminanceDownSamplePostProcesses = [];
  56655. this.blurHPostProcesses = [];
  56656. this.blurVPostProcesses = [];
  56657. };
  56658. // Dispose
  56659. StandardRenderingPipeline.prototype.dispose = function () {
  56660. this._disposePostProcesses();
  56661. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  56662. _super.prototype.dispose.call(this);
  56663. };
  56664. // Serialize rendering pipeline
  56665. StandardRenderingPipeline.prototype.serialize = function () {
  56666. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  56667. serializationObject.customType = "StandardRenderingPipeline";
  56668. return serializationObject;
  56669. };
  56670. /**
  56671. * Static members
  56672. */
  56673. // Parse serialized pipeline
  56674. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  56675. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  56676. };
  56677. // Luminance steps
  56678. StandardRenderingPipeline.LuminanceSteps = 6;
  56679. __decorate([
  56680. BABYLON.serialize()
  56681. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  56682. __decorate([
  56683. BABYLON.serialize()
  56684. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  56685. __decorate([
  56686. BABYLON.serialize()
  56687. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  56688. __decorate([
  56689. BABYLON.serialize()
  56690. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  56691. __decorate([
  56692. BABYLON.serializeAsTexture("lensTexture")
  56693. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  56694. __decorate([
  56695. BABYLON.serialize()
  56696. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  56697. __decorate([
  56698. BABYLON.serialize()
  56699. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  56700. __decorate([
  56701. BABYLON.serialize()
  56702. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  56703. __decorate([
  56704. BABYLON.serialize()
  56705. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  56706. __decorate([
  56707. BABYLON.serialize()
  56708. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  56709. __decorate([
  56710. BABYLON.serialize()
  56711. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  56712. __decorate([
  56713. BABYLON.serializeAsTexture("lensColorTexture")
  56714. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  56715. __decorate([
  56716. BABYLON.serialize()
  56717. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  56718. __decorate([
  56719. BABYLON.serialize()
  56720. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  56721. __decorate([
  56722. BABYLON.serialize()
  56723. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  56724. __decorate([
  56725. BABYLON.serialize()
  56726. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  56727. __decorate([
  56728. BABYLON.serializeAsTexture("lensStarTexture")
  56729. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  56730. __decorate([
  56731. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  56732. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  56733. __decorate([
  56734. BABYLON.serialize()
  56735. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  56736. __decorate([
  56737. BABYLON.serialize()
  56738. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  56739. __decorate([
  56740. BABYLON.serialize()
  56741. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  56742. __decorate([
  56743. BABYLON.serialize()
  56744. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  56745. __decorate([
  56746. BABYLON.serialize()
  56747. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  56748. __decorate([
  56749. BABYLON.serialize()
  56750. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  56751. __decorate([
  56752. BABYLON.serialize()
  56753. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  56754. __decorate([
  56755. BABYLON.serialize()
  56756. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  56757. __decorate([
  56758. BABYLON.serialize()
  56759. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  56760. __decorate([
  56761. BABYLON.serialize()
  56762. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  56763. __decorate([
  56764. BABYLON.serialize()
  56765. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  56766. return StandardRenderingPipeline;
  56767. }(BABYLON.PostProcessRenderPipeline));
  56768. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  56769. })(BABYLON || (BABYLON = {}));
  56770. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  56771. var BABYLON;
  56772. (function (BABYLON) {
  56773. var FxaaPostProcess = (function (_super) {
  56774. __extends(FxaaPostProcess, _super);
  56775. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  56776. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56777. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  56778. _this.onApplyObservable.add(function (effect) {
  56779. var texelSize = _this.texelSize;
  56780. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  56781. });
  56782. return _this;
  56783. }
  56784. return FxaaPostProcess;
  56785. }(BABYLON.PostProcess));
  56786. BABYLON.FxaaPostProcess = FxaaPostProcess;
  56787. })(BABYLON || (BABYLON = {}));
  56788. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  56789. var BABYLON;
  56790. (function (BABYLON) {
  56791. var DefaultRenderingPipeline = (function (_super) {
  56792. __extends(DefaultRenderingPipeline, _super);
  56793. /**
  56794. * @constructor
  56795. * @param {string} name - The rendering pipeline name
  56796. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  56797. * @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)
  56798. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  56799. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  56800. */
  56801. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  56802. if (automaticBuild === void 0) { automaticBuild = true; }
  56803. var _this = _super.call(this, scene.getEngine(), name) || this;
  56804. _this.PassPostProcessId = "PassPostProcessEffect";
  56805. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  56806. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  56807. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  56808. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  56809. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  56810. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  56811. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  56812. // IAnimatable
  56813. _this.animations = [];
  56814. // Values
  56815. _this._bloomEnabled = false;
  56816. _this._fxaaEnabled = false;
  56817. _this._imageProcessingEnabled = true;
  56818. _this._bloomScale = 0.6;
  56819. _this._buildAllowed = true;
  56820. /**
  56821. * Specifies the size of the bloom blur kernel, relative to the final output size
  56822. */
  56823. _this.bloomKernel = 64;
  56824. /**
  56825. * Specifies the weight of the bloom in the final rendering
  56826. */
  56827. _this._bloomWeight = 0.15;
  56828. _this._cameras = cameras || [];
  56829. _this._buildAllowed = automaticBuild;
  56830. // Initialize
  56831. _this._scene = scene;
  56832. var caps = _this._scene.getEngine().getCaps();
  56833. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  56834. // Misc
  56835. if (_this._hdr) {
  56836. if (caps.textureHalfFloatRender) {
  56837. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  56838. }
  56839. else if (caps.textureFloatRender) {
  56840. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  56841. }
  56842. }
  56843. else {
  56844. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  56845. }
  56846. // Attach
  56847. scene.postProcessRenderPipelineManager.addPipeline(_this);
  56848. _this._buildPipeline();
  56849. return _this;
  56850. }
  56851. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  56852. get: function () {
  56853. return this._bloomWeight;
  56854. },
  56855. set: function (value) {
  56856. if (this._bloomWeight === value) {
  56857. return;
  56858. }
  56859. this._bloomWeight = value;
  56860. if (this._hdr && this.copyBack) {
  56861. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  56862. }
  56863. },
  56864. enumerable: true,
  56865. configurable: true
  56866. });
  56867. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  56868. get: function () {
  56869. return this._bloomScale;
  56870. },
  56871. set: function (value) {
  56872. if (this._bloomScale === value) {
  56873. return;
  56874. }
  56875. this._bloomScale = value;
  56876. this._buildPipeline();
  56877. },
  56878. enumerable: true,
  56879. configurable: true
  56880. });
  56881. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  56882. get: function () {
  56883. return this._bloomEnabled;
  56884. },
  56885. set: function (enabled) {
  56886. if (this._bloomEnabled === enabled) {
  56887. return;
  56888. }
  56889. this._bloomEnabled = enabled;
  56890. this._buildPipeline();
  56891. },
  56892. enumerable: true,
  56893. configurable: true
  56894. });
  56895. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  56896. get: function () {
  56897. return this._fxaaEnabled;
  56898. },
  56899. set: function (enabled) {
  56900. if (this._fxaaEnabled === enabled) {
  56901. return;
  56902. }
  56903. this._fxaaEnabled = enabled;
  56904. this._buildPipeline();
  56905. },
  56906. enumerable: true,
  56907. configurable: true
  56908. });
  56909. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  56910. get: function () {
  56911. return this._imageProcessingEnabled;
  56912. },
  56913. set: function (enabled) {
  56914. if (this._imageProcessingEnabled === enabled) {
  56915. return;
  56916. }
  56917. this._imageProcessingEnabled = enabled;
  56918. this._buildPipeline();
  56919. },
  56920. enumerable: true,
  56921. configurable: true
  56922. });
  56923. /**
  56924. * Force the compilation of the entire pipeline.
  56925. */
  56926. DefaultRenderingPipeline.prototype.prepare = function () {
  56927. var previousState = this._buildAllowed;
  56928. this._buildAllowed = true;
  56929. this._buildPipeline();
  56930. this._buildAllowed = previousState;
  56931. };
  56932. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  56933. var _this = this;
  56934. if (!this._buildAllowed) {
  56935. return;
  56936. }
  56937. var engine = this._scene.getEngine();
  56938. this._disposePostProcesses();
  56939. this._reset();
  56940. if (this.bloomEnabled) {
  56941. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  56942. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  56943. if (!this._hdr) {
  56944. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  56945. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  56946. this.highlights.autoClear = false;
  56947. this.highlights.alwaysForcePOT = true;
  56948. }
  56949. 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);
  56950. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  56951. this.blurX.alwaysForcePOT = true;
  56952. this.blurX.autoClear = false;
  56953. this.blurX.onActivateObservable.add(function () {
  56954. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  56955. _this.blurX.kernel = _this.bloomKernel * dw;
  56956. });
  56957. 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);
  56958. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  56959. this.blurY.alwaysForcePOT = true;
  56960. this.blurY.autoClear = false;
  56961. this.blurY.onActivateObservable.add(function () {
  56962. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  56963. _this.blurY.kernel = _this.bloomKernel * dh;
  56964. });
  56965. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  56966. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  56967. this.copyBack.alwaysForcePOT = true;
  56968. if (this._hdr) {
  56969. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  56970. var w = this.bloomWeight;
  56971. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  56972. }
  56973. else {
  56974. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  56975. }
  56976. this.copyBack.autoClear = false;
  56977. }
  56978. if (this._imageProcessingEnabled) {
  56979. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  56980. if (this._hdr) {
  56981. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  56982. }
  56983. else {
  56984. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  56985. }
  56986. }
  56987. if (this.fxaaEnabled) {
  56988. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  56989. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  56990. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  56991. }
  56992. else {
  56993. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  56994. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  56995. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  56996. }
  56997. if (this.bloomEnabled) {
  56998. if (this._hdr) {
  56999. this.copyBack.shareOutputWith(this.blurX);
  57000. if (this.imageProcessing) {
  57001. this.imageProcessing.shareOutputWith(this.pass);
  57002. this.imageProcessing.autoClear = false;
  57003. }
  57004. else if (this.fxaa) {
  57005. this.fxaa.shareOutputWith(this.pass);
  57006. }
  57007. else {
  57008. this.finalMerge.shareOutputWith(this.pass);
  57009. }
  57010. }
  57011. else {
  57012. if (this.fxaa) {
  57013. this.fxaa.shareOutputWith(this.pass);
  57014. }
  57015. else {
  57016. this.finalMerge.shareOutputWith(this.pass);
  57017. }
  57018. }
  57019. }
  57020. if (this._cameras !== null) {
  57021. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  57022. }
  57023. };
  57024. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  57025. for (var i = 0; i < this._cameras.length; i++) {
  57026. var camera = this._cameras[i];
  57027. if (this.pass) {
  57028. this.pass.dispose(camera);
  57029. }
  57030. if (this.highlights) {
  57031. this.highlights.dispose(camera);
  57032. }
  57033. if (this.blurX) {
  57034. this.blurX.dispose(camera);
  57035. }
  57036. if (this.blurY) {
  57037. this.blurY.dispose(camera);
  57038. }
  57039. if (this.copyBack) {
  57040. this.copyBack.dispose(camera);
  57041. }
  57042. if (this.imageProcessing) {
  57043. this.imageProcessing.dispose(camera);
  57044. }
  57045. if (this.fxaa) {
  57046. this.fxaa.dispose(camera);
  57047. }
  57048. if (this.finalMerge) {
  57049. this.finalMerge.dispose(camera);
  57050. }
  57051. }
  57052. this.pass = null;
  57053. this.highlights = null;
  57054. this.blurX = null;
  57055. this.blurY = null;
  57056. this.copyBack = null;
  57057. this.imageProcessing = null;
  57058. this.fxaa = null;
  57059. this.finalMerge = null;
  57060. };
  57061. // Dispose
  57062. DefaultRenderingPipeline.prototype.dispose = function () {
  57063. this._disposePostProcesses();
  57064. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  57065. _super.prototype.dispose.call(this);
  57066. };
  57067. // Serialize rendering pipeline
  57068. DefaultRenderingPipeline.prototype.serialize = function () {
  57069. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  57070. serializationObject.customType = "DefaultRenderingPipeline";
  57071. return serializationObject;
  57072. };
  57073. // Parse serialized pipeline
  57074. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  57075. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  57076. };
  57077. __decorate([
  57078. BABYLON.serialize()
  57079. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  57080. __decorate([
  57081. BABYLON.serialize()
  57082. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  57083. __decorate([
  57084. BABYLON.serialize()
  57085. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  57086. __decorate([
  57087. BABYLON.serialize()
  57088. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  57089. __decorate([
  57090. BABYLON.serialize()
  57091. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  57092. __decorate([
  57093. BABYLON.serialize()
  57094. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  57095. __decorate([
  57096. BABYLON.serialize()
  57097. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  57098. __decorate([
  57099. BABYLON.serialize()
  57100. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  57101. return DefaultRenderingPipeline;
  57102. }(BABYLON.PostProcessRenderPipeline));
  57103. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  57104. })(BABYLON || (BABYLON = {}));
  57105. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  57106. var BABYLON;
  57107. (function (BABYLON) {
  57108. var GeometryBufferRenderer = (function () {
  57109. function GeometryBufferRenderer(scene, ratio) {
  57110. if (ratio === void 0) { ratio = 1; }
  57111. this._viewMatrix = BABYLON.Matrix.Zero();
  57112. this._projectionMatrix = BABYLON.Matrix.Zero();
  57113. this._transformMatrix = BABYLON.Matrix.Zero();
  57114. this._worldViewProjection = BABYLON.Matrix.Zero();
  57115. this._enablePosition = false;
  57116. this._scene = scene;
  57117. this._ratio = ratio;
  57118. // Render target
  57119. this._createRenderTargets();
  57120. }
  57121. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  57122. set: function (meshes) {
  57123. this._multiRenderTarget.renderList = meshes;
  57124. },
  57125. enumerable: true,
  57126. configurable: true
  57127. });
  57128. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  57129. get: function () {
  57130. return this._multiRenderTarget.isSupported;
  57131. },
  57132. enumerable: true,
  57133. configurable: true
  57134. });
  57135. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  57136. get: function () {
  57137. return this._enablePosition;
  57138. },
  57139. set: function (enable) {
  57140. this._enablePosition = enable;
  57141. this.dispose();
  57142. this._createRenderTargets();
  57143. },
  57144. enumerable: true,
  57145. configurable: true
  57146. });
  57147. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  57148. var material = subMesh.getMaterial();
  57149. if (material && material.disableDepthWrite) {
  57150. return false;
  57151. }
  57152. var defines = [];
  57153. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  57154. var mesh = subMesh.getMesh();
  57155. var scene = mesh.getScene();
  57156. // Alpha test
  57157. if (material && material.needAlphaTesting()) {
  57158. defines.push("#define ALPHATEST");
  57159. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  57160. attribs.push(BABYLON.VertexBuffer.UVKind);
  57161. defines.push("#define UV1");
  57162. }
  57163. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  57164. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  57165. defines.push("#define UV2");
  57166. }
  57167. }
  57168. // Buffers
  57169. if (this._enablePosition) {
  57170. defines.push("#define POSITION");
  57171. }
  57172. // Bones
  57173. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57174. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57175. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57176. if (mesh.numBoneInfluencers > 4) {
  57177. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57178. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57179. }
  57180. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57181. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  57182. }
  57183. else {
  57184. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57185. }
  57186. // Instances
  57187. if (useInstances) {
  57188. defines.push("#define INSTANCES");
  57189. attribs.push("world0");
  57190. attribs.push("world1");
  57191. attribs.push("world2");
  57192. attribs.push("world3");
  57193. }
  57194. // Get correct effect
  57195. var join = defines.join("\n");
  57196. if (this._cachedDefines !== join) {
  57197. this._cachedDefines = join;
  57198. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, null, null, null, { buffersCount: this._enablePosition ? 3 : 2 });
  57199. }
  57200. return this._effect.isReady();
  57201. };
  57202. GeometryBufferRenderer.prototype.getGBuffer = function () {
  57203. return this._multiRenderTarget;
  57204. };
  57205. // Methods
  57206. GeometryBufferRenderer.prototype.dispose = function () {
  57207. this.getGBuffer().dispose();
  57208. };
  57209. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  57210. var _this = this;
  57211. var engine = this._scene.getEngine();
  57212. var count = this._enablePosition ? 3 : 2;
  57213. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  57214. if (!this.isSupported) {
  57215. return null;
  57216. }
  57217. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57218. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57219. this._multiRenderTarget.refreshRate = 1;
  57220. this._multiRenderTarget.renderParticles = false;
  57221. this._multiRenderTarget.renderList = null;
  57222. // set default depth value to 1.0 (far away)
  57223. this._multiRenderTarget.onClearObservable.add(function (engine) {
  57224. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  57225. });
  57226. // Custom render function
  57227. var renderSubMesh = function (subMesh) {
  57228. var mesh = subMesh.getRenderingMesh();
  57229. var scene = _this._scene;
  57230. var engine = scene.getEngine();
  57231. // Culling
  57232. engine.setState(subMesh.getMaterial().backFaceCulling);
  57233. // Managing instances
  57234. var batch = mesh._getInstancesRenderList(subMesh._id);
  57235. if (batch.mustReturn) {
  57236. return;
  57237. }
  57238. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  57239. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  57240. engine.enableEffect(_this._effect);
  57241. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  57242. var material = subMesh.getMaterial();
  57243. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  57244. _this._effect.setMatrix("view", scene.getViewMatrix());
  57245. // Alpha test
  57246. if (material && material.needAlphaTesting()) {
  57247. var alphaTexture = material.getAlphaTestTexture();
  57248. _this._effect.setTexture("diffuseSampler", alphaTexture);
  57249. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  57250. }
  57251. // Bones
  57252. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57253. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  57254. }
  57255. // Draw
  57256. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  57257. }
  57258. };
  57259. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  57260. var index;
  57261. if (depthOnlySubMeshes.length) {
  57262. engine.setColorWrite(false);
  57263. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  57264. renderSubMesh(depthOnlySubMeshes.data[index]);
  57265. }
  57266. engine.setColorWrite(true);
  57267. }
  57268. for (index = 0; index < opaqueSubMeshes.length; index++) {
  57269. renderSubMesh(opaqueSubMeshes.data[index]);
  57270. }
  57271. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  57272. renderSubMesh(alphaTestSubMeshes.data[index]);
  57273. }
  57274. };
  57275. };
  57276. return GeometryBufferRenderer;
  57277. }());
  57278. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  57279. })(BABYLON || (BABYLON = {}));
  57280. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  57281. var BABYLON;
  57282. (function (BABYLON) {
  57283. var RefractionPostProcess = (function (_super) {
  57284. __extends(RefractionPostProcess, _super);
  57285. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  57286. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  57287. _this.color = color;
  57288. _this.depth = depth;
  57289. _this.colorLevel = colorLevel;
  57290. _this.onActivateObservable.add(function (cam) {
  57291. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  57292. });
  57293. _this.onApplyObservable.add(function (effect) {
  57294. effect.setColor3("baseColor", _this.color);
  57295. effect.setFloat("depth", _this.depth);
  57296. effect.setFloat("colorLevel", _this.colorLevel);
  57297. effect.setTexture("refractionSampler", _this._refRexture);
  57298. });
  57299. return _this;
  57300. }
  57301. // Methods
  57302. RefractionPostProcess.prototype.dispose = function (camera) {
  57303. if (this._refRexture) {
  57304. this._refRexture.dispose();
  57305. }
  57306. _super.prototype.dispose.call(this, camera);
  57307. };
  57308. return RefractionPostProcess;
  57309. }(BABYLON.PostProcess));
  57310. BABYLON.RefractionPostProcess = RefractionPostProcess;
  57311. })(BABYLON || (BABYLON = {}));
  57312. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  57313. var BABYLON;
  57314. (function (BABYLON) {
  57315. var BlackAndWhitePostProcess = (function (_super) {
  57316. __extends(BlackAndWhitePostProcess, _super);
  57317. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  57318. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  57319. _this.degree = 1;
  57320. _this.onApplyObservable.add(function (effect) {
  57321. effect.setFloat("degree", _this.degree);
  57322. });
  57323. return _this;
  57324. }
  57325. return BlackAndWhitePostProcess;
  57326. }(BABYLON.PostProcess));
  57327. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  57328. })(BABYLON || (BABYLON = {}));
  57329. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  57330. var BABYLON;
  57331. (function (BABYLON) {
  57332. var ConvolutionPostProcess = (function (_super) {
  57333. __extends(ConvolutionPostProcess, _super);
  57334. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  57335. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  57336. _this.kernel = kernel;
  57337. _this.onApply = function (effect) {
  57338. effect.setFloat2("screenSize", _this.width, _this.height);
  57339. effect.setArray("kernel", _this.kernel);
  57340. };
  57341. return _this;
  57342. }
  57343. // Statics
  57344. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  57345. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  57346. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  57347. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  57348. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  57349. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  57350. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  57351. return ConvolutionPostProcess;
  57352. }(BABYLON.PostProcess));
  57353. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  57354. })(BABYLON || (BABYLON = {}));
  57355. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  57356. var BABYLON;
  57357. (function (BABYLON) {
  57358. var FilterPostProcess = (function (_super) {
  57359. __extends(FilterPostProcess, _super);
  57360. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  57361. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  57362. _this.kernelMatrix = kernelMatrix;
  57363. _this.onApply = function (effect) {
  57364. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  57365. };
  57366. return _this;
  57367. }
  57368. return FilterPostProcess;
  57369. }(BABYLON.PostProcess));
  57370. BABYLON.FilterPostProcess = FilterPostProcess;
  57371. })(BABYLON || (BABYLON = {}));
  57372. //# sourceMappingURL=babylon.filterPostProcess.js.map
  57373. var BABYLON;
  57374. (function (BABYLON) {
  57375. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  57376. var VolumetricLightScatteringPostProcess = (function (_super) {
  57377. __extends(VolumetricLightScatteringPostProcess, _super);
  57378. /**
  57379. * @constructor
  57380. * @param {string} name - The post-process name
  57381. * @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)
  57382. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  57383. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  57384. * @param {number} samples - The post-process quality, default 100
  57385. * @param {number} samplingMode - The post-process filtering mode
  57386. * @param {BABYLON.Engine} engine - The babylon engine
  57387. * @param {boolean} reusable - If the post-process is reusable
  57388. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  57389. */
  57390. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  57391. if (samples === void 0) { samples = 100; }
  57392. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  57393. 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;
  57394. _this._screenCoordinates = BABYLON.Vector2.Zero();
  57395. /**
  57396. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  57397. * @type {Vector3}
  57398. */
  57399. _this.customMeshPosition = BABYLON.Vector3.Zero();
  57400. /**
  57401. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  57402. * @type {boolean}
  57403. */
  57404. _this.useCustomMeshPosition = false;
  57405. /**
  57406. * If the post-process should inverse the light scattering direction
  57407. * @type {boolean}
  57408. */
  57409. _this.invert = true;
  57410. /**
  57411. * Array containing the excluded meshes not rendered in the internal pass
  57412. */
  57413. _this.excludedMeshes = new Array();
  57414. /**
  57415. * Controls the overall intensity of the post-process
  57416. * @type {number}
  57417. */
  57418. _this.exposure = 0.3;
  57419. /**
  57420. * Dissipates each sample's contribution in range [0, 1]
  57421. * @type {number}
  57422. */
  57423. _this.decay = 0.96815;
  57424. /**
  57425. * Controls the overall intensity of each sample
  57426. * @type {number}
  57427. */
  57428. _this.weight = 0.58767;
  57429. /**
  57430. * Controls the density of each sample
  57431. * @type {number}
  57432. */
  57433. _this.density = 0.926;
  57434. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  57435. var engine = scene.getEngine();
  57436. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  57437. // Configure mesh
  57438. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  57439. // Configure
  57440. _this._createPass(scene, ratio.passRatio || ratio);
  57441. _this.onActivate = function (camera) {
  57442. if (!_this.isSupported) {
  57443. _this.dispose(camera);
  57444. }
  57445. _this.onActivate = null;
  57446. };
  57447. _this.onApplyObservable.add(function (effect) {
  57448. _this._updateMeshScreenCoordinates(scene);
  57449. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  57450. effect.setFloat("exposure", _this.exposure);
  57451. effect.setFloat("decay", _this.decay);
  57452. effect.setFloat("weight", _this.weight);
  57453. effect.setFloat("density", _this.density);
  57454. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  57455. });
  57456. return _this;
  57457. }
  57458. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  57459. get: function () {
  57460. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  57461. return false;
  57462. },
  57463. set: function (useDiffuseColor) {
  57464. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  57465. },
  57466. enumerable: true,
  57467. configurable: true
  57468. });
  57469. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  57470. return "VolumetricLightScatteringPostProcess";
  57471. };
  57472. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  57473. var mesh = subMesh.getMesh();
  57474. // Render this.mesh as default
  57475. if (mesh === this.mesh) {
  57476. return mesh.material.isReady(mesh);
  57477. }
  57478. var defines = [];
  57479. var attribs = [BABYLON.VertexBuffer.PositionKind];
  57480. var material = subMesh.getMaterial();
  57481. var needUV = false;
  57482. // Alpha test
  57483. if (material) {
  57484. if (material.needAlphaTesting()) {
  57485. defines.push("#define ALPHATEST");
  57486. }
  57487. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  57488. attribs.push(BABYLON.VertexBuffer.UVKind);
  57489. defines.push("#define UV1");
  57490. }
  57491. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  57492. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  57493. defines.push("#define UV2");
  57494. }
  57495. }
  57496. // Bones
  57497. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57498. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57499. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57500. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57501. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  57502. }
  57503. else {
  57504. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57505. }
  57506. // Instances
  57507. if (useInstances) {
  57508. defines.push("#define INSTANCES");
  57509. attribs.push("world0");
  57510. attribs.push("world1");
  57511. attribs.push("world2");
  57512. attribs.push("world3");
  57513. }
  57514. // Get correct effect
  57515. var join = defines.join("\n");
  57516. if (this._cachedDefines !== join) {
  57517. this._cachedDefines = join;
  57518. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  57519. }
  57520. return this._volumetricLightScatteringPass.isReady();
  57521. };
  57522. /**
  57523. * Sets the new light position for light scattering effect
  57524. * @param {BABYLON.Vector3} The new custom light position
  57525. */
  57526. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  57527. this.customMeshPosition = position;
  57528. };
  57529. /**
  57530. * Returns the light position for light scattering effect
  57531. * @return {BABYLON.Vector3} The custom light position
  57532. */
  57533. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  57534. return this.customMeshPosition;
  57535. };
  57536. /**
  57537. * Disposes the internal assets and detaches the post-process from the camera
  57538. */
  57539. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  57540. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  57541. if (rttIndex !== -1) {
  57542. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  57543. }
  57544. this._volumetricLightScatteringRTT.dispose();
  57545. _super.prototype.dispose.call(this, camera);
  57546. };
  57547. /**
  57548. * Returns the render target texture used by the post-process
  57549. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  57550. */
  57551. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  57552. return this._volumetricLightScatteringRTT;
  57553. };
  57554. // Private methods
  57555. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  57556. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  57557. return true;
  57558. }
  57559. return false;
  57560. };
  57561. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  57562. var _this = this;
  57563. var engine = scene.getEngine();
  57564. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  57565. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57566. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57567. this._volumetricLightScatteringRTT.renderList = null;
  57568. this._volumetricLightScatteringRTT.renderParticles = false;
  57569. var camera = this.getCamera();
  57570. if (camera) {
  57571. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  57572. }
  57573. else {
  57574. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  57575. }
  57576. // Custom render function for submeshes
  57577. var renderSubMesh = function (subMesh) {
  57578. var mesh = subMesh.getRenderingMesh();
  57579. if (_this._meshExcluded(mesh)) {
  57580. return;
  57581. }
  57582. var scene = mesh.getScene();
  57583. var engine = scene.getEngine();
  57584. // Culling
  57585. engine.setState(subMesh.getMaterial().backFaceCulling);
  57586. // Managing instances
  57587. var batch = mesh._getInstancesRenderList(subMesh._id);
  57588. if (batch.mustReturn) {
  57589. return;
  57590. }
  57591. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  57592. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  57593. var effect = _this._volumetricLightScatteringPass;
  57594. if (mesh === _this.mesh) {
  57595. if (subMesh.effect) {
  57596. effect = subMesh.effect;
  57597. }
  57598. else {
  57599. effect = subMesh.getMaterial().getEffect();
  57600. }
  57601. }
  57602. engine.enableEffect(effect);
  57603. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  57604. if (mesh === _this.mesh) {
  57605. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  57606. }
  57607. else {
  57608. var material = subMesh.getMaterial();
  57609. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  57610. // Alpha test
  57611. if (material && material.needAlphaTesting()) {
  57612. var alphaTexture = material.getAlphaTestTexture();
  57613. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  57614. if (alphaTexture) {
  57615. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  57616. }
  57617. }
  57618. // Bones
  57619. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57620. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  57621. }
  57622. }
  57623. // Draw
  57624. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  57625. }
  57626. };
  57627. // Render target texture callbacks
  57628. var savedSceneClearColor;
  57629. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  57630. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  57631. savedSceneClearColor = scene.clearColor;
  57632. scene.clearColor = sceneClearColor;
  57633. });
  57634. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  57635. scene.clearColor = savedSceneClearColor;
  57636. });
  57637. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  57638. var engine = scene.getEngine();
  57639. var index;
  57640. if (depthOnlySubMeshes.length) {
  57641. engine.setColorWrite(false);
  57642. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  57643. renderSubMesh(depthOnlySubMeshes.data[index]);
  57644. }
  57645. engine.setColorWrite(true);
  57646. }
  57647. for (index = 0; index < opaqueSubMeshes.length; index++) {
  57648. renderSubMesh(opaqueSubMeshes.data[index]);
  57649. }
  57650. engine.setAlphaTesting(true);
  57651. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  57652. renderSubMesh(alphaTestSubMeshes.data[index]);
  57653. }
  57654. engine.setAlphaTesting(false);
  57655. if (transparentSubMeshes.length) {
  57656. // Sort sub meshes
  57657. for (index = 0; index < transparentSubMeshes.length; index++) {
  57658. var submesh = transparentSubMeshes.data[index];
  57659. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  57660. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  57661. }
  57662. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  57663. sortedArray.sort(function (a, b) {
  57664. // Alpha index first
  57665. if (a._alphaIndex > b._alphaIndex) {
  57666. return 1;
  57667. }
  57668. if (a._alphaIndex < b._alphaIndex) {
  57669. return -1;
  57670. }
  57671. // Then distance to camera
  57672. if (a._distanceToCamera < b._distanceToCamera) {
  57673. return 1;
  57674. }
  57675. if (a._distanceToCamera > b._distanceToCamera) {
  57676. return -1;
  57677. }
  57678. return 0;
  57679. });
  57680. // Render sub meshes
  57681. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57682. for (index = 0; index < sortedArray.length; index++) {
  57683. renderSubMesh(sortedArray[index]);
  57684. }
  57685. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57686. }
  57687. };
  57688. };
  57689. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  57690. var transform = scene.getTransformMatrix();
  57691. var meshPosition;
  57692. if (this.useCustomMeshPosition) {
  57693. meshPosition = this.customMeshPosition;
  57694. }
  57695. else if (this.attachedNode) {
  57696. meshPosition = this.attachedNode.position;
  57697. }
  57698. else {
  57699. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  57700. }
  57701. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  57702. this._screenCoordinates.x = pos.x / this._viewPort.width;
  57703. this._screenCoordinates.y = pos.y / this._viewPort.height;
  57704. if (this.invert)
  57705. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  57706. };
  57707. // Static methods
  57708. /**
  57709. * Creates a default mesh for the Volumeric Light Scattering post-process
  57710. * @param {string} The mesh name
  57711. * @param {BABYLON.Scene} The scene where to create the mesh
  57712. * @return {BABYLON.Mesh} the default mesh
  57713. */
  57714. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  57715. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  57716. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  57717. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  57718. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  57719. mesh.material = material;
  57720. return mesh;
  57721. };
  57722. __decorate([
  57723. BABYLON.serializeAsVector3()
  57724. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  57725. __decorate([
  57726. BABYLON.serialize()
  57727. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  57728. __decorate([
  57729. BABYLON.serialize()
  57730. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  57731. __decorate([
  57732. BABYLON.serializeAsMeshReference()
  57733. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  57734. __decorate([
  57735. BABYLON.serialize()
  57736. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  57737. __decorate([
  57738. BABYLON.serialize()
  57739. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  57740. __decorate([
  57741. BABYLON.serialize()
  57742. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  57743. __decorate([
  57744. BABYLON.serialize()
  57745. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  57746. __decorate([
  57747. BABYLON.serialize()
  57748. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  57749. return VolumetricLightScatteringPostProcess;
  57750. }(BABYLON.PostProcess));
  57751. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  57752. })(BABYLON || (BABYLON = {}));
  57753. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  57754. //
  57755. // This post-process allows the modification of rendered colors by using
  57756. // a 'look-up table' (LUT). This effect is also called Color Grading.
  57757. //
  57758. // The object needs to be provided an url to a texture containing the color
  57759. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  57760. // Use an image editing software to tweak the LUT to match your needs.
  57761. //
  57762. // For an example of a color LUT, see here:
  57763. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  57764. // For explanations on color grading, see here:
  57765. // http://udn.epicgames.com/Three/ColorGrading.html
  57766. //
  57767. var BABYLON;
  57768. (function (BABYLON) {
  57769. var ColorCorrectionPostProcess = (function (_super) {
  57770. __extends(ColorCorrectionPostProcess, _super);
  57771. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  57772. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  57773. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  57774. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  57775. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57776. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57777. _this.onApply = function (effect) {
  57778. effect.setTexture("colorTable", _this._colorTableTexture);
  57779. };
  57780. return _this;
  57781. }
  57782. return ColorCorrectionPostProcess;
  57783. }(BABYLON.PostProcess));
  57784. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  57785. })(BABYLON || (BABYLON = {}));
  57786. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  57787. var BABYLON;
  57788. (function (BABYLON) {
  57789. var TonemappingOperator;
  57790. (function (TonemappingOperator) {
  57791. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  57792. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  57793. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  57794. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  57795. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  57796. ;
  57797. var TonemapPostProcess = (function (_super) {
  57798. __extends(TonemapPostProcess, _super);
  57799. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  57800. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  57801. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57802. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  57803. _this._operator = _operator;
  57804. _this.exposureAdjustment = exposureAdjustment;
  57805. var defines = "#define ";
  57806. if (_this._operator === TonemappingOperator.Hable)
  57807. defines += "HABLE_TONEMAPPING";
  57808. else if (_this._operator === TonemappingOperator.Reinhard)
  57809. defines += "REINHARD_TONEMAPPING";
  57810. else if (_this._operator === TonemappingOperator.HejiDawson)
  57811. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  57812. else if (_this._operator === TonemappingOperator.Photographic)
  57813. defines += "PHOTOGRAPHIC_TONEMAPPING";
  57814. //sadly a second call to create the effect.
  57815. _this.updateEffect(defines);
  57816. _this.onApply = function (effect) {
  57817. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  57818. };
  57819. return _this;
  57820. }
  57821. return TonemapPostProcess;
  57822. }(BABYLON.PostProcess));
  57823. BABYLON.TonemapPostProcess = TonemapPostProcess;
  57824. })(BABYLON || (BABYLON = {}));
  57825. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  57826. var BABYLON;
  57827. (function (BABYLON) {
  57828. var DisplayPassPostProcess = (function (_super) {
  57829. __extends(DisplayPassPostProcess, _super);
  57830. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  57831. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  57832. }
  57833. return DisplayPassPostProcess;
  57834. }(BABYLON.PostProcess));
  57835. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  57836. })(BABYLON || (BABYLON = {}));
  57837. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  57838. var BABYLON;
  57839. (function (BABYLON) {
  57840. var HighlightsPostProcess = (function (_super) {
  57841. __extends(HighlightsPostProcess, _super);
  57842. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  57843. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57844. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  57845. }
  57846. return HighlightsPostProcess;
  57847. }(BABYLON.PostProcess));
  57848. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  57849. })(BABYLON || (BABYLON = {}));
  57850. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  57851. var BABYLON;
  57852. (function (BABYLON) {
  57853. var ImageProcessingPostProcess = (function (_super) {
  57854. __extends(ImageProcessingPostProcess, _super);
  57855. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  57856. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57857. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  57858. _this._fromLinearSpace = true;
  57859. /**
  57860. * Defines cache preventing GC.
  57861. */
  57862. _this._defines = {
  57863. IMAGEPROCESSING: false,
  57864. VIGNETTE: false,
  57865. VIGNETTEBLENDMODEMULTIPLY: false,
  57866. VIGNETTEBLENDMODEOPAQUE: false,
  57867. TONEMAPPING: false,
  57868. CONTRAST: false,
  57869. COLORCURVES: false,
  57870. COLORGRADING: false,
  57871. FROMLINEARSPACE: false,
  57872. SAMPLER3DGREENDEPTH: false,
  57873. SAMPLER3DBGRMAP: false,
  57874. IMAGEPROCESSINGPOSTPROCESS: false,
  57875. EXPOSURE: false,
  57876. };
  57877. // Setup the default processing configuration to the scene.
  57878. _this._attachImageProcessingConfiguration(null, true);
  57879. _this.imageProcessingConfiguration.applyByPostProcess = true;
  57880. _this.onApply = function (effect) {
  57881. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  57882. };
  57883. return _this;
  57884. }
  57885. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  57886. /**
  57887. * Gets the image processing configuration used either in this material.
  57888. */
  57889. get: function () {
  57890. return this._imageProcessingConfiguration;
  57891. },
  57892. /**
  57893. * Sets the Default image processing configuration used either in the this material.
  57894. *
  57895. * If sets to null, the scene one is in use.
  57896. */
  57897. set: function (value) {
  57898. this._attachImageProcessingConfiguration(value);
  57899. },
  57900. enumerable: true,
  57901. configurable: true
  57902. });
  57903. /**
  57904. * Attaches a new image processing configuration to the PBR Material.
  57905. * @param configuration
  57906. */
  57907. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  57908. var _this = this;
  57909. if (doNotBuild === void 0) { doNotBuild = false; }
  57910. if (configuration === this._imageProcessingConfiguration) {
  57911. return;
  57912. }
  57913. // Detaches observer.
  57914. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  57915. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  57916. }
  57917. // Pick the scene configuration if needed.
  57918. if (!configuration) {
  57919. var scene = null;
  57920. var engine = this.getEngine();
  57921. var camera = this.getCamera();
  57922. if (camera) {
  57923. scene = camera.getScene();
  57924. }
  57925. else if (engine && engine.scenes) {
  57926. var scenes = engine.scenes;
  57927. scene = scenes[scenes.length - 1];
  57928. }
  57929. else {
  57930. scene = BABYLON.Engine.LastCreatedScene;
  57931. }
  57932. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  57933. }
  57934. else {
  57935. this._imageProcessingConfiguration = configuration;
  57936. }
  57937. // Attaches observer.
  57938. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  57939. _this._updateParameters();
  57940. });
  57941. // Ensure the effect will be rebuilt.
  57942. if (!doNotBuild) {
  57943. this._updateParameters();
  57944. }
  57945. };
  57946. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  57947. /**
  57948. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  57949. */
  57950. get: function () {
  57951. return this.imageProcessingConfiguration.colorCurves;
  57952. },
  57953. /**
  57954. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  57955. */
  57956. set: function (value) {
  57957. this.imageProcessingConfiguration.colorCurves = value;
  57958. },
  57959. enumerable: true,
  57960. configurable: true
  57961. });
  57962. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  57963. /**
  57964. * Gets wether the color curves effect is enabled.
  57965. */
  57966. get: function () {
  57967. return this.imageProcessingConfiguration.colorCurvesEnabled;
  57968. },
  57969. /**
  57970. * Sets wether the color curves effect is enabled.
  57971. */
  57972. set: function (value) {
  57973. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  57974. },
  57975. enumerable: true,
  57976. configurable: true
  57977. });
  57978. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  57979. /**
  57980. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  57981. */
  57982. get: function () {
  57983. return this.imageProcessingConfiguration.colorGradingTexture;
  57984. },
  57985. /**
  57986. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  57987. */
  57988. set: function (value) {
  57989. this.imageProcessingConfiguration.colorGradingTexture = value;
  57990. },
  57991. enumerable: true,
  57992. configurable: true
  57993. });
  57994. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  57995. /**
  57996. * Gets wether the color grading effect is enabled.
  57997. */
  57998. get: function () {
  57999. return this.imageProcessingConfiguration.colorGradingEnabled;
  58000. },
  58001. /**
  58002. * Gets wether the color grading effect is enabled.
  58003. */
  58004. set: function (value) {
  58005. this.imageProcessingConfiguration.colorGradingEnabled = value;
  58006. },
  58007. enumerable: true,
  58008. configurable: true
  58009. });
  58010. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  58011. /**
  58012. * Gets exposure used in the effect.
  58013. */
  58014. get: function () {
  58015. return this.imageProcessingConfiguration.exposure;
  58016. },
  58017. /**
  58018. * Sets exposure used in the effect.
  58019. */
  58020. set: function (value) {
  58021. this.imageProcessingConfiguration.exposure = value;
  58022. },
  58023. enumerable: true,
  58024. configurable: true
  58025. });
  58026. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  58027. /**
  58028. * Gets wether tonemapping is enabled or not.
  58029. */
  58030. get: function () {
  58031. return this._imageProcessingConfiguration.toneMappingEnabled;
  58032. },
  58033. /**
  58034. * Sets wether tonemapping is enabled or not
  58035. */
  58036. set: function (value) {
  58037. this._imageProcessingConfiguration.toneMappingEnabled = value;
  58038. },
  58039. enumerable: true,
  58040. configurable: true
  58041. });
  58042. ;
  58043. ;
  58044. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  58045. /**
  58046. * Gets contrast used in the effect.
  58047. */
  58048. get: function () {
  58049. return this.imageProcessingConfiguration.contrast;
  58050. },
  58051. /**
  58052. * Sets contrast used in the effect.
  58053. */
  58054. set: function (value) {
  58055. this.imageProcessingConfiguration.contrast = value;
  58056. },
  58057. enumerable: true,
  58058. configurable: true
  58059. });
  58060. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  58061. /**
  58062. * Gets Vignette stretch size.
  58063. */
  58064. get: function () {
  58065. return this.imageProcessingConfiguration.vignetteStretch;
  58066. },
  58067. /**
  58068. * Sets Vignette stretch size.
  58069. */
  58070. set: function (value) {
  58071. this.imageProcessingConfiguration.vignetteStretch = value;
  58072. },
  58073. enumerable: true,
  58074. configurable: true
  58075. });
  58076. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  58077. /**
  58078. * Gets Vignette centre X Offset.
  58079. */
  58080. get: function () {
  58081. return this.imageProcessingConfiguration.vignetteCentreX;
  58082. },
  58083. /**
  58084. * Sets Vignette centre X Offset.
  58085. */
  58086. set: function (value) {
  58087. this.imageProcessingConfiguration.vignetteCentreX = value;
  58088. },
  58089. enumerable: true,
  58090. configurable: true
  58091. });
  58092. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  58093. /**
  58094. * Gets Vignette centre Y Offset.
  58095. */
  58096. get: function () {
  58097. return this.imageProcessingConfiguration.vignetteCentreY;
  58098. },
  58099. /**
  58100. * Sets Vignette centre Y Offset.
  58101. */
  58102. set: function (value) {
  58103. this.imageProcessingConfiguration.vignetteCentreY = value;
  58104. },
  58105. enumerable: true,
  58106. configurable: true
  58107. });
  58108. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  58109. /**
  58110. * Gets Vignette weight or intensity of the vignette effect.
  58111. */
  58112. get: function () {
  58113. return this.imageProcessingConfiguration.vignetteWeight;
  58114. },
  58115. /**
  58116. * Sets Vignette weight or intensity of the vignette effect.
  58117. */
  58118. set: function (value) {
  58119. this.imageProcessingConfiguration.vignetteWeight = value;
  58120. },
  58121. enumerable: true,
  58122. configurable: true
  58123. });
  58124. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  58125. /**
  58126. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  58127. * if vignetteEnabled is set to true.
  58128. */
  58129. get: function () {
  58130. return this.imageProcessingConfiguration.vignetteColor;
  58131. },
  58132. /**
  58133. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  58134. * if vignetteEnabled is set to true.
  58135. */
  58136. set: function (value) {
  58137. this.imageProcessingConfiguration.vignetteColor = value;
  58138. },
  58139. enumerable: true,
  58140. configurable: true
  58141. });
  58142. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  58143. /**
  58144. * Gets Camera field of view used by the Vignette effect.
  58145. */
  58146. get: function () {
  58147. return this.imageProcessingConfiguration.vignetteCameraFov;
  58148. },
  58149. /**
  58150. * Sets Camera field of view used by the Vignette effect.
  58151. */
  58152. set: function (value) {
  58153. this.imageProcessingConfiguration.vignetteCameraFov = value;
  58154. },
  58155. enumerable: true,
  58156. configurable: true
  58157. });
  58158. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  58159. /**
  58160. * Gets the vignette blend mode allowing different kind of effect.
  58161. */
  58162. get: function () {
  58163. return this.imageProcessingConfiguration.vignetteBlendMode;
  58164. },
  58165. /**
  58166. * Sets the vignette blend mode allowing different kind of effect.
  58167. */
  58168. set: function (value) {
  58169. this.imageProcessingConfiguration.vignetteBlendMode = value;
  58170. },
  58171. enumerable: true,
  58172. configurable: true
  58173. });
  58174. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  58175. /**
  58176. * Gets wether the vignette effect is enabled.
  58177. */
  58178. get: function () {
  58179. return this.imageProcessingConfiguration.vignetteEnabled;
  58180. },
  58181. /**
  58182. * Sets wether the vignette effect is enabled.
  58183. */
  58184. set: function (value) {
  58185. this.imageProcessingConfiguration.vignetteEnabled = value;
  58186. },
  58187. enumerable: true,
  58188. configurable: true
  58189. });
  58190. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  58191. /**
  58192. * Gets wether the input of the processing is in Gamma or Linear Space.
  58193. */
  58194. get: function () {
  58195. return this._fromLinearSpace;
  58196. },
  58197. /**
  58198. * Sets wether the input of the processing is in Gamma or Linear Space.
  58199. */
  58200. set: function (value) {
  58201. if (this._fromLinearSpace === value) {
  58202. return;
  58203. }
  58204. this._fromLinearSpace = value;
  58205. this._updateParameters();
  58206. },
  58207. enumerable: true,
  58208. configurable: true
  58209. });
  58210. ImageProcessingPostProcess.prototype.getClassName = function () {
  58211. return "ImageProcessingPostProcess";
  58212. };
  58213. ImageProcessingPostProcess.prototype._updateParameters = function () {
  58214. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  58215. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  58216. var defines = "";
  58217. for (var define in this._defines) {
  58218. if (this._defines[define]) {
  58219. defines += "#define " + define + ";\r\n";
  58220. }
  58221. }
  58222. var samplers = ["textureSampler"];
  58223. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  58224. var uniforms = ["scale"];
  58225. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  58226. this.updateEffect(defines, uniforms, samplers);
  58227. };
  58228. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  58229. _super.prototype.dispose.call(this, camera);
  58230. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  58231. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  58232. }
  58233. this.imageProcessingConfiguration.applyByPostProcess = false;
  58234. };
  58235. __decorate([
  58236. BABYLON.serialize()
  58237. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  58238. return ImageProcessingPostProcess;
  58239. }(BABYLON.PostProcess));
  58240. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  58241. })(BABYLON || (BABYLON = {}));
  58242. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  58243. var BABYLON;
  58244. (function (BABYLON) {
  58245. var BlurPostProcess = (function (_super) {
  58246. __extends(BlurPostProcess, _super);
  58247. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  58248. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  58249. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58250. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  58251. _this.direction = direction;
  58252. _this._packedFloat = false;
  58253. _this.onApplyObservable.add(function (effect) {
  58254. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  58255. });
  58256. _this.kernel = kernel;
  58257. return _this;
  58258. }
  58259. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  58260. /**
  58261. * Gets the length in pixels of the blur sample region
  58262. */
  58263. get: function () {
  58264. return this._idealKernel;
  58265. },
  58266. /**
  58267. * Sets the length in pixels of the blur sample region
  58268. */
  58269. set: function (v) {
  58270. if (this._idealKernel === v) {
  58271. return;
  58272. }
  58273. v = Math.max(v, 1);
  58274. this._idealKernel = v;
  58275. this._kernel = this._nearestBestKernel(v);
  58276. this._updateParameters();
  58277. },
  58278. enumerable: true,
  58279. configurable: true
  58280. });
  58281. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  58282. /**
  58283. * Gets wether or not the blur is unpacking/repacking floats
  58284. */
  58285. get: function () {
  58286. return this._packedFloat;
  58287. },
  58288. /**
  58289. * Sets wether or not the blur needs to unpack/repack floats
  58290. */
  58291. set: function (v) {
  58292. if (this._packedFloat === v) {
  58293. return;
  58294. }
  58295. this._packedFloat = v;
  58296. this._updateParameters();
  58297. },
  58298. enumerable: true,
  58299. configurable: true
  58300. });
  58301. BlurPostProcess.prototype._updateParameters = function () {
  58302. // Generate sampling offsets and weights
  58303. var N = this._kernel;
  58304. var centerIndex = (N - 1) / 2;
  58305. // Generate Gaussian sampling weights over kernel
  58306. var offsets = [];
  58307. var weights = [];
  58308. var totalWeight = 0;
  58309. for (var i = 0; i < N; i++) {
  58310. var u = i / (N - 1);
  58311. var w = this._gaussianWeight(u * 2.0 - 1);
  58312. offsets[i] = (i - centerIndex);
  58313. weights[i] = w;
  58314. totalWeight += w;
  58315. }
  58316. // Normalize weights
  58317. for (var i = 0; i < weights.length; i++) {
  58318. weights[i] /= totalWeight;
  58319. }
  58320. // Optimize: combine samples to take advantage of hardware linear sampling
  58321. // Walk from left to center, combining pairs (symmetrically)
  58322. var linearSamplingWeights = [];
  58323. var linearSamplingOffsets = [];
  58324. var linearSamplingMap = [];
  58325. for (var i = 0; i <= centerIndex; i += 2) {
  58326. var j = Math.min(i + 1, Math.floor(centerIndex));
  58327. var singleCenterSample = i === j;
  58328. if (singleCenterSample) {
  58329. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  58330. }
  58331. else {
  58332. var sharedCell = j === centerIndex;
  58333. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  58334. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  58335. if (offsetLinear === 0) {
  58336. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  58337. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  58338. }
  58339. else {
  58340. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  58341. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  58342. }
  58343. }
  58344. }
  58345. for (var i = 0; i < linearSamplingMap.length; i++) {
  58346. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  58347. linearSamplingWeights[i] = linearSamplingMap[i].w;
  58348. }
  58349. // Replace with optimized
  58350. offsets = linearSamplingOffsets;
  58351. weights = linearSamplingWeights;
  58352. // Generate shaders
  58353. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  58354. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  58355. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  58356. var defines = "";
  58357. for (var i = 0; i < varyingCount; i++) {
  58358. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  58359. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  58360. }
  58361. var depCount = 0;
  58362. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  58363. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  58364. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  58365. depCount++;
  58366. }
  58367. if (this.packedFloat) {
  58368. defines += "#define PACKEDFLOAT 1";
  58369. }
  58370. this.updateEffect(defines, null, null, {
  58371. varyingCount: varyingCount,
  58372. depCount: depCount
  58373. });
  58374. };
  58375. /**
  58376. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  58377. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  58378. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  58379. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  58380. * The gaps between physical kernels are compensated for in the weighting of the samples
  58381. * @param idealKernel Ideal blur kernel.
  58382. * @return Nearest best kernel.
  58383. */
  58384. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  58385. var v = Math.round(idealKernel);
  58386. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  58387. var k = _a[_i];
  58388. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  58389. return Math.max(k, 3);
  58390. }
  58391. }
  58392. return Math.max(v, 3);
  58393. };
  58394. /**
  58395. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  58396. * @param x The point on the Gaussian distribution to sample.
  58397. * @return the value of the Gaussian function at x.
  58398. */
  58399. BlurPostProcess.prototype._gaussianWeight = function (x) {
  58400. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  58401. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  58402. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  58403. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  58404. // truncated at around 1.3% of peak strength.
  58405. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  58406. var sigma = (1 / 3);
  58407. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  58408. var exponent = -((x * x) / (2.0 * sigma * sigma));
  58409. var weight = (1.0 / denominator) * Math.exp(exponent);
  58410. return weight;
  58411. };
  58412. /**
  58413. * Generates a string that can be used as a floating point number in GLSL.
  58414. * @param x Value to print.
  58415. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  58416. * @return GLSL float string.
  58417. */
  58418. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  58419. if (decimalFigures === void 0) { decimalFigures = 8; }
  58420. return x.toFixed(decimalFigures).replace(/0+$/, '');
  58421. };
  58422. return BlurPostProcess;
  58423. }(BABYLON.PostProcess));
  58424. BABYLON.BlurPostProcess = BlurPostProcess;
  58425. })(BABYLON || (BABYLON = {}));
  58426. //# sourceMappingURL=babylon.blurPostProcess.js.map
  58427. /// <reference path="..\babylon.node.ts" />
  58428. var BABYLON;
  58429. (function (BABYLON) {
  58430. var Bone = (function (_super) {
  58431. __extends(Bone, _super);
  58432. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  58433. if (parentBone === void 0) { parentBone = null; }
  58434. var _this = _super.call(this, name, skeleton.getScene()) || this;
  58435. _this.name = name;
  58436. _this.children = new Array();
  58437. _this.animations = new Array();
  58438. _this._worldTransform = new BABYLON.Matrix();
  58439. _this._absoluteTransform = new BABYLON.Matrix();
  58440. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  58441. _this._scaleMatrix = BABYLON.Matrix.Identity();
  58442. _this._scaleVector = BABYLON.Vector3.One();
  58443. _this._negateScaleChildren = BABYLON.Vector3.One();
  58444. _this._scalingDeterminant = 1;
  58445. _this._skeleton = skeleton;
  58446. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  58447. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  58448. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  58449. _this._index = index;
  58450. skeleton.bones.push(_this);
  58451. _this.setParent(parentBone, false);
  58452. _this._updateDifferenceMatrix();
  58453. return _this;
  58454. }
  58455. Object.defineProperty(Bone.prototype, "_matrix", {
  58456. get: function () {
  58457. return this._localMatrix;
  58458. },
  58459. set: function (val) {
  58460. if (this._localMatrix) {
  58461. this._localMatrix.copyFrom(val);
  58462. }
  58463. else {
  58464. this._localMatrix = val;
  58465. }
  58466. },
  58467. enumerable: true,
  58468. configurable: true
  58469. });
  58470. // Members
  58471. Bone.prototype.getSkeleton = function () {
  58472. return this._skeleton;
  58473. };
  58474. Bone.prototype.getParent = function () {
  58475. return this._parent;
  58476. };
  58477. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  58478. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  58479. if (this._parent === parent) {
  58480. return;
  58481. }
  58482. if (this._parent) {
  58483. var index = this._parent.children.indexOf(this);
  58484. if (index !== -1) {
  58485. this._parent.children.splice(index);
  58486. }
  58487. }
  58488. this._parent = parent;
  58489. if (this._parent) {
  58490. this._parent.children.push(this);
  58491. }
  58492. if (updateDifferenceMatrix) {
  58493. this._updateDifferenceMatrix();
  58494. }
  58495. };
  58496. Bone.prototype.getLocalMatrix = function () {
  58497. return this._localMatrix;
  58498. };
  58499. Bone.prototype.getBaseMatrix = function () {
  58500. return this._baseMatrix;
  58501. };
  58502. Bone.prototype.getRestPose = function () {
  58503. return this._restPose;
  58504. };
  58505. Bone.prototype.returnToRest = function () {
  58506. this.updateMatrix(this._restPose.clone());
  58507. };
  58508. Bone.prototype.getWorldMatrix = function () {
  58509. return this._worldTransform;
  58510. };
  58511. Bone.prototype.getInvertedAbsoluteTransform = function () {
  58512. return this._invertedAbsoluteTransform;
  58513. };
  58514. Bone.prototype.getAbsoluteTransform = function () {
  58515. return this._absoluteTransform;
  58516. };
  58517. Object.defineProperty(Bone.prototype, "position", {
  58518. // Properties (matches AbstractMesh properties)
  58519. get: function () {
  58520. return this.getPosition();
  58521. },
  58522. set: function (newPosition) {
  58523. this.setPosition(newPosition);
  58524. },
  58525. enumerable: true,
  58526. configurable: true
  58527. });
  58528. Object.defineProperty(Bone.prototype, "rotation", {
  58529. get: function () {
  58530. return this.getRotation();
  58531. },
  58532. set: function (newRotation) {
  58533. this.setRotation(newRotation);
  58534. },
  58535. enumerable: true,
  58536. configurable: true
  58537. });
  58538. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  58539. get: function () {
  58540. return this.getRotationQuaternion();
  58541. },
  58542. set: function (newRotation) {
  58543. this.setRotationQuaternion(newRotation);
  58544. },
  58545. enumerable: true,
  58546. configurable: true
  58547. });
  58548. Object.defineProperty(Bone.prototype, "scaling", {
  58549. get: function () {
  58550. return this.getScale();
  58551. },
  58552. set: function (newScaling) {
  58553. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  58554. },
  58555. enumerable: true,
  58556. configurable: true
  58557. });
  58558. // Methods
  58559. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  58560. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  58561. this._baseMatrix = matrix.clone();
  58562. this._localMatrix = matrix.clone();
  58563. this._skeleton._markAsDirty();
  58564. if (updateDifferenceMatrix) {
  58565. this._updateDifferenceMatrix();
  58566. }
  58567. };
  58568. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  58569. if (!rootMatrix) {
  58570. rootMatrix = this._baseMatrix;
  58571. }
  58572. if (this._parent) {
  58573. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  58574. }
  58575. else {
  58576. this._absoluteTransform.copyFrom(rootMatrix);
  58577. }
  58578. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  58579. for (var index = 0; index < this.children.length; index++) {
  58580. this.children[index]._updateDifferenceMatrix();
  58581. }
  58582. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  58583. };
  58584. Bone.prototype.markAsDirty = function () {
  58585. this._currentRenderId++;
  58586. this._skeleton._markAsDirty();
  58587. };
  58588. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  58589. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  58590. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  58591. // all animation may be coming from a library skeleton, so may need to create animation
  58592. if (this.animations.length === 0) {
  58593. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  58594. this.animations[0].setKeys([]);
  58595. }
  58596. // get animation info / verify there is such a range from the source bone
  58597. var sourceRange = source.animations[0].getRange(rangeName);
  58598. if (!sourceRange) {
  58599. return false;
  58600. }
  58601. var from = sourceRange.from;
  58602. var to = sourceRange.to;
  58603. var sourceKeys = source.animations[0].getKeys();
  58604. // rescaling prep
  58605. var sourceBoneLength = source.length;
  58606. var sourceParent = source.getParent();
  58607. var parent = this.getParent();
  58608. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  58609. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  58610. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  58611. var destKeys = this.animations[0].getKeys();
  58612. // loop vars declaration
  58613. var orig;
  58614. var origTranslation;
  58615. var mat;
  58616. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  58617. orig = sourceKeys[key];
  58618. if (orig.frame >= from && orig.frame <= to) {
  58619. if (rescaleAsRequired) {
  58620. mat = orig.value.clone();
  58621. // scale based on parent ratio, when bone has parent
  58622. if (parentScalingReqd) {
  58623. origTranslation = mat.getTranslation();
  58624. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  58625. // scale based on skeleton dimension ratio when root bone, and value is passed
  58626. }
  58627. else if (dimensionsScalingReqd) {
  58628. origTranslation = mat.getTranslation();
  58629. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  58630. // use original when root bone, and no data for skelDimensionsRatio
  58631. }
  58632. else {
  58633. mat = orig.value;
  58634. }
  58635. }
  58636. else {
  58637. mat = orig.value;
  58638. }
  58639. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  58640. }
  58641. }
  58642. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  58643. return true;
  58644. };
  58645. /**
  58646. * Translate the bone in local or world space.
  58647. * @param vec The amount to translate the bone.
  58648. * @param space The space that the translation is in.
  58649. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  58650. */
  58651. Bone.prototype.translate = function (vec, space, mesh) {
  58652. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  58653. var lm = this.getLocalMatrix();
  58654. if (space == BABYLON.Space.LOCAL) {
  58655. lm.m[12] += vec.x;
  58656. lm.m[13] += vec.y;
  58657. lm.m[14] += vec.z;
  58658. }
  58659. else {
  58660. var wm;
  58661. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  58662. if (mesh) {
  58663. wm = mesh.getWorldMatrix();
  58664. }
  58665. this._skeleton.computeAbsoluteTransforms();
  58666. var tmat = Bone._tmpMats[0];
  58667. var tvec = Bone._tmpVecs[0];
  58668. if (mesh) {
  58669. tmat.copyFrom(this._parent.getAbsoluteTransform());
  58670. tmat.multiplyToRef(wm, tmat);
  58671. }
  58672. else {
  58673. tmat.copyFrom(this._parent.getAbsoluteTransform());
  58674. }
  58675. tmat.m[12] = 0;
  58676. tmat.m[13] = 0;
  58677. tmat.m[14] = 0;
  58678. tmat.invert();
  58679. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  58680. lm.m[12] += tvec.x;
  58681. lm.m[13] += tvec.y;
  58682. lm.m[14] += tvec.z;
  58683. }
  58684. this.markAsDirty();
  58685. };
  58686. /**
  58687. * Set the postion of the bone in local or world space.
  58688. * @param position The position to set the bone.
  58689. * @param space The space that the position is in.
  58690. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  58691. */
  58692. Bone.prototype.setPosition = function (position, space, mesh) {
  58693. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  58694. var lm = this.getLocalMatrix();
  58695. if (space == BABYLON.Space.LOCAL) {
  58696. lm.m[12] = position.x;
  58697. lm.m[13] = position.y;
  58698. lm.m[14] = position.z;
  58699. }
  58700. else {
  58701. var wm;
  58702. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  58703. if (mesh) {
  58704. wm = mesh.getWorldMatrix();
  58705. }
  58706. this._skeleton.computeAbsoluteTransforms();
  58707. var tmat = Bone._tmpMats[0];
  58708. var vec = Bone._tmpVecs[0];
  58709. if (mesh) {
  58710. tmat.copyFrom(this._parent.getAbsoluteTransform());
  58711. tmat.multiplyToRef(wm, tmat);
  58712. }
  58713. else {
  58714. tmat.copyFrom(this._parent.getAbsoluteTransform());
  58715. }
  58716. tmat.invert();
  58717. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  58718. lm.m[12] = vec.x;
  58719. lm.m[13] = vec.y;
  58720. lm.m[14] = vec.z;
  58721. }
  58722. this.markAsDirty();
  58723. };
  58724. /**
  58725. * Set the absolute postion of the bone (world space).
  58726. * @param position The position to set the bone.
  58727. * @param mesh The mesh that this bone is attached to.
  58728. */
  58729. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  58730. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  58731. };
  58732. /**
  58733. * Set the scale of the bone on the x, y and z axes.
  58734. * @param x The scale of the bone on the x axis.
  58735. * @param x The scale of the bone on the y axis.
  58736. * @param z The scale of the bone on the z axis.
  58737. * @param scaleChildren Set this to true if children of the bone should be scaled.
  58738. */
  58739. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  58740. if (scaleChildren === void 0) { scaleChildren = false; }
  58741. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  58742. if (!scaleChildren) {
  58743. this._negateScaleChildren.x = 1 / x;
  58744. this._negateScaleChildren.y = 1 / y;
  58745. this._negateScaleChildren.z = 1 / z;
  58746. }
  58747. this._syncScaleVector();
  58748. }
  58749. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  58750. };
  58751. /**
  58752. * Scale the bone on the x, y and z axes.
  58753. * @param x The amount to scale the bone on the x axis.
  58754. * @param x The amount to scale the bone on the y axis.
  58755. * @param z The amount to scale the bone on the z axis.
  58756. * @param scaleChildren Set this to true if children of the bone should be scaled.
  58757. */
  58758. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  58759. if (scaleChildren === void 0) { scaleChildren = false; }
  58760. var locMat = this.getLocalMatrix();
  58761. var origLocMat = Bone._tmpMats[0];
  58762. origLocMat.copyFrom(locMat);
  58763. var origLocMatInv = Bone._tmpMats[1];
  58764. origLocMatInv.copyFrom(origLocMat);
  58765. origLocMatInv.invert();
  58766. var scaleMat = Bone._tmpMats[2];
  58767. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  58768. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  58769. this._scaleVector.x *= x;
  58770. this._scaleVector.y *= y;
  58771. this._scaleVector.z *= z;
  58772. locMat.multiplyToRef(origLocMatInv, locMat);
  58773. locMat.multiplyToRef(scaleMat, locMat);
  58774. locMat.multiplyToRef(origLocMat, locMat);
  58775. var parent = this.getParent();
  58776. if (parent) {
  58777. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  58778. }
  58779. else {
  58780. this.getAbsoluteTransform().copyFrom(locMat);
  58781. }
  58782. var len = this.children.length;
  58783. scaleMat.invert();
  58784. for (var i = 0; i < len; i++) {
  58785. var child = this.children[i];
  58786. var cm = child.getLocalMatrix();
  58787. cm.multiplyToRef(scaleMat, cm);
  58788. var lm = child.getLocalMatrix();
  58789. lm.m[12] *= x;
  58790. lm.m[13] *= y;
  58791. lm.m[14] *= z;
  58792. }
  58793. this.computeAbsoluteTransforms();
  58794. if (scaleChildren) {
  58795. for (var i = 0; i < len; i++) {
  58796. this.children[i].scale(x, y, z, scaleChildren);
  58797. }
  58798. }
  58799. this.markAsDirty();
  58800. };
  58801. /**
  58802. * Set the yaw, pitch, and roll of the bone in local or world space.
  58803. * @param yaw The rotation of the bone on the y axis.
  58804. * @param pitch The rotation of the bone on the x axis.
  58805. * @param roll The rotation of the bone on the z axis.
  58806. * @param space The space that the axes of rotation are in.
  58807. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  58808. */
  58809. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  58810. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  58811. var rotMat = Bone._tmpMats[0];
  58812. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  58813. var rotMatInv = Bone._tmpMats[1];
  58814. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  58815. rotMatInv.multiplyToRef(rotMat, rotMat);
  58816. this._rotateWithMatrix(rotMat, space, mesh);
  58817. };
  58818. /**
  58819. * Rotate the bone on an axis in local or world space.
  58820. * @param axis The axis to rotate the bone on.
  58821. * @param amount The amount to rotate the bone.
  58822. * @param space The space that the axis is in.
  58823. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  58824. */
  58825. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  58826. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  58827. var rmat = Bone._tmpMats[0];
  58828. rmat.m[12] = 0;
  58829. rmat.m[13] = 0;
  58830. rmat.m[14] = 0;
  58831. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  58832. this._rotateWithMatrix(rmat, space, mesh);
  58833. };
  58834. /**
  58835. * Set the rotation of the bone to a particular axis angle in local or world space.
  58836. * @param axis The axis to rotate the bone on.
  58837. * @param angle The angle that the bone should be rotated to.
  58838. * @param space The space that the axis is in.
  58839. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  58840. */
  58841. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  58842. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  58843. var rotMat = Bone._tmpMats[0];
  58844. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  58845. var rotMatInv = Bone._tmpMats[1];
  58846. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  58847. rotMatInv.multiplyToRef(rotMat, rotMat);
  58848. this._rotateWithMatrix(rotMat, space, mesh);
  58849. };
  58850. /**
  58851. * Set the euler rotation of the bone in local of world space.
  58852. * @param rotation The euler rotation that the bone should be set to.
  58853. * @param space The space that the rotation is in.
  58854. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  58855. */
  58856. Bone.prototype.setRotation = function (rotation, space, mesh) {
  58857. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  58858. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  58859. };
  58860. /**
  58861. * Set the quaternion rotation of the bone in local of world space.
  58862. * @param quat The quaternion rotation that the bone should be set to.
  58863. * @param space The space that the rotation is in.
  58864. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  58865. */
  58866. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  58867. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  58868. var rotMatInv = Bone._tmpMats[0];
  58869. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  58870. var rotMat = Bone._tmpMats[1];
  58871. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  58872. rotMatInv.multiplyToRef(rotMat, rotMat);
  58873. this._rotateWithMatrix(rotMat, space, mesh);
  58874. };
  58875. /**
  58876. * Set the rotation matrix of the bone in local of world space.
  58877. * @param rotMat The rotation matrix that the bone should be set to.
  58878. * @param space The space that the rotation is in.
  58879. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  58880. */
  58881. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  58882. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  58883. var rotMatInv = Bone._tmpMats[0];
  58884. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  58885. var rotMat2 = Bone._tmpMats[1];
  58886. rotMat2.copyFrom(rotMat);
  58887. rotMatInv.multiplyToRef(rotMat, rotMat2);
  58888. this._rotateWithMatrix(rotMat2, space, mesh);
  58889. };
  58890. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  58891. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  58892. var lmat = this.getLocalMatrix();
  58893. var lx = lmat.m[12];
  58894. var ly = lmat.m[13];
  58895. var lz = lmat.m[14];
  58896. var parent = this.getParent();
  58897. var parentScale = Bone._tmpMats[3];
  58898. var parentScaleInv = Bone._tmpMats[4];
  58899. if (parent) {
  58900. if (space == BABYLON.Space.WORLD) {
  58901. if (mesh) {
  58902. parentScale.copyFrom(mesh.getWorldMatrix());
  58903. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  58904. }
  58905. else {
  58906. parentScale.copyFrom(parent.getAbsoluteTransform());
  58907. }
  58908. }
  58909. else {
  58910. parentScale = parent._scaleMatrix;
  58911. }
  58912. parentScaleInv.copyFrom(parentScale);
  58913. parentScaleInv.invert();
  58914. lmat.multiplyToRef(parentScale, lmat);
  58915. lmat.multiplyToRef(rmat, lmat);
  58916. lmat.multiplyToRef(parentScaleInv, lmat);
  58917. }
  58918. else {
  58919. if (space == BABYLON.Space.WORLD && mesh) {
  58920. parentScale.copyFrom(mesh.getWorldMatrix());
  58921. parentScaleInv.copyFrom(parentScale);
  58922. parentScaleInv.invert();
  58923. lmat.multiplyToRef(parentScale, lmat);
  58924. lmat.multiplyToRef(rmat, lmat);
  58925. lmat.multiplyToRef(parentScaleInv, lmat);
  58926. }
  58927. else {
  58928. lmat.multiplyToRef(rmat, lmat);
  58929. }
  58930. }
  58931. lmat.m[12] = lx;
  58932. lmat.m[13] = ly;
  58933. lmat.m[14] = lz;
  58934. this.computeAbsoluteTransforms();
  58935. this.markAsDirty();
  58936. };
  58937. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  58938. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  58939. if (space == BABYLON.Space.WORLD) {
  58940. var scaleMatrix = Bone._tmpMats[2];
  58941. scaleMatrix.copyFrom(this._scaleMatrix);
  58942. rotMatInv.copyFrom(this.getAbsoluteTransform());
  58943. if (mesh) {
  58944. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  58945. var meshScale = Bone._tmpMats[3];
  58946. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  58947. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  58948. }
  58949. rotMatInv.invert();
  58950. scaleMatrix.m[0] *= this._scalingDeterminant;
  58951. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  58952. }
  58953. else {
  58954. rotMatInv.copyFrom(this.getLocalMatrix());
  58955. rotMatInv.invert();
  58956. var scaleMatrix = Bone._tmpMats[2];
  58957. scaleMatrix.copyFrom(this._scaleMatrix);
  58958. if (this._parent) {
  58959. var pscaleMatrix = Bone._tmpMats[3];
  58960. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  58961. pscaleMatrix.invert();
  58962. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  58963. }
  58964. else {
  58965. scaleMatrix.m[0] *= this._scalingDeterminant;
  58966. }
  58967. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  58968. }
  58969. };
  58970. /**
  58971. * Get the scale of the bone
  58972. * @returns the scale of the bone
  58973. */
  58974. Bone.prototype.getScale = function () {
  58975. return this._scaleVector.clone();
  58976. };
  58977. /**
  58978. * Copy the scale of the bone to a vector3.
  58979. * @param result The vector3 to copy the scale to
  58980. */
  58981. Bone.prototype.getScaleToRef = function (result) {
  58982. result.copyFrom(this._scaleVector);
  58983. };
  58984. /**
  58985. * Get the position of the bone in local or world space.
  58986. * @param space The space that the returned position is in.
  58987. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  58988. * @returns The position of the bone
  58989. */
  58990. Bone.prototype.getPosition = function (space, mesh) {
  58991. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  58992. var pos = BABYLON.Vector3.Zero();
  58993. this.getPositionToRef(space, mesh, pos);
  58994. return pos;
  58995. };
  58996. /**
  58997. * Copy the position of the bone to a vector3 in local or world space.
  58998. * @param space The space that the returned position is in.
  58999. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59000. * @param result The vector3 to copy the position to.
  59001. */
  59002. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  59003. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59004. if (space == BABYLON.Space.LOCAL) {
  59005. var lm = this.getLocalMatrix();
  59006. result.x = lm.m[12];
  59007. result.y = lm.m[13];
  59008. result.z = lm.m[14];
  59009. }
  59010. else {
  59011. var wm;
  59012. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  59013. if (mesh) {
  59014. wm = mesh.getWorldMatrix();
  59015. }
  59016. this._skeleton.computeAbsoluteTransforms();
  59017. var tmat = Bone._tmpMats[0];
  59018. if (mesh) {
  59019. tmat.copyFrom(this.getAbsoluteTransform());
  59020. tmat.multiplyToRef(wm, tmat);
  59021. }
  59022. else {
  59023. tmat = this.getAbsoluteTransform();
  59024. }
  59025. result.x = tmat.m[12];
  59026. result.y = tmat.m[13];
  59027. result.z = tmat.m[14];
  59028. }
  59029. };
  59030. /**
  59031. * Get the absolute position of the bone (world space).
  59032. * @param mesh The mesh that this bone is attached to.
  59033. * @returns The absolute position of the bone
  59034. */
  59035. Bone.prototype.getAbsolutePosition = function (mesh) {
  59036. var pos = BABYLON.Vector3.Zero();
  59037. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  59038. return pos;
  59039. };
  59040. /**
  59041. * Copy the absolute position of the bone (world space) to the result param.
  59042. * @param mesh The mesh that this bone is attached to.
  59043. * @param result The vector3 to copy the absolute position to.
  59044. */
  59045. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  59046. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  59047. };
  59048. /**
  59049. * Compute the absolute transforms of this bone and its children.
  59050. */
  59051. Bone.prototype.computeAbsoluteTransforms = function () {
  59052. if (this._parent) {
  59053. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  59054. }
  59055. else {
  59056. this._absoluteTransform.copyFrom(this._localMatrix);
  59057. var poseMatrix = this._skeleton.getPoseMatrix();
  59058. if (poseMatrix) {
  59059. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  59060. }
  59061. }
  59062. var children = this.children;
  59063. var len = children.length;
  59064. for (var i = 0; i < len; i++) {
  59065. children[i].computeAbsoluteTransforms();
  59066. }
  59067. };
  59068. Bone.prototype._syncScaleVector = function () {
  59069. var lm = this.getLocalMatrix();
  59070. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  59071. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  59072. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  59073. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  59074. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  59075. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  59076. this._scaleVector.x = xs * Math.sqrt(xsq);
  59077. this._scaleVector.y = ys * Math.sqrt(ysq);
  59078. this._scaleVector.z = zs * Math.sqrt(zsq);
  59079. if (this._parent) {
  59080. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  59081. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  59082. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  59083. }
  59084. 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);
  59085. };
  59086. /**
  59087. * Get the world direction from an axis that is in the local space of the bone.
  59088. * @param localAxis The local direction that is used to compute the world direction.
  59089. * @param mesh The mesh that this bone is attached to.
  59090. * @returns The world direction
  59091. */
  59092. Bone.prototype.getDirection = function (localAxis, mesh) {
  59093. var result = BABYLON.Vector3.Zero();
  59094. this.getDirectionToRef(localAxis, mesh, result);
  59095. return result;
  59096. };
  59097. /**
  59098. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  59099. * @param localAxis The local direction that is used to compute the world direction.
  59100. * @param mesh The mesh that this bone is attached to.
  59101. * @param result The vector3 that the world direction will be copied to.
  59102. */
  59103. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  59104. var wm;
  59105. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  59106. if (mesh) {
  59107. wm = mesh.getWorldMatrix();
  59108. }
  59109. this._skeleton.computeAbsoluteTransforms();
  59110. var mat = Bone._tmpMats[0];
  59111. mat.copyFrom(this.getAbsoluteTransform());
  59112. if (mesh) {
  59113. mat.multiplyToRef(wm, mat);
  59114. }
  59115. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  59116. result.normalize();
  59117. };
  59118. /**
  59119. * Get the euler rotation of the bone in local or world space.
  59120. * @param space The space that the rotation should be in.
  59121. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59122. * @returns The euler rotation
  59123. */
  59124. Bone.prototype.getRotation = function (space, mesh) {
  59125. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59126. var result = BABYLON.Vector3.Zero();
  59127. this.getRotationToRef(space, mesh, result);
  59128. return result;
  59129. };
  59130. /**
  59131. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  59132. * @param space The space that the rotation should be in.
  59133. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59134. * @param result The vector3 that the rotation should be copied to.
  59135. */
  59136. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  59137. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59138. var quat = Bone._tmpQuat;
  59139. this.getRotationQuaternionToRef(space, mesh, quat);
  59140. quat.toEulerAnglesToRef(result);
  59141. };
  59142. /**
  59143. * Get the quaternion rotation of the bone in either local or world space.
  59144. * @param space The space that the rotation should be in.
  59145. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59146. * @returns The quaternion rotation
  59147. */
  59148. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  59149. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59150. var result = BABYLON.Quaternion.Identity();
  59151. this.getRotationQuaternionToRef(space, mesh, result);
  59152. return result;
  59153. };
  59154. /**
  59155. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  59156. * @param space The space that the rotation should be in.
  59157. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59158. * @param result The quaternion that the rotation should be copied to.
  59159. */
  59160. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  59161. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59162. if (space == BABYLON.Space.LOCAL) {
  59163. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  59164. }
  59165. else {
  59166. var mat = Bone._tmpMats[0];
  59167. var amat = this.getAbsoluteTransform();
  59168. if (mesh) {
  59169. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  59170. }
  59171. else {
  59172. mat.copyFrom(amat);
  59173. }
  59174. mat.m[0] *= this._scalingDeterminant;
  59175. mat.m[1] *= this._scalingDeterminant;
  59176. mat.m[2] *= this._scalingDeterminant;
  59177. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  59178. }
  59179. };
  59180. /**
  59181. * Get the rotation matrix of the bone in local or world space.
  59182. * @param space The space that the rotation should be in.
  59183. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59184. * @returns The rotation matrix
  59185. */
  59186. Bone.prototype.getRotationMatrix = function (space, mesh) {
  59187. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59188. var result = BABYLON.Matrix.Identity();
  59189. this.getRotationMatrixToRef(space, mesh, result);
  59190. return result;
  59191. };
  59192. /**
  59193. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  59194. * @param space The space that the rotation should be in.
  59195. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  59196. * @param result The quaternion that the rotation should be copied to.
  59197. */
  59198. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  59199. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  59200. if (space == BABYLON.Space.LOCAL) {
  59201. this.getLocalMatrix().getRotationMatrixToRef(result);
  59202. }
  59203. else {
  59204. var mat = Bone._tmpMats[0];
  59205. var amat = this.getAbsoluteTransform();
  59206. if (mesh) {
  59207. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  59208. }
  59209. else {
  59210. mat.copyFrom(amat);
  59211. }
  59212. mat.m[0] *= this._scalingDeterminant;
  59213. mat.m[1] *= this._scalingDeterminant;
  59214. mat.m[2] *= this._scalingDeterminant;
  59215. mat.getRotationMatrixToRef(result);
  59216. }
  59217. };
  59218. /**
  59219. * Get the world position of a point that is in the local space of the bone.
  59220. * @param position The local position
  59221. * @param mesh The mesh that this bone is attached to.
  59222. * @returns The world position
  59223. */
  59224. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  59225. var result = BABYLON.Vector3.Zero();
  59226. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  59227. return result;
  59228. };
  59229. /**
  59230. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  59231. * @param position The local position
  59232. * @param mesh The mesh that this bone is attached to.
  59233. * @param result The vector3 that the world position should be copied to.
  59234. */
  59235. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  59236. var wm;
  59237. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  59238. if (mesh) {
  59239. wm = mesh.getWorldMatrix();
  59240. }
  59241. this._skeleton.computeAbsoluteTransforms();
  59242. var tmat = Bone._tmpMats[0];
  59243. if (mesh) {
  59244. tmat.copyFrom(this.getAbsoluteTransform());
  59245. tmat.multiplyToRef(wm, tmat);
  59246. }
  59247. else {
  59248. tmat = this.getAbsoluteTransform();
  59249. }
  59250. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  59251. };
  59252. /**
  59253. * Get the local position of a point that is in world space.
  59254. * @param position The world position
  59255. * @param mesh The mesh that this bone is attached to.
  59256. * @returns The local position
  59257. */
  59258. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  59259. var result = BABYLON.Vector3.Zero();
  59260. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  59261. return result;
  59262. };
  59263. /**
  59264. * Get the local position of a point that is in world space and copy it to the result param.
  59265. * @param position The world position
  59266. * @param mesh The mesh that this bone is attached to.
  59267. * @param result The vector3 that the local position should be copied to.
  59268. */
  59269. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  59270. var wm;
  59271. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  59272. if (mesh) {
  59273. wm = mesh.getWorldMatrix();
  59274. }
  59275. this._skeleton.computeAbsoluteTransforms();
  59276. var tmat = Bone._tmpMats[0];
  59277. tmat.copyFrom(this.getAbsoluteTransform());
  59278. if (mesh) {
  59279. tmat.multiplyToRef(wm, tmat);
  59280. }
  59281. tmat.invert();
  59282. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  59283. };
  59284. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59285. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  59286. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  59287. return Bone;
  59288. }(BABYLON.Node));
  59289. BABYLON.Bone = Bone;
  59290. })(BABYLON || (BABYLON = {}));
  59291. //# sourceMappingURL=babylon.bone.js.map
  59292. var BABYLON;
  59293. (function (BABYLON) {
  59294. var BoneIKController = (function () {
  59295. function BoneIKController(mesh, bone, options) {
  59296. this.targetPosition = BABYLON.Vector3.Zero();
  59297. this.poleTargetPosition = BABYLON.Vector3.Zero();
  59298. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  59299. this.poleAngle = 0;
  59300. this.slerpAmount = 1;
  59301. this._bone1Quat = BABYLON.Quaternion.Identity();
  59302. this._bone1Mat = BABYLON.Matrix.Identity();
  59303. this._bone2Ang = Math.PI;
  59304. this._maxAngle = Math.PI;
  59305. this._rightHandedSystem = false;
  59306. this._bendAxis = BABYLON.Vector3.Right();
  59307. this._slerping = false;
  59308. this._adjustRoll = 0;
  59309. this._bone2 = bone;
  59310. this._bone1 = bone.getParent();
  59311. this.mesh = mesh;
  59312. var bonePos = bone.getPosition();
  59313. if (bone.getAbsoluteTransform().determinant() > 0) {
  59314. this._rightHandedSystem = true;
  59315. this._bendAxis.x = 0;
  59316. this._bendAxis.y = 0;
  59317. this._bendAxis.z = -1;
  59318. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  59319. this._adjustRoll = Math.PI * .5;
  59320. this._bendAxis.z = 1;
  59321. }
  59322. }
  59323. if (this._bone1.length) {
  59324. var boneScale1 = this._bone1.getScale();
  59325. var boneScale2 = this._bone2.getScale();
  59326. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  59327. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  59328. }
  59329. else if (this._bone1.children[0]) {
  59330. mesh.computeWorldMatrix(true);
  59331. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  59332. var pos2 = this._bone2.getAbsolutePosition(mesh);
  59333. var pos3 = this._bone1.getAbsolutePosition(mesh);
  59334. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  59335. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  59336. }
  59337. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  59338. this.maxAngle = Math.PI;
  59339. if (options) {
  59340. if (options.targetMesh) {
  59341. this.targetMesh = options.targetMesh;
  59342. this.targetMesh.computeWorldMatrix(true);
  59343. }
  59344. if (options.poleTargetMesh) {
  59345. this.poleTargetMesh = options.poleTargetMesh;
  59346. this.poleTargetMesh.computeWorldMatrix(true);
  59347. }
  59348. else if (options.poleTargetBone) {
  59349. this.poleTargetBone = options.poleTargetBone;
  59350. }
  59351. else if (this._bone1.getParent()) {
  59352. this.poleTargetBone = this._bone1.getParent();
  59353. }
  59354. if (options.poleTargetLocalOffset) {
  59355. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  59356. }
  59357. if (options.poleAngle) {
  59358. this.poleAngle = options.poleAngle;
  59359. }
  59360. if (options.bendAxis) {
  59361. this._bendAxis.copyFrom(options.bendAxis);
  59362. }
  59363. if (options.maxAngle) {
  59364. this.maxAngle = options.maxAngle;
  59365. }
  59366. if (options.slerpAmount) {
  59367. this.slerpAmount = options.slerpAmount;
  59368. }
  59369. }
  59370. }
  59371. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  59372. get: function () {
  59373. return this._maxAngle;
  59374. },
  59375. set: function (value) {
  59376. this._setMaxAngle(value);
  59377. },
  59378. enumerable: true,
  59379. configurable: true
  59380. });
  59381. BoneIKController.prototype._setMaxAngle = function (ang) {
  59382. if (ang < 0) {
  59383. ang = 0;
  59384. }
  59385. if (ang > Math.PI || ang == undefined) {
  59386. ang = Math.PI;
  59387. }
  59388. this._maxAngle = ang;
  59389. var a = this._bone1Length;
  59390. var b = this._bone2Length;
  59391. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  59392. };
  59393. BoneIKController.prototype.update = function () {
  59394. var bone1 = this._bone1;
  59395. var target = this.targetPosition;
  59396. var poleTarget = this.poleTargetPosition;
  59397. var mat1 = BoneIKController._tmpMats[0];
  59398. var mat2 = BoneIKController._tmpMats[1];
  59399. if (this.targetMesh) {
  59400. target.copyFrom(this.targetMesh.getAbsolutePosition());
  59401. }
  59402. if (this.poleTargetBone) {
  59403. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  59404. }
  59405. else if (this.poleTargetMesh) {
  59406. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  59407. }
  59408. var bonePos = BoneIKController._tmpVecs[0];
  59409. var zaxis = BoneIKController._tmpVecs[1];
  59410. var xaxis = BoneIKController._tmpVecs[2];
  59411. var yaxis = BoneIKController._tmpVecs[3];
  59412. var upAxis = BoneIKController._tmpVecs[4];
  59413. var _tmpQuat = BoneIKController._tmpQuat;
  59414. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  59415. poleTarget.subtractToRef(bonePos, upAxis);
  59416. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  59417. upAxis.y = 1;
  59418. }
  59419. else {
  59420. upAxis.normalize();
  59421. }
  59422. target.subtractToRef(bonePos, yaxis);
  59423. yaxis.normalize();
  59424. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  59425. zaxis.normalize();
  59426. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  59427. xaxis.normalize();
  59428. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  59429. var a = this._bone1Length;
  59430. var b = this._bone2Length;
  59431. var c = BABYLON.Vector3.Distance(bonePos, target);
  59432. if (this._maxReach > 0) {
  59433. c = Math.min(this._maxReach, c);
  59434. }
  59435. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  59436. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  59437. if (acosa > 1) {
  59438. acosa = 1;
  59439. }
  59440. if (acosb > 1) {
  59441. acosb = 1;
  59442. }
  59443. if (acosa < -1) {
  59444. acosa = -1;
  59445. }
  59446. if (acosb < -1) {
  59447. acosb = -1;
  59448. }
  59449. var angA = Math.acos(acosa);
  59450. var angB = Math.acos(acosb);
  59451. var angC = -angA - angB;
  59452. if (this._rightHandedSystem) {
  59453. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  59454. mat2.multiplyToRef(mat1, mat1);
  59455. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  59456. mat2.multiplyToRef(mat1, mat1);
  59457. }
  59458. else {
  59459. var _tmpVec = BoneIKController._tmpVecs[5];
  59460. _tmpVec.copyFrom(this._bendAxis);
  59461. _tmpVec.x *= -1;
  59462. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  59463. mat2.multiplyToRef(mat1, mat1);
  59464. }
  59465. if (this.poleAngle) {
  59466. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  59467. mat1.multiplyToRef(mat2, mat1);
  59468. }
  59469. if (this.slerpAmount < 1) {
  59470. if (!this._slerping) {
  59471. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  59472. }
  59473. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  59474. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  59475. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  59476. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  59477. this._slerping = true;
  59478. }
  59479. else {
  59480. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  59481. this._bone1Mat.copyFrom(mat1);
  59482. this._slerping = false;
  59483. }
  59484. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  59485. this._bone2Ang = angC;
  59486. };
  59487. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59488. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  59489. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  59490. return BoneIKController;
  59491. }());
  59492. BABYLON.BoneIKController = BoneIKController;
  59493. })(BABYLON || (BABYLON = {}));
  59494. //# sourceMappingURL=babylon.boneIKController.js.map
  59495. var BABYLON;
  59496. (function (BABYLON) {
  59497. var BoneLookController = (function () {
  59498. /**
  59499. * Create a BoneLookController
  59500. * @param mesh the mesh that the bone belongs to
  59501. * @param bone the bone that will be looking to the target
  59502. * @param target the target Vector3 to look at
  59503. * @param settings optional settings:
  59504. * - maxYaw: the maximum angle the bone will yaw to
  59505. * - minYaw: the minimum angle the bone will yaw to
  59506. * - maxPitch: the maximum angle the bone will pitch to
  59507. * - minPitch: the minimum angle the bone will yaw to
  59508. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  59509. * - upAxis: the up axis of the coordinate system
  59510. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  59511. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  59512. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  59513. * - adjustYaw: used to make an adjustment to the yaw of the bone
  59514. * - adjustPitch: used to make an adjustment to the pitch of the bone
  59515. * - adjustRoll: used to make an adjustment to the roll of the bone
  59516. **/
  59517. function BoneLookController(mesh, bone, target, options) {
  59518. /**
  59519. * The up axis of the coordinate system that is used when the bone is rotated.
  59520. */
  59521. this.upAxis = BABYLON.Vector3.Up();
  59522. /**
  59523. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  59524. */
  59525. this.upAxisSpace = BABYLON.Space.LOCAL;
  59526. /**
  59527. * Used to make an adjustment to the yaw of the bone.
  59528. */
  59529. this.adjustYaw = 0;
  59530. /**
  59531. * Used to make an adjustment to the pitch of the bone.
  59532. */
  59533. this.adjustPitch = 0;
  59534. /**
  59535. * Used to make an adjustment to the roll of the bone.
  59536. */
  59537. this.adjustRoll = 0;
  59538. /**
  59539. * 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).
  59540. */
  59541. this.slerpAmount = 1;
  59542. this._boneQuat = BABYLON.Quaternion.Identity();
  59543. this._slerping = false;
  59544. this._firstFrameSkipped = false;
  59545. this._fowardAxis = BABYLON.Vector3.Forward();
  59546. this.mesh = mesh;
  59547. this.bone = bone;
  59548. this.target = target;
  59549. if (options) {
  59550. if (options.adjustYaw) {
  59551. this.adjustYaw = options.adjustYaw;
  59552. }
  59553. if (options.adjustPitch) {
  59554. this.adjustPitch = options.adjustPitch;
  59555. }
  59556. if (options.adjustRoll) {
  59557. this.adjustRoll = options.adjustRoll;
  59558. }
  59559. if (options.maxYaw != null) {
  59560. this.maxYaw = options.maxYaw;
  59561. }
  59562. else {
  59563. this.maxYaw = Math.PI;
  59564. }
  59565. if (options.minYaw != null) {
  59566. this.minYaw = options.minYaw;
  59567. }
  59568. else {
  59569. this.minYaw = -Math.PI;
  59570. }
  59571. if (options.maxPitch != null) {
  59572. this.maxPitch = options.maxPitch;
  59573. }
  59574. else {
  59575. this.maxPitch = Math.PI;
  59576. }
  59577. if (options.minPitch != null) {
  59578. this.minPitch = options.minPitch;
  59579. }
  59580. else {
  59581. this.minPitch = -Math.PI;
  59582. }
  59583. if (options.slerpAmount != null) {
  59584. this.slerpAmount = options.slerpAmount;
  59585. }
  59586. if (options.upAxis != null) {
  59587. this.upAxis = options.upAxis;
  59588. }
  59589. if (options.upAxisSpace != null) {
  59590. this.upAxisSpace = options.upAxisSpace;
  59591. }
  59592. if (options.yawAxis != null || options.pitchAxis != null) {
  59593. var newYawAxis = BABYLON.Axis.Y;
  59594. var newPitchAxis = BABYLON.Axis.X;
  59595. if (options.yawAxis != null) {
  59596. newYawAxis = options.yawAxis.clone();
  59597. newYawAxis.normalize();
  59598. }
  59599. if (options.pitchAxis != null) {
  59600. newPitchAxis = options.pitchAxis.clone();
  59601. newPitchAxis.normalize();
  59602. }
  59603. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  59604. this._transformYawPitch = BABYLON.Matrix.Identity();
  59605. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  59606. this._transformYawPitchInv = this._transformYawPitch.clone();
  59607. this._transformYawPitch.invert();
  59608. }
  59609. }
  59610. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  59611. this.upAxisSpace = BABYLON.Space.LOCAL;
  59612. }
  59613. }
  59614. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  59615. /**
  59616. * Get/set the minimum yaw angle that the bone can look to.
  59617. */
  59618. get: function () {
  59619. return this._minYaw;
  59620. },
  59621. set: function (value) {
  59622. this._minYaw = value;
  59623. this._minYawSin = Math.sin(value);
  59624. this._minYawCos = Math.cos(value);
  59625. if (this._maxYaw != null) {
  59626. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  59627. this._yawRange = this._maxYaw - this._minYaw;
  59628. }
  59629. },
  59630. enumerable: true,
  59631. configurable: true
  59632. });
  59633. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  59634. /**
  59635. * Get/set the maximum yaw angle that the bone can look to.
  59636. */
  59637. get: function () {
  59638. return this._maxYaw;
  59639. },
  59640. set: function (value) {
  59641. this._maxYaw = value;
  59642. this._maxYawSin = Math.sin(value);
  59643. this._maxYawCos = Math.cos(value);
  59644. if (this._minYaw != null) {
  59645. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  59646. this._yawRange = this._maxYaw - this._minYaw;
  59647. }
  59648. },
  59649. enumerable: true,
  59650. configurable: true
  59651. });
  59652. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  59653. /**
  59654. * Get/set the minimum pitch angle that the bone can look to.
  59655. */
  59656. get: function () {
  59657. return this._minPitch;
  59658. },
  59659. set: function (value) {
  59660. this._minPitch = value;
  59661. this._minPitchTan = Math.tan(value);
  59662. },
  59663. enumerable: true,
  59664. configurable: true
  59665. });
  59666. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  59667. /**
  59668. * Get/set the maximum pitch angle that the bone can look to.
  59669. */
  59670. get: function () {
  59671. return this._maxPitch;
  59672. },
  59673. set: function (value) {
  59674. this._maxPitch = value;
  59675. this._maxPitchTan = Math.tan(value);
  59676. },
  59677. enumerable: true,
  59678. configurable: true
  59679. });
  59680. /**
  59681. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  59682. */
  59683. BoneLookController.prototype.update = function () {
  59684. //skip the first frame when slerping so that the mesh rotation is correct
  59685. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  59686. this._firstFrameSkipped = true;
  59687. return;
  59688. }
  59689. var bone = this.bone;
  59690. var bonePos = BoneLookController._tmpVecs[0];
  59691. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  59692. var target = this.target;
  59693. var _tmpMat1 = BoneLookController._tmpMats[0];
  59694. var _tmpMat2 = BoneLookController._tmpMats[1];
  59695. var mesh = this.mesh;
  59696. var parentBone = bone.getParent();
  59697. var upAxis = BoneLookController._tmpVecs[1];
  59698. upAxis.copyFrom(this.upAxis);
  59699. if (this.upAxisSpace == BABYLON.Space.BONE) {
  59700. if (this._transformYawPitch) {
  59701. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  59702. }
  59703. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  59704. }
  59705. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  59706. mesh.getDirectionToRef(upAxis, upAxis);
  59707. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  59708. upAxis.normalize();
  59709. }
  59710. }
  59711. var checkYaw = false;
  59712. var checkPitch = false;
  59713. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  59714. checkYaw = true;
  59715. }
  59716. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  59717. checkPitch = true;
  59718. }
  59719. if (checkYaw || checkPitch) {
  59720. var spaceMat = BoneLookController._tmpMats[2];
  59721. var spaceMatInv = BoneLookController._tmpMats[3];
  59722. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  59723. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  59724. }
  59725. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  59726. spaceMat.copyFrom(mesh.getWorldMatrix());
  59727. }
  59728. else {
  59729. var forwardAxis = BoneLookController._tmpVecs[2];
  59730. forwardAxis.copyFrom(this._fowardAxis);
  59731. if (this._transformYawPitch) {
  59732. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  59733. }
  59734. if (parentBone) {
  59735. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  59736. }
  59737. else {
  59738. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  59739. }
  59740. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  59741. rightAxis.normalize();
  59742. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  59743. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  59744. }
  59745. spaceMat.invertToRef(spaceMatInv);
  59746. var xzlen;
  59747. if (checkPitch) {
  59748. var localTarget = BoneLookController._tmpVecs[3];
  59749. target.subtractToRef(bonePos, localTarget);
  59750. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  59751. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  59752. var pitch = Math.atan2(localTarget.y, xzlen);
  59753. var newPitch = pitch;
  59754. if (pitch > this._maxPitch) {
  59755. localTarget.y = this._maxPitchTan * xzlen;
  59756. newPitch = this._maxPitch;
  59757. }
  59758. else if (pitch < this._minPitch) {
  59759. localTarget.y = this._minPitchTan * xzlen;
  59760. newPitch = this._minPitch;
  59761. }
  59762. if (pitch != newPitch) {
  59763. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  59764. localTarget.addInPlace(bonePos);
  59765. target = localTarget;
  59766. }
  59767. }
  59768. if (checkYaw) {
  59769. var localTarget = BoneLookController._tmpVecs[4];
  59770. target.subtractToRef(bonePos, localTarget);
  59771. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  59772. var yaw = Math.atan2(localTarget.x, localTarget.z);
  59773. var newYaw = yaw;
  59774. if (yaw > this._maxYaw || yaw < this._minYaw) {
  59775. if (xzlen == null) {
  59776. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  59777. }
  59778. if (this._yawRange > Math.PI) {
  59779. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  59780. localTarget.z = this._maxYawCos * xzlen;
  59781. localTarget.x = this._maxYawSin * xzlen;
  59782. newYaw = this._maxYaw;
  59783. }
  59784. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  59785. localTarget.z = this._minYawCos * xzlen;
  59786. localTarget.x = this._minYawSin * xzlen;
  59787. newYaw = this._minYaw;
  59788. }
  59789. }
  59790. else {
  59791. if (yaw > this._maxYaw) {
  59792. localTarget.z = this._maxYawCos * xzlen;
  59793. localTarget.x = this._maxYawSin * xzlen;
  59794. newYaw = this._maxYaw;
  59795. }
  59796. else if (yaw < this._minYaw) {
  59797. localTarget.z = this._minYawCos * xzlen;
  59798. localTarget.x = this._minYawSin * xzlen;
  59799. newYaw = this._minYaw;
  59800. }
  59801. }
  59802. }
  59803. if (this._slerping && this._yawRange > Math.PI) {
  59804. //are we going to be crossing into the min/max region?
  59805. var boneFwd = BoneLookController._tmpVecs[8];
  59806. boneFwd.copyFrom(BABYLON.Axis.Z);
  59807. if (this._transformYawPitch) {
  59808. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  59809. }
  59810. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  59811. this._boneQuat.toRotationMatrix(boneRotMat);
  59812. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  59813. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  59814. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  59815. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  59816. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  59817. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  59818. if (angBtwTar > angBtwMidYaw) {
  59819. if (xzlen == null) {
  59820. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  59821. }
  59822. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  59823. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  59824. if (angBtwMin < angBtwMax) {
  59825. newYaw = boneYaw + Math.PI * .75;
  59826. localTarget.z = Math.cos(newYaw) * xzlen;
  59827. localTarget.x = Math.sin(newYaw) * xzlen;
  59828. }
  59829. else {
  59830. newYaw = boneYaw - Math.PI * .75;
  59831. localTarget.z = Math.cos(newYaw) * xzlen;
  59832. localTarget.x = Math.sin(newYaw) * xzlen;
  59833. }
  59834. }
  59835. }
  59836. if (yaw != newYaw) {
  59837. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  59838. localTarget.addInPlace(bonePos);
  59839. target = localTarget;
  59840. }
  59841. }
  59842. }
  59843. var zaxis = BoneLookController._tmpVecs[5];
  59844. var xaxis = BoneLookController._tmpVecs[6];
  59845. var yaxis = BoneLookController._tmpVecs[7];
  59846. var _tmpQuat = BoneLookController._tmpQuat;
  59847. target.subtractToRef(bonePos, zaxis);
  59848. zaxis.normalize();
  59849. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  59850. xaxis.normalize();
  59851. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  59852. yaxis.normalize();
  59853. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  59854. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  59855. return;
  59856. }
  59857. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  59858. return;
  59859. }
  59860. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  59861. return;
  59862. }
  59863. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  59864. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  59865. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  59866. }
  59867. if (this.slerpAmount < 1) {
  59868. if (!this._slerping) {
  59869. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  59870. }
  59871. if (this._transformYawPitch) {
  59872. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  59873. }
  59874. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  59875. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  59876. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  59877. this._slerping = true;
  59878. }
  59879. else {
  59880. if (this._transformYawPitch) {
  59881. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  59882. }
  59883. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  59884. this._slerping = false;
  59885. }
  59886. };
  59887. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  59888. var angDiff = ang2 - ang1;
  59889. angDiff %= Math.PI * 2;
  59890. if (angDiff > Math.PI) {
  59891. angDiff -= Math.PI * 2;
  59892. }
  59893. else if (angDiff < -Math.PI) {
  59894. angDiff += Math.PI * 2;
  59895. }
  59896. return angDiff;
  59897. };
  59898. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  59899. ang1 %= (2 * Math.PI);
  59900. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  59901. ang2 %= (2 * Math.PI);
  59902. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  59903. var ab = 0;
  59904. if (ang1 < ang2) {
  59905. ab = ang2 - ang1;
  59906. }
  59907. else {
  59908. ab = ang1 - ang2;
  59909. }
  59910. if (ab > Math.PI) {
  59911. ab = Math.PI * 2 - ab;
  59912. }
  59913. return ab;
  59914. };
  59915. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  59916. ang %= (2 * Math.PI);
  59917. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  59918. ang1 %= (2 * Math.PI);
  59919. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  59920. ang2 %= (2 * Math.PI);
  59921. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  59922. if (ang1 < ang2) {
  59923. if (ang > ang1 && ang < ang2) {
  59924. return true;
  59925. }
  59926. }
  59927. else {
  59928. if (ang > ang2 && ang < ang1) {
  59929. return true;
  59930. }
  59931. }
  59932. return false;
  59933. };
  59934. 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()];
  59935. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  59936. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  59937. return BoneLookController;
  59938. }());
  59939. BABYLON.BoneLookController = BoneLookController;
  59940. })(BABYLON || (BABYLON = {}));
  59941. //# sourceMappingURL=babylon.boneLookController.js.map
  59942. var BABYLON;
  59943. (function (BABYLON) {
  59944. var Skeleton = (function () {
  59945. function Skeleton(name, id, scene) {
  59946. this.name = name;
  59947. this.id = id;
  59948. this.bones = new Array();
  59949. this.needInitialSkinMatrix = false;
  59950. this._isDirty = true;
  59951. this._meshesWithPoseMatrix = new Array();
  59952. this._identity = BABYLON.Matrix.Identity();
  59953. this._ranges = {};
  59954. this._lastAbsoluteTransformsUpdateId = -1;
  59955. // Events
  59956. /**
  59957. * An event triggered before computing the skeleton's matrices
  59958. * @type {BABYLON.Observable}
  59959. */
  59960. this.onBeforeComputeObservable = new BABYLON.Observable();
  59961. this.bones = [];
  59962. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59963. scene.skeletons.push(this);
  59964. //make sure it will recalculate the matrix next time prepare is called.
  59965. this._isDirty = true;
  59966. }
  59967. // Members
  59968. Skeleton.prototype.getTransformMatrices = function (mesh) {
  59969. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  59970. return mesh._bonesTransformMatrices;
  59971. }
  59972. if (!this._transformMatrices) {
  59973. this.prepare();
  59974. }
  59975. return this._transformMatrices;
  59976. };
  59977. Skeleton.prototype.getScene = function () {
  59978. return this._scene;
  59979. };
  59980. // Methods
  59981. /**
  59982. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  59983. */
  59984. Skeleton.prototype.toString = function (fullDetails) {
  59985. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  59986. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  59987. if (fullDetails) {
  59988. ret += ", Ranges: {";
  59989. var first = true;
  59990. for (var name_1 in this._ranges) {
  59991. if (first) {
  59992. ret += ", ";
  59993. first = false;
  59994. }
  59995. ret += name_1;
  59996. }
  59997. ret += "}";
  59998. }
  59999. return ret;
  60000. };
  60001. /**
  60002. * Get bone's index searching by name
  60003. * @param {string} name is bone's name to search for
  60004. * @return {number} Indice of the bone. Returns -1 if not found
  60005. */
  60006. Skeleton.prototype.getBoneIndexByName = function (name) {
  60007. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  60008. if (this.bones[boneIndex].name === name) {
  60009. return boneIndex;
  60010. }
  60011. }
  60012. return -1;
  60013. };
  60014. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  60015. // check name not already in use
  60016. if (!this._ranges[name]) {
  60017. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  60018. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  60019. if (this.bones[i].animations[0]) {
  60020. this.bones[i].animations[0].createRange(name, from, to);
  60021. }
  60022. }
  60023. }
  60024. };
  60025. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  60026. if (deleteFrames === void 0) { deleteFrames = true; }
  60027. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  60028. if (this.bones[i].animations[0]) {
  60029. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  60030. }
  60031. }
  60032. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  60033. };
  60034. Skeleton.prototype.getAnimationRange = function (name) {
  60035. return this._ranges[name];
  60036. };
  60037. /**
  60038. * Returns as an Array, all AnimationRanges defined on this skeleton
  60039. */
  60040. Skeleton.prototype.getAnimationRanges = function () {
  60041. var animationRanges = [];
  60042. var name;
  60043. var i = 0;
  60044. for (name in this._ranges) {
  60045. animationRanges[i] = this._ranges[name];
  60046. i++;
  60047. }
  60048. return animationRanges;
  60049. };
  60050. /**
  60051. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  60052. */
  60053. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  60054. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  60055. if (this._ranges[name] || !source.getAnimationRange(name)) {
  60056. return false;
  60057. }
  60058. var ret = true;
  60059. var frameOffset = this._getHighestAnimationFrame() + 1;
  60060. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  60061. var boneDict = {};
  60062. var sourceBones = source.bones;
  60063. var nBones;
  60064. var i;
  60065. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  60066. boneDict[sourceBones[i].name] = sourceBones[i];
  60067. }
  60068. if (this.bones.length !== sourceBones.length) {
  60069. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  60070. ret = false;
  60071. }
  60072. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  60073. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  60074. var boneName = this.bones[i].name;
  60075. var sourceBone = boneDict[boneName];
  60076. if (sourceBone) {
  60077. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  60078. }
  60079. else {
  60080. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  60081. ret = false;
  60082. }
  60083. }
  60084. // do not call createAnimationRange(), since it also is done to bones, which was already done
  60085. var range = source.getAnimationRange(name);
  60086. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  60087. return ret;
  60088. };
  60089. Skeleton.prototype.returnToRest = function () {
  60090. for (var index = 0; index < this.bones.length; index++) {
  60091. this.bones[index].returnToRest();
  60092. }
  60093. };
  60094. Skeleton.prototype._getHighestAnimationFrame = function () {
  60095. var ret = 0;
  60096. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  60097. if (this.bones[i].animations[0]) {
  60098. var highest = this.bones[i].animations[0].getHighestFrame();
  60099. if (ret < highest) {
  60100. ret = highest;
  60101. }
  60102. }
  60103. }
  60104. return ret;
  60105. };
  60106. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  60107. var range = this.getAnimationRange(name);
  60108. if (!range) {
  60109. return null;
  60110. }
  60111. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  60112. };
  60113. Skeleton.prototype._markAsDirty = function () {
  60114. this._isDirty = true;
  60115. };
  60116. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  60117. this._meshesWithPoseMatrix.push(mesh);
  60118. };
  60119. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  60120. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  60121. if (index > -1) {
  60122. this._meshesWithPoseMatrix.splice(index, 1);
  60123. }
  60124. };
  60125. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  60126. this.onBeforeComputeObservable.notifyObservers(this);
  60127. for (var index = 0; index < this.bones.length; index++) {
  60128. var bone = this.bones[index];
  60129. var parentBone = bone.getParent();
  60130. if (parentBone) {
  60131. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  60132. }
  60133. else {
  60134. if (initialSkinMatrix) {
  60135. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  60136. }
  60137. else {
  60138. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  60139. }
  60140. }
  60141. if (bone._index !== -1) {
  60142. var mappedIndex = bone._index === undefined ? index : bone._index;
  60143. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  60144. }
  60145. }
  60146. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  60147. };
  60148. Skeleton.prototype.prepare = function () {
  60149. if (!this._isDirty) {
  60150. return;
  60151. }
  60152. if (this.needInitialSkinMatrix) {
  60153. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  60154. var mesh = this._meshesWithPoseMatrix[index];
  60155. var poseMatrix = mesh.getPoseMatrix();
  60156. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  60157. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  60158. }
  60159. if (this._synchronizedWithMesh !== mesh) {
  60160. this._synchronizedWithMesh = mesh;
  60161. // Prepare bones
  60162. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  60163. var bone = this.bones[boneIndex];
  60164. if (!bone.getParent()) {
  60165. var matrix = bone.getBaseMatrix();
  60166. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  60167. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  60168. }
  60169. }
  60170. }
  60171. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  60172. }
  60173. }
  60174. else {
  60175. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  60176. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  60177. }
  60178. this._computeTransformMatrices(this._transformMatrices, null);
  60179. }
  60180. this._isDirty = false;
  60181. this._scene._activeBones.addCount(this.bones.length, false);
  60182. };
  60183. Skeleton.prototype.getAnimatables = function () {
  60184. if (!this._animatables || this._animatables.length !== this.bones.length) {
  60185. this._animatables = [];
  60186. for (var index = 0; index < this.bones.length; index++) {
  60187. this._animatables.push(this.bones[index]);
  60188. }
  60189. }
  60190. return this._animatables;
  60191. };
  60192. Skeleton.prototype.clone = function (name, id) {
  60193. var result = new Skeleton(name, id || name, this._scene);
  60194. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  60195. for (var index = 0; index < this.bones.length; index++) {
  60196. var source = this.bones[index];
  60197. var parentBone = null;
  60198. if (source.getParent()) {
  60199. var parentIndex = this.bones.indexOf(source.getParent());
  60200. parentBone = result.bones[parentIndex];
  60201. }
  60202. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  60203. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  60204. }
  60205. if (this._ranges) {
  60206. result._ranges = {};
  60207. for (var rangeName in this._ranges) {
  60208. result._ranges[rangeName] = this._ranges[rangeName].clone();
  60209. }
  60210. }
  60211. this._isDirty = true;
  60212. return result;
  60213. };
  60214. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  60215. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  60216. this.bones.forEach(function (bone) {
  60217. bone.animations.forEach(function (animation) {
  60218. animation.enableBlending = true;
  60219. animation.blendingSpeed = blendingSpeed;
  60220. });
  60221. });
  60222. };
  60223. Skeleton.prototype.dispose = function () {
  60224. this._meshesWithPoseMatrix = [];
  60225. // Animations
  60226. this.getScene().stopAnimation(this);
  60227. // Remove from scene
  60228. this.getScene().removeSkeleton(this);
  60229. };
  60230. Skeleton.prototype.serialize = function () {
  60231. var serializationObject = {};
  60232. serializationObject.name = this.name;
  60233. serializationObject.id = this.id;
  60234. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  60235. serializationObject.bones = [];
  60236. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  60237. for (var index = 0; index < this.bones.length; index++) {
  60238. var bone = this.bones[index];
  60239. var serializedBone = {
  60240. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  60241. name: bone.name,
  60242. matrix: bone.getBaseMatrix().toArray(),
  60243. rest: bone.getRestPose().toArray()
  60244. };
  60245. serializationObject.bones.push(serializedBone);
  60246. if (bone.length) {
  60247. serializedBone.length = bone.length;
  60248. }
  60249. if (bone.animations && bone.animations.length > 0) {
  60250. serializedBone.animation = bone.animations[0].serialize();
  60251. }
  60252. serializationObject.ranges = [];
  60253. for (var name in this._ranges) {
  60254. var range = {};
  60255. range.name = name;
  60256. range.from = this._ranges[name].from;
  60257. range.to = this._ranges[name].to;
  60258. serializationObject.ranges.push(range);
  60259. }
  60260. }
  60261. return serializationObject;
  60262. };
  60263. Skeleton.Parse = function (parsedSkeleton, scene) {
  60264. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  60265. if (parsedSkeleton.dimensionsAtRest) {
  60266. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  60267. }
  60268. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  60269. var index;
  60270. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  60271. var parsedBone = parsedSkeleton.bones[index];
  60272. var parentBone = null;
  60273. if (parsedBone.parentBoneIndex > -1) {
  60274. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  60275. }
  60276. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  60277. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  60278. if (parsedBone.length) {
  60279. bone.length = parsedBone.length;
  60280. }
  60281. if (parsedBone.animation) {
  60282. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  60283. }
  60284. }
  60285. // placed after bones, so createAnimationRange can cascade down
  60286. if (parsedSkeleton.ranges) {
  60287. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  60288. var data = parsedSkeleton.ranges[index];
  60289. skeleton.createAnimationRange(data.name, data.from, data.to);
  60290. }
  60291. }
  60292. return skeleton;
  60293. };
  60294. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  60295. if (forceUpdate === void 0) { forceUpdate = false; }
  60296. var renderId = this._scene.getRenderId();
  60297. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  60298. this.bones[0].computeAbsoluteTransforms();
  60299. this._lastAbsoluteTransformsUpdateId = renderId;
  60300. }
  60301. };
  60302. Skeleton.prototype.getPoseMatrix = function () {
  60303. var poseMatrix;
  60304. if (this._meshesWithPoseMatrix.length > 0) {
  60305. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  60306. }
  60307. return poseMatrix;
  60308. };
  60309. Skeleton.prototype.sortBones = function () {
  60310. var bones = new Array();
  60311. var visited = new Array(this.bones.length);
  60312. for (var index = 0; index < this.bones.length; index++) {
  60313. this._sortBones(index, bones, visited);
  60314. }
  60315. this.bones = bones;
  60316. };
  60317. Skeleton.prototype._sortBones = function (index, bones, visited) {
  60318. if (visited[index]) {
  60319. return;
  60320. }
  60321. visited[index] = true;
  60322. var bone = this.bones[index];
  60323. if (bone._index === undefined) {
  60324. bone._index = index;
  60325. }
  60326. var parentBone = bone.getParent();
  60327. if (parentBone) {
  60328. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  60329. }
  60330. bones.push(bone);
  60331. };
  60332. return Skeleton;
  60333. }());
  60334. BABYLON.Skeleton = Skeleton;
  60335. })(BABYLON || (BABYLON = {}));
  60336. //# sourceMappingURL=babylon.skeleton.js.map
  60337. var BABYLON;
  60338. (function (BABYLON) {
  60339. var SphericalPolynomial = (function () {
  60340. function SphericalPolynomial() {
  60341. this.x = BABYLON.Vector3.Zero();
  60342. this.y = BABYLON.Vector3.Zero();
  60343. this.z = BABYLON.Vector3.Zero();
  60344. this.xx = BABYLON.Vector3.Zero();
  60345. this.yy = BABYLON.Vector3.Zero();
  60346. this.zz = BABYLON.Vector3.Zero();
  60347. this.xy = BABYLON.Vector3.Zero();
  60348. this.yz = BABYLON.Vector3.Zero();
  60349. this.zx = BABYLON.Vector3.Zero();
  60350. }
  60351. SphericalPolynomial.prototype.addAmbient = function (color) {
  60352. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  60353. this.xx = this.xx.add(colorVector);
  60354. this.yy = this.yy.add(colorVector);
  60355. this.zz = this.zz.add(colorVector);
  60356. };
  60357. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  60358. var result = new SphericalPolynomial();
  60359. result.x = harmonics.L11.scale(1.02333);
  60360. result.y = harmonics.L1_1.scale(1.02333);
  60361. result.z = harmonics.L10.scale(1.02333);
  60362. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  60363. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  60364. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  60365. result.yz = harmonics.L2_1.scale(0.858086);
  60366. result.zx = harmonics.L21.scale(0.858086);
  60367. result.xy = harmonics.L2_2.scale(0.858086);
  60368. result.scale(1.0 / Math.PI);
  60369. return result;
  60370. };
  60371. SphericalPolynomial.prototype.scale = function (scale) {
  60372. this.x = this.x.scale(scale);
  60373. this.y = this.y.scale(scale);
  60374. this.z = this.z.scale(scale);
  60375. this.xx = this.xx.scale(scale);
  60376. this.yy = this.yy.scale(scale);
  60377. this.zz = this.zz.scale(scale);
  60378. this.yz = this.yz.scale(scale);
  60379. this.zx = this.zx.scale(scale);
  60380. this.xy = this.xy.scale(scale);
  60381. };
  60382. return SphericalPolynomial;
  60383. }());
  60384. BABYLON.SphericalPolynomial = SphericalPolynomial;
  60385. var SphericalHarmonics = (function () {
  60386. function SphericalHarmonics() {
  60387. this.L00 = BABYLON.Vector3.Zero();
  60388. this.L1_1 = BABYLON.Vector3.Zero();
  60389. this.L10 = BABYLON.Vector3.Zero();
  60390. this.L11 = BABYLON.Vector3.Zero();
  60391. this.L2_2 = BABYLON.Vector3.Zero();
  60392. this.L2_1 = BABYLON.Vector3.Zero();
  60393. this.L20 = BABYLON.Vector3.Zero();
  60394. this.L21 = BABYLON.Vector3.Zero();
  60395. this.L22 = BABYLON.Vector3.Zero();
  60396. }
  60397. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  60398. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  60399. var c = colorVector.scale(deltaSolidAngle);
  60400. this.L00 = this.L00.add(c.scale(0.282095));
  60401. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  60402. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  60403. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  60404. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  60405. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  60406. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  60407. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  60408. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  60409. };
  60410. SphericalHarmonics.prototype.scale = function (scale) {
  60411. this.L00 = this.L00.scale(scale);
  60412. this.L1_1 = this.L1_1.scale(scale);
  60413. this.L10 = this.L10.scale(scale);
  60414. this.L11 = this.L11.scale(scale);
  60415. this.L2_2 = this.L2_2.scale(scale);
  60416. this.L2_1 = this.L2_1.scale(scale);
  60417. this.L20 = this.L20.scale(scale);
  60418. this.L21 = this.L21.scale(scale);
  60419. this.L22 = this.L22.scale(scale);
  60420. };
  60421. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  60422. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  60423. //
  60424. // E_lm = A_l * L_lm
  60425. //
  60426. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  60427. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  60428. // the scaling factors are given in equation 9.
  60429. // Constant (Band 0)
  60430. this.L00 = this.L00.scale(3.141593);
  60431. // Linear (Band 1)
  60432. this.L1_1 = this.L1_1.scale(2.094395);
  60433. this.L10 = this.L10.scale(2.094395);
  60434. this.L11 = this.L11.scale(2.094395);
  60435. // Quadratic (Band 2)
  60436. this.L2_2 = this.L2_2.scale(0.785398);
  60437. this.L2_1 = this.L2_1.scale(0.785398);
  60438. this.L20 = this.L20.scale(0.785398);
  60439. this.L21 = this.L21.scale(0.785398);
  60440. this.L22 = this.L22.scale(0.785398);
  60441. };
  60442. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  60443. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  60444. // L = (1/pi) * E * rho
  60445. //
  60446. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  60447. this.scale(1.0 / Math.PI);
  60448. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  60449. // (The pixel shader must apply albedo after texture fetches, etc).
  60450. };
  60451. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  60452. var result = new SphericalHarmonics();
  60453. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  60454. result.L1_1 = polynomial.y.scale(0.977204);
  60455. result.L10 = polynomial.z.scale(0.977204);
  60456. result.L11 = polynomial.x.scale(0.977204);
  60457. result.L2_2 = polynomial.xy.scale(1.16538);
  60458. result.L2_1 = polynomial.yz.scale(1.16538);
  60459. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  60460. result.L21 = polynomial.zx.scale(1.16538);
  60461. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  60462. result.scale(Math.PI);
  60463. return result;
  60464. };
  60465. return SphericalHarmonics;
  60466. }());
  60467. BABYLON.SphericalHarmonics = SphericalHarmonics;
  60468. })(BABYLON || (BABYLON = {}));
  60469. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  60470. var BABYLON;
  60471. (function (BABYLON) {
  60472. var Internals;
  60473. (function (Internals) {
  60474. var FileFaceOrientation = (function () {
  60475. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  60476. this.name = name;
  60477. this.worldAxisForNormal = worldAxisForNormal;
  60478. this.worldAxisForFileX = worldAxisForFileX;
  60479. this.worldAxisForFileY = worldAxisForFileY;
  60480. }
  60481. return FileFaceOrientation;
  60482. }());
  60483. ;
  60484. /**
  60485. * Helper class dealing with the extraction of spherical polynomial dataArray
  60486. * from a cube map.
  60487. */
  60488. var CubeMapToSphericalPolynomialTools = (function () {
  60489. function CubeMapToSphericalPolynomialTools() {
  60490. }
  60491. /**
  60492. * Converts a texture to the according Spherical Polynomial data.
  60493. * This extracts the first 3 orders only as they are the only one used in the lighting.
  60494. *
  60495. * @param texture The texture to extract the information from.
  60496. * @return The Spherical Polynomial data.
  60497. */
  60498. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  60499. if (!texture.isCube) {
  60500. // Only supports cube Textures currently.
  60501. return null;
  60502. }
  60503. var size = texture.getSize().width;
  60504. var right = texture.readPixels(0);
  60505. var left = texture.readPixels(1);
  60506. var up;
  60507. var down;
  60508. if (texture.isRenderTarget) {
  60509. up = texture.readPixels(3);
  60510. down = texture.readPixels(2);
  60511. }
  60512. else {
  60513. up = texture.readPixels(2);
  60514. down = texture.readPixels(3);
  60515. }
  60516. var front = texture.readPixels(4);
  60517. var back = texture.readPixels(5);
  60518. var gammaSpace = texture.gammaSpace;
  60519. // Always read as RGBA.
  60520. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  60521. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60522. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60523. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60524. }
  60525. var cubeInfo = {
  60526. size: size,
  60527. right: right,
  60528. left: left,
  60529. up: up,
  60530. down: down,
  60531. front: front,
  60532. back: back,
  60533. format: format,
  60534. type: type,
  60535. gammaSpace: gammaSpace,
  60536. };
  60537. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  60538. };
  60539. /**
  60540. * Converts a cubemap to the according Spherical Polynomial data.
  60541. * This extracts the first 3 orders only as they are the only one used in the lighting.
  60542. *
  60543. * @param cubeInfo The Cube map to extract the information from.
  60544. * @return The Spherical Polynomial data.
  60545. */
  60546. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  60547. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  60548. var totalSolidAngle = 0.0;
  60549. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  60550. var du = 2.0 / cubeInfo.size;
  60551. var dv = du;
  60552. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  60553. var minUV = du * 0.5 - 1.0;
  60554. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  60555. var fileFace = this.FileFaces[faceIndex];
  60556. var dataArray = cubeInfo[fileFace.name];
  60557. var v = minUV;
  60558. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  60559. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  60560. // Because SP is still linear, so summation is fine in that basis.
  60561. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  60562. for (var y = 0; y < cubeInfo.size; y++) {
  60563. var u = minUV;
  60564. for (var x = 0; x < cubeInfo.size; x++) {
  60565. // World direction (not normalised)
  60566. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  60567. worldDirection.normalize();
  60568. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  60569. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  60570. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  60571. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  60572. // Handle Integer types.
  60573. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60574. r /= 255;
  60575. g /= 255;
  60576. b /= 255;
  60577. }
  60578. // Handle Gamma space textures.
  60579. if (cubeInfo.gammaSpace) {
  60580. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  60581. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  60582. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  60583. }
  60584. var color = new BABYLON.Color3(r, g, b);
  60585. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  60586. totalSolidAngle += deltaSolidAngle;
  60587. u += du;
  60588. }
  60589. v += dv;
  60590. }
  60591. }
  60592. // Solid angle for entire sphere is 4*pi
  60593. var sphereSolidAngle = 4.0 * Math.PI;
  60594. // Adjust the solid angle to allow for how many faces we processed.
  60595. var facesProcessed = 6.0;
  60596. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  60597. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  60598. // This is needed because the numerical integration over the cube uses a
  60599. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  60600. // and also to compensate for accumulative error due to float precision in the summation.
  60601. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  60602. sphericalHarmonics.scale(correctionFactor);
  60603. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  60604. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  60605. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  60606. };
  60607. CubeMapToSphericalPolynomialTools.FileFaces = [
  60608. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  60609. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  60610. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  60611. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  60612. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  60613. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  60614. ];
  60615. return CubeMapToSphericalPolynomialTools;
  60616. }());
  60617. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  60618. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  60619. })(BABYLON || (BABYLON = {}));
  60620. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  60621. var BABYLON;
  60622. (function (BABYLON) {
  60623. var Internals;
  60624. (function (Internals) {
  60625. /**
  60626. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  60627. */
  60628. var PanoramaToCubeMapTools = (function () {
  60629. function PanoramaToCubeMapTools() {
  60630. }
  60631. /**
  60632. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  60633. *
  60634. * @param float32Array The source data.
  60635. * @param inputWidth The width of the input panorama.
  60636. * @param inputhHeight The height of the input panorama.
  60637. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  60638. * @return The cubemap data
  60639. */
  60640. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  60641. if (!float32Array) {
  60642. throw "ConvertPanoramaToCubemap: input cannot be null";
  60643. }
  60644. if (float32Array.length != inputWidth * inputHeight * 3) {
  60645. throw "ConvertPanoramaToCubemap: input size is wrong";
  60646. }
  60647. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  60648. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  60649. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  60650. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  60651. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  60652. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  60653. return {
  60654. front: textureFront,
  60655. back: textureBack,
  60656. left: textureLeft,
  60657. right: textureRight,
  60658. up: textureUp,
  60659. down: textureDown,
  60660. size: size,
  60661. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  60662. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  60663. gammaSpace: false,
  60664. };
  60665. };
  60666. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  60667. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  60668. var textureArray = new Float32Array(buffer);
  60669. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  60670. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  60671. var dy = 1 / texSize;
  60672. var fy = 0;
  60673. for (var y = 0; y < texSize; y++) {
  60674. var xv1 = faceData[0];
  60675. var xv2 = faceData[2];
  60676. for (var x = 0; x < texSize; x++) {
  60677. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  60678. v.normalize();
  60679. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  60680. // 3 channels per pixels
  60681. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  60682. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  60683. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  60684. xv1 = xv1.add(rotDX1);
  60685. xv2 = xv2.add(rotDX2);
  60686. }
  60687. fy += dy;
  60688. }
  60689. return textureArray;
  60690. };
  60691. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  60692. var theta = Math.atan2(vDir.z, vDir.x);
  60693. var phi = Math.acos(vDir.y);
  60694. while (theta < -Math.PI)
  60695. theta += 2 * Math.PI;
  60696. while (theta > Math.PI)
  60697. theta -= 2 * Math.PI;
  60698. var dx = theta / Math.PI;
  60699. var dy = phi / Math.PI;
  60700. // recenter.
  60701. dx = dx * 0.5 + 0.5;
  60702. var px = Math.round(dx * inputWidth);
  60703. if (px < 0)
  60704. px = 0;
  60705. else if (px >= inputWidth)
  60706. px = inputWidth - 1;
  60707. var py = Math.round(dy * inputHeight);
  60708. if (py < 0)
  60709. py = 0;
  60710. else if (py >= inputHeight)
  60711. py = inputHeight - 1;
  60712. var inputY = (inputHeight - py - 1);
  60713. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  60714. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  60715. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  60716. return {
  60717. r: r,
  60718. g: g,
  60719. b: b
  60720. };
  60721. };
  60722. PanoramaToCubeMapTools.FACE_FRONT = [
  60723. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  60724. new BABYLON.Vector3(1.0, -1.0, -1.0),
  60725. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  60726. new BABYLON.Vector3(1.0, 1.0, -1.0)
  60727. ];
  60728. PanoramaToCubeMapTools.FACE_BACK = [
  60729. new BABYLON.Vector3(1.0, -1.0, 1.0),
  60730. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  60731. new BABYLON.Vector3(1.0, 1.0, 1.0),
  60732. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  60733. ];
  60734. PanoramaToCubeMapTools.FACE_RIGHT = [
  60735. new BABYLON.Vector3(1.0, -1.0, -1.0),
  60736. new BABYLON.Vector3(1.0, -1.0, 1.0),
  60737. new BABYLON.Vector3(1.0, 1.0, -1.0),
  60738. new BABYLON.Vector3(1.0, 1.0, 1.0)
  60739. ];
  60740. PanoramaToCubeMapTools.FACE_LEFT = [
  60741. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  60742. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  60743. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  60744. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  60745. ];
  60746. PanoramaToCubeMapTools.FACE_DOWN = [
  60747. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  60748. new BABYLON.Vector3(1.0, 1.0, -1.0),
  60749. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  60750. new BABYLON.Vector3(1.0, 1.0, 1.0)
  60751. ];
  60752. PanoramaToCubeMapTools.FACE_UP = [
  60753. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  60754. new BABYLON.Vector3(1.0, -1.0, 1.0),
  60755. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  60756. new BABYLON.Vector3(1.0, -1.0, -1.0)
  60757. ];
  60758. return PanoramaToCubeMapTools;
  60759. }());
  60760. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  60761. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  60762. })(BABYLON || (BABYLON = {}));
  60763. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  60764. var BABYLON;
  60765. (function (BABYLON) {
  60766. var Internals;
  60767. (function (Internals) {
  60768. ;
  60769. /**
  60770. * This groups tools to convert HDR texture to native colors array.
  60771. */
  60772. var HDRTools = (function () {
  60773. function HDRTools() {
  60774. }
  60775. HDRTools.Ldexp = function (mantissa, exponent) {
  60776. if (exponent > 1023) {
  60777. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  60778. }
  60779. if (exponent < -1074) {
  60780. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  60781. }
  60782. return mantissa * Math.pow(2, exponent);
  60783. };
  60784. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  60785. if (exponent > 0) {
  60786. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  60787. float32array[index + 0] = red * exponent;
  60788. float32array[index + 1] = green * exponent;
  60789. float32array[index + 2] = blue * exponent;
  60790. }
  60791. else {
  60792. float32array[index + 0] = 0;
  60793. float32array[index + 1] = 0;
  60794. float32array[index + 2] = 0;
  60795. }
  60796. };
  60797. HDRTools.readStringLine = function (uint8array, startIndex) {
  60798. var line = "";
  60799. var character = "";
  60800. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  60801. character = String.fromCharCode(uint8array[i]);
  60802. if (character == "\n") {
  60803. break;
  60804. }
  60805. line += character;
  60806. }
  60807. return line;
  60808. };
  60809. /**
  60810. * Reads header information from an RGBE texture stored in a native array.
  60811. * More information on this format are available here:
  60812. * https://en.wikipedia.org/wiki/RGBE_image_format
  60813. *
  60814. * @param uint8array The binary file stored in native array.
  60815. * @return The header information.
  60816. */
  60817. HDRTools.RGBE_ReadHeader = function (uint8array) {
  60818. var height = 0;
  60819. var width = 0;
  60820. var line = this.readStringLine(uint8array, 0);
  60821. if (line[0] != '#' || line[1] != '?') {
  60822. throw "Bad HDR Format.";
  60823. }
  60824. var endOfHeader = false;
  60825. var findFormat = false;
  60826. var lineIndex = 0;
  60827. do {
  60828. lineIndex += (line.length + 1);
  60829. line = this.readStringLine(uint8array, lineIndex);
  60830. if (line == "FORMAT=32-bit_rle_rgbe") {
  60831. findFormat = true;
  60832. }
  60833. else if (line.length == 0) {
  60834. endOfHeader = true;
  60835. }
  60836. } while (!endOfHeader);
  60837. if (!findFormat) {
  60838. throw "HDR Bad header format, unsupported FORMAT";
  60839. }
  60840. lineIndex += (line.length + 1);
  60841. line = this.readStringLine(uint8array, lineIndex);
  60842. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  60843. var match = sizeRegexp.exec(line);
  60844. // TODO. Support +Y and -X if needed.
  60845. if (match.length < 3) {
  60846. throw "HDR Bad header format, no size";
  60847. }
  60848. width = parseInt(match[2]);
  60849. height = parseInt(match[1]);
  60850. if (width < 8 || width > 0x7fff) {
  60851. throw "HDR Bad header format, unsupported size";
  60852. }
  60853. lineIndex += (line.length + 1);
  60854. return {
  60855. height: height,
  60856. width: width,
  60857. dataPosition: lineIndex
  60858. };
  60859. };
  60860. /**
  60861. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  60862. * This RGBE texture needs to store the information as a panorama.
  60863. *
  60864. * More information on this format are available here:
  60865. * https://en.wikipedia.org/wiki/RGBE_image_format
  60866. *
  60867. * @param buffer The binary file stored in an array buffer.
  60868. * @param size The expected size of the extracted cubemap.
  60869. * @return The Cube Map information.
  60870. */
  60871. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  60872. var uint8array = new Uint8Array(buffer);
  60873. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  60874. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  60875. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  60876. return cubeMapData;
  60877. };
  60878. /**
  60879. * Returns the pixels data extracted from an RGBE texture.
  60880. * This pixels will be stored left to right up to down in the R G B order in one array.
  60881. *
  60882. * More information on this format are available here:
  60883. * https://en.wikipedia.org/wiki/RGBE_image_format
  60884. *
  60885. * @param uint8array The binary file stored in an array buffer.
  60886. * @param hdrInfo The header information of the file.
  60887. * @return The pixels data in RGB right to left up to down order.
  60888. */
  60889. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  60890. // Keep for multi format supports.
  60891. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  60892. };
  60893. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  60894. var num_scanlines = hdrInfo.height;
  60895. var scanline_width = hdrInfo.width;
  60896. var a, b, c, d, count;
  60897. var dataIndex = hdrInfo.dataPosition;
  60898. var index = 0, endIndex = 0, i = 0;
  60899. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  60900. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  60901. // 3 channels of 4 bytes per pixel in float.
  60902. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  60903. var resultArray = new Float32Array(resultBuffer);
  60904. // read in each successive scanline
  60905. while (num_scanlines > 0) {
  60906. a = uint8array[dataIndex++];
  60907. b = uint8array[dataIndex++];
  60908. c = uint8array[dataIndex++];
  60909. d = uint8array[dataIndex++];
  60910. if (a != 2 || b != 2 || (c & 0x80)) {
  60911. // this file is not run length encoded
  60912. throw "HDR Bad header format, not RLE";
  60913. }
  60914. if (((c << 8) | d) != scanline_width) {
  60915. throw "HDR Bad header format, wrong scan line width";
  60916. }
  60917. index = 0;
  60918. // read each of the four channels for the scanline into the buffer
  60919. for (i = 0; i < 4; i++) {
  60920. endIndex = (i + 1) * scanline_width;
  60921. while (index < endIndex) {
  60922. a = uint8array[dataIndex++];
  60923. b = uint8array[dataIndex++];
  60924. if (a > 128) {
  60925. // a run of the same value
  60926. count = a - 128;
  60927. if ((count == 0) || (count > endIndex - index)) {
  60928. throw "HDR Bad Format, bad scanline data (run)";
  60929. }
  60930. while (count-- > 0) {
  60931. scanLineArray[index++] = b;
  60932. }
  60933. }
  60934. else {
  60935. // a non-run
  60936. count = a;
  60937. if ((count == 0) || (count > endIndex - index)) {
  60938. throw "HDR Bad Format, bad scanline data (non-run)";
  60939. }
  60940. scanLineArray[index++] = b;
  60941. if (--count > 0) {
  60942. for (var j = 0; j < count; j++) {
  60943. scanLineArray[index++] = uint8array[dataIndex++];
  60944. }
  60945. }
  60946. }
  60947. }
  60948. }
  60949. // now convert data from buffer into floats
  60950. for (i = 0; i < scanline_width; i++) {
  60951. a = scanLineArray[i];
  60952. b = scanLineArray[i + scanline_width];
  60953. c = scanLineArray[i + 2 * scanline_width];
  60954. d = scanLineArray[i + 3 * scanline_width];
  60955. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  60956. }
  60957. num_scanlines--;
  60958. }
  60959. return resultArray;
  60960. };
  60961. return HDRTools;
  60962. }());
  60963. Internals.HDRTools = HDRTools;
  60964. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  60965. })(BABYLON || (BABYLON = {}));
  60966. //# sourceMappingURL=babylon.hdr.js.map
  60967. var BABYLON;
  60968. (function (BABYLON) {
  60969. /**
  60970. * This represents a texture coming from an HDR input.
  60971. *
  60972. * The only supported format is currently panorama picture stored in RGBE format.
  60973. * Example of such files can be found on HDRLib: http://hdrlib.com/
  60974. */
  60975. var HDRCubeTexture = (function (_super) {
  60976. __extends(HDRCubeTexture, _super);
  60977. /**
  60978. * Instantiates an HDRTexture from the following parameters.
  60979. *
  60980. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  60981. * @param scene The scene the texture will be used in
  60982. * @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.
  60983. * @param noMipmap Forces to not generate the mipmap if true
  60984. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  60985. * @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)
  60986. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  60987. */
  60988. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  60989. if (noMipmap === void 0) { noMipmap = false; }
  60990. if (generateHarmonics === void 0) { generateHarmonics = true; }
  60991. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  60992. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  60993. if (onLoad === void 0) { onLoad = null; }
  60994. if (onError === void 0) { onError = null; }
  60995. var _this = _super.call(this, scene) || this;
  60996. _this._useInGammaSpace = false;
  60997. _this._generateHarmonics = true;
  60998. _this._isBABYLONPreprocessed = false;
  60999. _this._onLoad = null;
  61000. _this._onError = null;
  61001. /**
  61002. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  61003. */
  61004. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  61005. /**
  61006. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  61007. * This is usefull at run time to apply the good shader.
  61008. */
  61009. _this.isPMREM = false;
  61010. _this._isBlocking = true;
  61011. if (!url) {
  61012. return _this;
  61013. }
  61014. _this.name = url;
  61015. _this.url = url;
  61016. _this.hasAlpha = false;
  61017. _this.isCube = true;
  61018. _this._textureMatrix = BABYLON.Matrix.Identity();
  61019. _this._onLoad = onLoad;
  61020. _this._onError = onError;
  61021. _this.gammaSpace = false;
  61022. if (size) {
  61023. _this._isBABYLONPreprocessed = false;
  61024. _this._noMipmap = noMipmap;
  61025. _this._size = size;
  61026. _this._useInGammaSpace = useInGammaSpace;
  61027. _this._usePMREMGenerator = usePMREMGenerator &&
  61028. scene.getEngine().getCaps().textureLOD &&
  61029. _this.getScene().getEngine().getCaps().textureFloat &&
  61030. !_this._useInGammaSpace;
  61031. }
  61032. else {
  61033. _this._isBABYLONPreprocessed = true;
  61034. _this._noMipmap = false;
  61035. _this._useInGammaSpace = false;
  61036. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  61037. _this.getScene().getEngine().getCaps().textureFloat &&
  61038. !_this._useInGammaSpace;
  61039. }
  61040. _this.isPMREM = _this._usePMREMGenerator;
  61041. _this._texture = _this._getFromCache(url, _this._noMipmap);
  61042. if (!_this._texture) {
  61043. if (!scene.useDelayedTextureLoading) {
  61044. _this.loadTexture();
  61045. }
  61046. else {
  61047. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  61048. }
  61049. }
  61050. return _this;
  61051. }
  61052. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  61053. /**
  61054. * Gets wether or not the texture is blocking during loading.
  61055. */
  61056. get: function () {
  61057. return this._isBlocking;
  61058. },
  61059. /**
  61060. * Sets wether or not the texture is blocking during loading.
  61061. */
  61062. set: function (value) {
  61063. this._isBlocking = value;
  61064. },
  61065. enumerable: true,
  61066. configurable: true
  61067. });
  61068. /**
  61069. * Occurs when the file is a preprocessed .babylon.hdr file.
  61070. */
  61071. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  61072. var _this = this;
  61073. var mipLevels = 0;
  61074. var floatArrayView = null;
  61075. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  61076. var mips = new Array();
  61077. var startIndex = 30;
  61078. for (var level = 0; level < mipLevels; level++) {
  61079. mips.push([]);
  61080. // Fill each pixel of the mip level.
  61081. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  61082. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  61083. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  61084. mips[level].push(faceData);
  61085. startIndex += faceSize;
  61086. }
  61087. }
  61088. return mips;
  61089. } : null;
  61090. var callback = function (buffer) {
  61091. // Create Native Array Views
  61092. var intArrayView = new Int32Array(buffer);
  61093. floatArrayView = new Float32Array(buffer);
  61094. // Fill header.
  61095. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  61096. _this._size = intArrayView[1]; // CubeMap max mip face size.
  61097. // Update Texture Information.
  61098. _this._texture.updateSize(_this._size, _this._size);
  61099. // Fill polynomial information.
  61100. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  61101. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  61102. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  61103. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  61104. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  61105. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  61106. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  61107. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  61108. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  61109. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  61110. _this.sphericalPolynomial = sphericalPolynomial;
  61111. // Fill pixel data.
  61112. mipLevels = intArrayView[29]; // Number of mip levels.
  61113. var startIndex = 30;
  61114. var data = [];
  61115. var faceSize = Math.pow(_this._size, 2) * 3;
  61116. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  61117. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  61118. startIndex += faceSize;
  61119. }
  61120. var results = [];
  61121. var byteArray = null;
  61122. // Push each faces.
  61123. for (var k = 0; k < 6; k++) {
  61124. var dataFace = null;
  61125. // To be deprecated.
  61126. if (version === 1) {
  61127. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  61128. dataFace = data[j];
  61129. }
  61130. // If special cases.
  61131. if (!mipmapGenerator) {
  61132. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  61133. // 3 channels of 1 bytes per pixel in bytes.
  61134. var byteBuffer = new ArrayBuffer(faceSize);
  61135. byteArray = new Uint8Array(byteBuffer);
  61136. }
  61137. for (var i = 0; i < _this._size * _this._size; i++) {
  61138. // Put in gamma space if requested.
  61139. if (_this._useInGammaSpace) {
  61140. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  61141. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  61142. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  61143. }
  61144. // Convert to int texture for fallback.
  61145. if (byteArray) {
  61146. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  61147. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  61148. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  61149. // May use luminance instead if the result is not accurate.
  61150. var max = Math.max(Math.max(r, g), b);
  61151. if (max > 255) {
  61152. var scale = 255 / max;
  61153. r *= scale;
  61154. g *= scale;
  61155. b *= scale;
  61156. }
  61157. byteArray[(i * 3) + 0] = r;
  61158. byteArray[(i * 3) + 1] = g;
  61159. byteArray[(i * 3) + 2] = b;
  61160. }
  61161. }
  61162. }
  61163. // Fill the array accordingly.
  61164. if (byteArray) {
  61165. results.push(byteArray);
  61166. }
  61167. else {
  61168. results.push(dataFace);
  61169. }
  61170. }
  61171. return results;
  61172. };
  61173. 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);
  61174. };
  61175. /**
  61176. * Occurs when the file is raw .hdr file.
  61177. */
  61178. HDRCubeTexture.prototype.loadHDRTexture = function () {
  61179. var _this = this;
  61180. var callback = function (buffer) {
  61181. // Extract the raw linear data.
  61182. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  61183. // Generate harmonics if needed.
  61184. if (_this._generateHarmonics) {
  61185. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  61186. _this.sphericalPolynomial = sphericalPolynomial;
  61187. }
  61188. var results = [];
  61189. var byteArray = null;
  61190. // Push each faces.
  61191. for (var j = 0; j < 6; j++) {
  61192. // Create uintarray fallback.
  61193. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  61194. // 3 channels of 1 bytes per pixel in bytes.
  61195. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  61196. byteArray = new Uint8Array(byteBuffer);
  61197. }
  61198. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  61199. // If special cases.
  61200. if (_this._useInGammaSpace || byteArray) {
  61201. for (var i = 0; i < _this._size * _this._size; i++) {
  61202. // Put in gamma space if requested.
  61203. if (_this._useInGammaSpace) {
  61204. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  61205. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  61206. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  61207. }
  61208. // Convert to int texture for fallback.
  61209. if (byteArray) {
  61210. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  61211. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  61212. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  61213. // May use luminance instead if the result is not accurate.
  61214. var max = Math.max(Math.max(r, g), b);
  61215. if (max > 255) {
  61216. var scale = 255 / max;
  61217. r *= scale;
  61218. g *= scale;
  61219. b *= scale;
  61220. }
  61221. byteArray[(i * 3) + 0] = r;
  61222. byteArray[(i * 3) + 1] = g;
  61223. byteArray[(i * 3) + 2] = b;
  61224. }
  61225. }
  61226. }
  61227. if (byteArray) {
  61228. results.push(byteArray);
  61229. }
  61230. else {
  61231. results.push(dataFace);
  61232. }
  61233. }
  61234. return results;
  61235. };
  61236. var mipmapGenerator = null;
  61237. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  61238. // if (!this._noMipmap &&
  61239. // this._usePMREMGenerator) {
  61240. // mipmapGenerator = (data: ArrayBufferView[]) => {
  61241. // // Custom setup of the generator matching with the PBR shader values.
  61242. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  61243. // this._size,
  61244. // this._size,
  61245. // 0,
  61246. // 3,
  61247. // this.getScene().getEngine().getCaps().textureFloat,
  61248. // 2048,
  61249. // 0.25,
  61250. // false,
  61251. // true);
  61252. // return generator.filterCubeMap();
  61253. // };
  61254. // }
  61255. 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);
  61256. };
  61257. /**
  61258. * Starts the loading process of the texture.
  61259. */
  61260. HDRCubeTexture.prototype.loadTexture = function () {
  61261. if (this._isBABYLONPreprocessed) {
  61262. this.loadBabylonTexture();
  61263. }
  61264. else {
  61265. this.loadHDRTexture();
  61266. }
  61267. };
  61268. HDRCubeTexture.prototype.clone = function () {
  61269. var size = this._isBABYLONPreprocessed ? null : this._size;
  61270. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  61271. // Base texture
  61272. newTexture.level = this.level;
  61273. newTexture.wrapU = this.wrapU;
  61274. newTexture.wrapV = this.wrapV;
  61275. newTexture.coordinatesIndex = this.coordinatesIndex;
  61276. newTexture.coordinatesMode = this.coordinatesMode;
  61277. return newTexture;
  61278. };
  61279. // Methods
  61280. HDRCubeTexture.prototype.delayLoad = function () {
  61281. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  61282. return;
  61283. }
  61284. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  61285. this._texture = this._getFromCache(this.url, this._noMipmap);
  61286. if (!this._texture) {
  61287. this.loadTexture();
  61288. }
  61289. };
  61290. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  61291. return this._textureMatrix;
  61292. };
  61293. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  61294. this._textureMatrix = value;
  61295. };
  61296. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  61297. var texture = null;
  61298. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  61299. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  61300. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  61301. texture.name = parsedTexture.name;
  61302. texture.hasAlpha = parsedTexture.hasAlpha;
  61303. texture.level = parsedTexture.level;
  61304. texture.coordinatesMode = parsedTexture.coordinatesMode;
  61305. texture.isBlocking = parsedTexture.isBlocking;
  61306. }
  61307. return texture;
  61308. };
  61309. HDRCubeTexture.prototype.serialize = function () {
  61310. if (!this.name) {
  61311. return null;
  61312. }
  61313. var serializationObject = {};
  61314. serializationObject.name = this.name;
  61315. serializationObject.hasAlpha = this.hasAlpha;
  61316. serializationObject.isCube = true;
  61317. serializationObject.level = this.level;
  61318. serializationObject.size = this._size;
  61319. serializationObject.coordinatesMode = this.coordinatesMode;
  61320. serializationObject.useInGammaSpace = this._useInGammaSpace;
  61321. serializationObject.generateHarmonics = this._generateHarmonics;
  61322. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  61323. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  61324. serializationObject.customType = "BABYLON.HDRCubeTexture";
  61325. serializationObject.noMipmap = this._noMipmap;
  61326. serializationObject.isBlocking = this._isBlocking;
  61327. return serializationObject;
  61328. };
  61329. /**
  61330. * Saves as a file the data contained in the texture in a binary format.
  61331. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  61332. * as the spherical used in the lighting.
  61333. * @param url The HDR file url.
  61334. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  61335. * @param onError Method called if any error happens during download.
  61336. * @return The packed binary data.
  61337. */
  61338. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  61339. if (onError === void 0) { onError = null; }
  61340. var callback = function (buffer) {
  61341. var data = new Blob([buffer], { type: 'application/octet-stream' });
  61342. // Returns a URL you can use as a href.
  61343. var objUrl = window.URL.createObjectURL(data);
  61344. // Simulates a link to it and click to dowload.
  61345. var a = document.createElement("a");
  61346. document.body.appendChild(a);
  61347. a.style.display = "none";
  61348. a.href = objUrl;
  61349. a.download = "envmap.babylon.hdr";
  61350. a.click();
  61351. };
  61352. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  61353. };
  61354. /**
  61355. * Serializes the data contained in the texture in a binary format.
  61356. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  61357. * as the spherical used in the lighting.
  61358. * @param url The HDR file url.
  61359. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  61360. * @param onError Method called if any error happens during download.
  61361. * @return The packed binary data.
  61362. */
  61363. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  61364. if (onError === void 0) { onError = null; }
  61365. // Needs the url tho create the texture.
  61366. if (!url) {
  61367. return null;
  61368. }
  61369. // Check Power of two size.
  61370. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  61371. return null;
  61372. }
  61373. // Coming Back in 3.1.
  61374. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  61375. return null;
  61376. };
  61377. HDRCubeTexture._facesMapping = [
  61378. "right",
  61379. "left",
  61380. "up",
  61381. "down",
  61382. "front",
  61383. "back"
  61384. ];
  61385. return HDRCubeTexture;
  61386. }(BABYLON.BaseTexture));
  61387. BABYLON.HDRCubeTexture = HDRCubeTexture;
  61388. })(BABYLON || (BABYLON = {}));
  61389. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  61390. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  61391. // Huge respect for a such great lib.
  61392. // Earcut license:
  61393. // Copyright (c) 2016, Mapbox
  61394. //
  61395. // Permission to use, copy, modify, and/or distribute this software for any purpose
  61396. // with or without fee is hereby granted, provided that the above copyright notice
  61397. // and this permission notice appear in all copies.
  61398. //
  61399. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  61400. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  61401. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  61402. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  61403. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  61404. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  61405. // THIS SOFTWARE.
  61406. var Earcut;
  61407. (function (Earcut) {
  61408. /**
  61409. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  61410. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  61411. * @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).
  61412. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  61413. */
  61414. function earcut(data, holeIndices, dim) {
  61415. dim = dim || 2;
  61416. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  61417. if (!outerNode)
  61418. return triangles;
  61419. var minX, minY, maxX, maxY, x, y, size;
  61420. if (hasHoles)
  61421. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  61422. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  61423. if (data.length > 80 * dim) {
  61424. minX = maxX = data[0];
  61425. minY = maxY = data[1];
  61426. for (var i = dim; i < outerLen; i += dim) {
  61427. x = data[i];
  61428. y = data[i + 1];
  61429. if (x < minX)
  61430. minX = x;
  61431. if (y < minY)
  61432. minY = y;
  61433. if (x > maxX)
  61434. maxX = x;
  61435. if (y > maxY)
  61436. maxY = y;
  61437. }
  61438. // minX, minY and size are later used to transform coords into integers for z-order calculation
  61439. size = Math.max(maxX - minX, maxY - minY);
  61440. }
  61441. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  61442. return triangles;
  61443. }
  61444. Earcut.earcut = earcut;
  61445. var Node = (function () {
  61446. function Node(i, x, y) {
  61447. this.i = i;
  61448. this.x = x;
  61449. this.y = y;
  61450. this.prev = null;
  61451. this.next = null;
  61452. this.z = null;
  61453. this.prevZ = null;
  61454. this.nextZ = null;
  61455. this.steiner = false;
  61456. }
  61457. return Node;
  61458. }());
  61459. // create a circular doubly linked list from polygon points in the specified winding order
  61460. function linkedList(data, start, end, dim, clockwise) {
  61461. var i, last;
  61462. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  61463. for (i = start; i < end; i += dim)
  61464. last = insertNode(i, data[i], data[i + 1], last);
  61465. }
  61466. else {
  61467. for (i = end - dim; i >= start; i -= dim)
  61468. last = insertNode(i, data[i], data[i + 1], last);
  61469. }
  61470. if (last && equals(last, last.next)) {
  61471. removeNode(last);
  61472. last = last.next;
  61473. }
  61474. return last;
  61475. }
  61476. // eliminate colinear or duplicate points
  61477. function filterPoints(start, end) {
  61478. if (!start)
  61479. return start;
  61480. if (!end)
  61481. end = start;
  61482. var p = start, again;
  61483. do {
  61484. again = false;
  61485. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  61486. removeNode(p);
  61487. p = end = p.prev;
  61488. if (p === p.next)
  61489. return null;
  61490. again = true;
  61491. }
  61492. else {
  61493. p = p.next;
  61494. }
  61495. } while (again || p !== end);
  61496. return end;
  61497. }
  61498. // main ear slicing loop which triangulates a polygon (given as a linked list)
  61499. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  61500. if (!ear)
  61501. return;
  61502. // interlink polygon nodes in z-order
  61503. if (!pass && size)
  61504. indexCurve(ear, minX, minY, size);
  61505. var stop = ear, prev, next;
  61506. // iterate through ears, slicing them one by one
  61507. while (ear.prev !== ear.next) {
  61508. prev = ear.prev;
  61509. next = ear.next;
  61510. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  61511. // cut off the triangle
  61512. triangles.push(prev.i / dim);
  61513. triangles.push(ear.i / dim);
  61514. triangles.push(next.i / dim);
  61515. removeNode(ear);
  61516. // skipping the next vertice leads to less sliver triangles
  61517. ear = next.next;
  61518. stop = next.next;
  61519. continue;
  61520. }
  61521. ear = next;
  61522. // if we looped through the whole remaining polygon and can't find any more ears
  61523. if (ear === stop) {
  61524. // try filtering points and slicing again
  61525. if (!pass) {
  61526. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  61527. // if this didn't work, try curing all small self-intersections locally
  61528. }
  61529. else if (pass === 1) {
  61530. ear = cureLocalIntersections(ear, triangles, dim);
  61531. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  61532. // as a last resort, try splitting the remaining polygon into two
  61533. }
  61534. else if (pass === 2) {
  61535. splitEarcut(ear, triangles, dim, minX, minY, size);
  61536. }
  61537. break;
  61538. }
  61539. }
  61540. }
  61541. // check whether a polygon node forms a valid ear with adjacent nodes
  61542. function isEar(ear) {
  61543. var a = ear.prev, b = ear, c = ear.next;
  61544. if (area(a, b, c) >= 0)
  61545. return false; // reflex, can't be an ear
  61546. // now make sure we don't have other points inside the potential ear
  61547. var p = ear.next.next;
  61548. while (p !== ear.prev) {
  61549. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  61550. area(p.prev, p, p.next) >= 0)
  61551. return false;
  61552. p = p.next;
  61553. }
  61554. return true;
  61555. }
  61556. function isEarHashed(ear, minX, minY, size) {
  61557. var a = ear.prev, b = ear, c = ear.next;
  61558. if (area(a, b, c) >= 0)
  61559. return false; // reflex, can't be an ear
  61560. // triangle bbox; min & max are calculated like this for speed
  61561. 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);
  61562. // z-order range for the current triangle bbox;
  61563. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  61564. // first look for points inside the triangle in increasing z-order
  61565. var p = ear.nextZ;
  61566. while (p && p.z <= maxZ) {
  61567. if (p !== ear.prev &&
  61568. p !== ear.next &&
  61569. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  61570. area(p.prev, p, p.next) >= 0)
  61571. return false;
  61572. p = p.nextZ;
  61573. }
  61574. // then look for points in decreasing z-order
  61575. p = ear.prevZ;
  61576. while (p && p.z >= minZ) {
  61577. if (p !== ear.prev &&
  61578. p !== ear.next &&
  61579. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  61580. area(p.prev, p, p.next) >= 0)
  61581. return false;
  61582. p = p.prevZ;
  61583. }
  61584. return true;
  61585. }
  61586. // go through all polygon nodes and cure small local self-intersections
  61587. function cureLocalIntersections(start, triangles, dim) {
  61588. var p = start;
  61589. do {
  61590. var a = p.prev, b = p.next.next;
  61591. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  61592. triangles.push(a.i / dim);
  61593. triangles.push(p.i / dim);
  61594. triangles.push(b.i / dim);
  61595. // remove two nodes involved
  61596. removeNode(p);
  61597. removeNode(p.next);
  61598. p = start = b;
  61599. }
  61600. p = p.next;
  61601. } while (p !== start);
  61602. return p;
  61603. }
  61604. // try splitting polygon into two and triangulate them independently
  61605. function splitEarcut(start, triangles, dim, minX, minY, size) {
  61606. // look for a valid diagonal that divides the polygon into two
  61607. var a = start;
  61608. do {
  61609. var b = a.next.next;
  61610. while (b !== a.prev) {
  61611. if (a.i !== b.i && isValidDiagonal(a, b)) {
  61612. // split the polygon in two by the diagonal
  61613. var c = splitPolygon(a, b);
  61614. // filter colinear points around the cuts
  61615. a = filterPoints(a, a.next);
  61616. c = filterPoints(c, c.next);
  61617. // run earcut on each half
  61618. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  61619. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  61620. return;
  61621. }
  61622. b = b.next;
  61623. }
  61624. a = a.next;
  61625. } while (a !== start);
  61626. }
  61627. // link every hole into the outer loop, producing a single-ring polygon without holes
  61628. function eliminateHoles(data, holeIndices, outerNode, dim) {
  61629. var queue = [], i, len, start, end, list;
  61630. for (i = 0, len = holeIndices.length; i < len; i++) {
  61631. start = holeIndices[i] * dim;
  61632. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  61633. list = linkedList(data, start, end, dim, false);
  61634. if (list === list.next)
  61635. list.steiner = true;
  61636. queue.push(getLeftmost(list));
  61637. }
  61638. queue.sort(compareX);
  61639. // process holes from left to right
  61640. for (i = 0; i < queue.length; i++) {
  61641. eliminateHole(queue[i], outerNode);
  61642. outerNode = filterPoints(outerNode, outerNode.next);
  61643. }
  61644. return outerNode;
  61645. }
  61646. function compareX(a, b) {
  61647. return a.x - b.x;
  61648. }
  61649. // find a bridge between vertices that connects hole with an outer ring and and link it
  61650. function eliminateHole(hole, outerNode) {
  61651. outerNode = findHoleBridge(hole, outerNode);
  61652. if (outerNode) {
  61653. var b = splitPolygon(outerNode, hole);
  61654. filterPoints(b, b.next);
  61655. }
  61656. }
  61657. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  61658. function findHoleBridge(hole, outerNode) {
  61659. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  61660. // find a segment intersected by a ray from the hole's leftmost point to the left;
  61661. // segment's endpoint with lesser x will be potential connection point
  61662. do {
  61663. if (hy <= p.y && hy >= p.next.y) {
  61664. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  61665. if (x <= hx && x > qx) {
  61666. qx = x;
  61667. if (x === hx) {
  61668. if (hy === p.y)
  61669. return p;
  61670. if (hy === p.next.y)
  61671. return p.next;
  61672. }
  61673. m = p.x < p.next.x ? p : p.next;
  61674. }
  61675. }
  61676. p = p.next;
  61677. } while (p !== outerNode);
  61678. if (!m)
  61679. return null;
  61680. if (hx === qx)
  61681. return m.prev; // hole touches outer segment; pick lower endpoint
  61682. // look for points inside the triangle of hole point, segment intersection and endpoint;
  61683. // if there are no points found, we have a valid connection;
  61684. // otherwise choose the point of the minimum angle with the ray as connection point
  61685. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  61686. p = m.next;
  61687. while (p !== stop) {
  61688. if (hx >= p.x &&
  61689. p.x >= mx &&
  61690. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  61691. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  61692. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  61693. m = p;
  61694. tanMin = tan;
  61695. }
  61696. }
  61697. p = p.next;
  61698. }
  61699. return m;
  61700. }
  61701. // interlink polygon nodes in z-order
  61702. function indexCurve(start, minX, minY, size) {
  61703. var p = start;
  61704. do {
  61705. if (p.z === null)
  61706. p.z = zOrder(p.x, p.y, minX, minY, size);
  61707. p.prevZ = p.prev;
  61708. p.nextZ = p.next;
  61709. p = p.next;
  61710. } while (p !== start);
  61711. p.prevZ.nextZ = null;
  61712. p.prevZ = null;
  61713. sortLinked(p);
  61714. }
  61715. // Simon Tatham's linked list merge sort algorithm
  61716. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  61717. function sortLinked(list) {
  61718. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  61719. do {
  61720. p = list;
  61721. list = null;
  61722. tail = null;
  61723. numMerges = 0;
  61724. while (p) {
  61725. numMerges++;
  61726. q = p;
  61727. pSize = 0;
  61728. for (i = 0; i < inSize; i++) {
  61729. pSize++;
  61730. q = q.nextZ;
  61731. if (!q)
  61732. break;
  61733. }
  61734. qSize = inSize;
  61735. while (pSize > 0 || (qSize > 0 && q)) {
  61736. if (pSize === 0) {
  61737. e = q;
  61738. q = q.nextZ;
  61739. qSize--;
  61740. }
  61741. else if (qSize === 0 || !q) {
  61742. e = p;
  61743. p = p.nextZ;
  61744. pSize--;
  61745. }
  61746. else if (p.z <= q.z) {
  61747. e = p;
  61748. p = p.nextZ;
  61749. pSize--;
  61750. }
  61751. else {
  61752. e = q;
  61753. q = q.nextZ;
  61754. qSize--;
  61755. }
  61756. if (tail)
  61757. tail.nextZ = e;
  61758. else
  61759. list = e;
  61760. e.prevZ = tail;
  61761. tail = e;
  61762. }
  61763. p = q;
  61764. }
  61765. tail.nextZ = null;
  61766. inSize *= 2;
  61767. } while (numMerges > 1);
  61768. return list;
  61769. }
  61770. // z-order of a point given coords and size of the data bounding box
  61771. function zOrder(x, y, minX, minY, size) {
  61772. // coords are transformed into non-negative 15-bit integer range
  61773. x = 32767 * (x - minX) / size;
  61774. y = 32767 * (y - minY) / size;
  61775. x = (x | (x << 8)) & 0x00FF00FF;
  61776. x = (x | (x << 4)) & 0x0F0F0F0F;
  61777. x = (x | (x << 2)) & 0x33333333;
  61778. x = (x | (x << 1)) & 0x55555555;
  61779. y = (y | (y << 8)) & 0x00FF00FF;
  61780. y = (y | (y << 4)) & 0x0F0F0F0F;
  61781. y = (y | (y << 2)) & 0x33333333;
  61782. y = (y | (y << 1)) & 0x55555555;
  61783. return x | (y << 1);
  61784. }
  61785. // find the leftmost node of a polygon ring
  61786. function getLeftmost(start) {
  61787. var p = start, leftmost = start;
  61788. do {
  61789. if (p.x < leftmost.x)
  61790. leftmost = p;
  61791. p = p.next;
  61792. } while (p !== start);
  61793. return leftmost;
  61794. }
  61795. // check if a point lies within a convex triangle
  61796. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  61797. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  61798. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  61799. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  61800. }
  61801. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  61802. function isValidDiagonal(a, b) {
  61803. return a.next.i !== b.i &&
  61804. a.prev.i !== b.i &&
  61805. !intersectsPolygon(a, b) &&
  61806. locallyInside(a, b) &&
  61807. locallyInside(b, a) &&
  61808. middleInside(a, b);
  61809. }
  61810. // signed area of a triangle
  61811. function area(p, q, r) {
  61812. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  61813. }
  61814. // check if two points are equal
  61815. function equals(p1, p2) {
  61816. return p1.x === p2.x && p1.y === p2.y;
  61817. }
  61818. // check if two segments intersect
  61819. function intersects(p1, q1, p2, q2) {
  61820. if ((equals(p1, q1) && equals(p2, q2)) ||
  61821. (equals(p1, q2) && equals(p2, q1)))
  61822. return true;
  61823. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  61824. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  61825. }
  61826. // check if a polygon diagonal intersects any polygon segments
  61827. function intersectsPolygon(a, b) {
  61828. var p = a;
  61829. do {
  61830. if (p.i !== a.i &&
  61831. p.next.i !== a.i &&
  61832. p.i !== b.i &&
  61833. p.next.i !== b.i &&
  61834. intersects(p, p.next, a, b))
  61835. return true;
  61836. p = p.next;
  61837. } while (p !== a);
  61838. return false;
  61839. }
  61840. // check if a polygon diagonal is locally inside the polygon
  61841. function locallyInside(a, b) {
  61842. return area(a.prev, a, a.next) < 0
  61843. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  61844. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  61845. }
  61846. // check if the middle point of a polygon diagonal is inside the polygon
  61847. function middleInside(a, b) {
  61848. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  61849. do {
  61850. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  61851. inside = !inside;
  61852. p = p.next;
  61853. } while (p !== a);
  61854. return inside;
  61855. }
  61856. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  61857. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  61858. function splitPolygon(a, b) {
  61859. 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;
  61860. a.next = b;
  61861. b.prev = a;
  61862. a2.next = an;
  61863. an.prev = a2;
  61864. b2.next = a2;
  61865. a2.prev = b2;
  61866. bp.next = b2;
  61867. b2.prev = bp;
  61868. return b2;
  61869. }
  61870. // create a node and optionally link it with previous one (in a circular doubly linked list)
  61871. function insertNode(i, x, y, last) {
  61872. var p = new Node(i, x, y);
  61873. if (!last) {
  61874. p.prev = p;
  61875. p.next = p;
  61876. }
  61877. else {
  61878. p.next = last.next;
  61879. p.prev = last;
  61880. last.next.prev = p;
  61881. last.next = p;
  61882. }
  61883. return p;
  61884. }
  61885. function removeNode(p) {
  61886. p.next.prev = p.prev;
  61887. p.prev.next = p.next;
  61888. if (p.prevZ)
  61889. p.prevZ.nextZ = p.nextZ;
  61890. if (p.nextZ)
  61891. p.nextZ.prevZ = p.prevZ;
  61892. }
  61893. /**
  61894. * return a percentage difference between the polygon area and its triangulation area;
  61895. * used to verify correctness of triangulation
  61896. */
  61897. function deviation(data, holeIndices, dim, triangles) {
  61898. var hasHoles = holeIndices && holeIndices.length;
  61899. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  61900. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  61901. if (hasHoles) {
  61902. for (var i = 0, len = holeIndices.length; i < len; i++) {
  61903. var start = holeIndices[i] * dim;
  61904. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  61905. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  61906. }
  61907. }
  61908. var trianglesArea = 0;
  61909. for (i = 0; i < triangles.length; i += 3) {
  61910. var a = triangles[i] * dim;
  61911. var b = triangles[i + 1] * dim;
  61912. var c = triangles[i + 2] * dim;
  61913. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  61914. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  61915. }
  61916. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  61917. }
  61918. Earcut.deviation = deviation;
  61919. ;
  61920. function signedArea(data, start, end, dim) {
  61921. var sum = 0;
  61922. for (var i = start, j = end - dim; i < end; i += dim) {
  61923. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  61924. j = i;
  61925. }
  61926. return sum;
  61927. }
  61928. /**
  61929. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  61930. */
  61931. function flatten(data) {
  61932. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  61933. for (var i = 0; i < data.length; i++) {
  61934. for (var j = 0; j < data[i].length; j++) {
  61935. for (var d = 0; d < dim; d++)
  61936. result.vertices.push(data[i][j][d]);
  61937. }
  61938. if (i > 0) {
  61939. holeIndex += data[i - 1].length;
  61940. result.holes.push(holeIndex);
  61941. }
  61942. }
  61943. return result;
  61944. }
  61945. Earcut.flatten = flatten;
  61946. ;
  61947. })(Earcut || (Earcut = {}));
  61948. //# sourceMappingURL=babylon.earcut.js.map
  61949. /// <reference path="..\Math\babylon.math.ts" />
  61950. var BABYLON;
  61951. (function (BABYLON) {
  61952. var IndexedVector2 = (function (_super) {
  61953. __extends(IndexedVector2, _super);
  61954. function IndexedVector2(original, index) {
  61955. var _this = _super.call(this, original.x, original.y) || this;
  61956. _this.index = index;
  61957. return _this;
  61958. }
  61959. return IndexedVector2;
  61960. }(BABYLON.Vector2));
  61961. var PolygonPoints = (function () {
  61962. function PolygonPoints() {
  61963. this.elements = new Array();
  61964. }
  61965. PolygonPoints.prototype.add = function (originalPoints) {
  61966. var _this = this;
  61967. var result = new Array();
  61968. originalPoints.forEach(function (point) {
  61969. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  61970. var newPoint = new IndexedVector2(point, _this.elements.length);
  61971. result.push(newPoint);
  61972. _this.elements.push(newPoint);
  61973. }
  61974. });
  61975. return result;
  61976. };
  61977. PolygonPoints.prototype.computeBounds = function () {
  61978. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  61979. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  61980. this.elements.forEach(function (point) {
  61981. // x
  61982. if (point.x < lmin.x) {
  61983. lmin.x = point.x;
  61984. }
  61985. else if (point.x > lmax.x) {
  61986. lmax.x = point.x;
  61987. }
  61988. // y
  61989. if (point.y < lmin.y) {
  61990. lmin.y = point.y;
  61991. }
  61992. else if (point.y > lmax.y) {
  61993. lmax.y = point.y;
  61994. }
  61995. });
  61996. return {
  61997. min: lmin,
  61998. max: lmax,
  61999. width: lmax.x - lmin.x,
  62000. height: lmax.y - lmin.y
  62001. };
  62002. };
  62003. return PolygonPoints;
  62004. }());
  62005. var Polygon = (function () {
  62006. function Polygon() {
  62007. }
  62008. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  62009. return [
  62010. new BABYLON.Vector2(xmin, ymin),
  62011. new BABYLON.Vector2(xmax, ymin),
  62012. new BABYLON.Vector2(xmax, ymax),
  62013. new BABYLON.Vector2(xmin, ymax)
  62014. ];
  62015. };
  62016. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  62017. if (cx === void 0) { cx = 0; }
  62018. if (cy === void 0) { cy = 0; }
  62019. if (numberOfSides === void 0) { numberOfSides = 32; }
  62020. var result = new Array();
  62021. var angle = 0;
  62022. var increment = (Math.PI * 2) / numberOfSides;
  62023. for (var i = 0; i < numberOfSides; i++) {
  62024. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  62025. angle -= increment;
  62026. }
  62027. return result;
  62028. };
  62029. Polygon.Parse = function (input) {
  62030. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  62031. var i, result = [];
  62032. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  62033. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  62034. }
  62035. return result;
  62036. };
  62037. Polygon.StartingAt = function (x, y) {
  62038. return BABYLON.Path2.StartingAt(x, y);
  62039. };
  62040. return Polygon;
  62041. }());
  62042. BABYLON.Polygon = Polygon;
  62043. var PolygonMeshBuilder = (function () {
  62044. function PolygonMeshBuilder(name, contours, scene) {
  62045. this._points = new PolygonPoints();
  62046. this._outlinepoints = new PolygonPoints();
  62047. this._holes = new Array();
  62048. this._epoints = new Array();
  62049. this._eholes = new Array();
  62050. this._name = name;
  62051. this._scene = scene;
  62052. var points;
  62053. if (contours instanceof BABYLON.Path2) {
  62054. points = contours.getPoints();
  62055. }
  62056. else {
  62057. points = contours;
  62058. }
  62059. this._addToepoint(points);
  62060. this._points.add(points);
  62061. this._outlinepoints.add(points);
  62062. }
  62063. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  62064. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  62065. var p = points_1[_i];
  62066. this._epoints.push(p.x, p.y);
  62067. }
  62068. };
  62069. PolygonMeshBuilder.prototype.addHole = function (hole) {
  62070. this._points.add(hole);
  62071. var holepoints = new PolygonPoints();
  62072. holepoints.add(hole);
  62073. this._holes.push(holepoints);
  62074. this._eholes.push(this._epoints.length / 2);
  62075. this._addToepoint(hole);
  62076. return this;
  62077. };
  62078. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  62079. var _this = this;
  62080. if (updatable === void 0) { updatable = false; }
  62081. var result = new BABYLON.Mesh(this._name, this._scene);
  62082. var normals = new Array();
  62083. var positions = new Array();
  62084. var uvs = new Array();
  62085. var bounds = this._points.computeBounds();
  62086. this._points.elements.forEach(function (p) {
  62087. normals.push(0, 1.0, 0);
  62088. positions.push(p.x, 0, p.y);
  62089. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  62090. });
  62091. var indices = new Array();
  62092. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  62093. for (var i = 0; i < res.length; i++) {
  62094. indices.push(res[i]);
  62095. }
  62096. if (depth > 0) {
  62097. var positionscount = (positions.length / 3); //get the current pointcount
  62098. this._points.elements.forEach(function (p) {
  62099. normals.push(0, -1.0, 0);
  62100. positions.push(p.x, -depth, p.y);
  62101. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  62102. });
  62103. var totalCount = indices.length;
  62104. for (var i = 0; i < totalCount; i += 3) {
  62105. var i0 = indices[i + 0];
  62106. var i1 = indices[i + 1];
  62107. var i2 = indices[i + 2];
  62108. indices.push(i2 + positionscount);
  62109. indices.push(i1 + positionscount);
  62110. indices.push(i0 + positionscount);
  62111. }
  62112. //Add the sides
  62113. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  62114. this._holes.forEach(function (hole) {
  62115. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  62116. });
  62117. }
  62118. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  62119. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  62120. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  62121. result.setIndices(indices);
  62122. return result;
  62123. };
  62124. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  62125. var StartIndex = positions.length / 3;
  62126. var ulength = 0;
  62127. for (var i = 0; i < points.elements.length; i++) {
  62128. var p = points.elements[i];
  62129. var p1;
  62130. if ((i + 1) > points.elements.length - 1) {
  62131. p1 = points.elements[0];
  62132. }
  62133. else {
  62134. p1 = points.elements[i + 1];
  62135. }
  62136. positions.push(p.x, 0, p.y);
  62137. positions.push(p.x, -depth, p.y);
  62138. positions.push(p1.x, 0, p1.y);
  62139. positions.push(p1.x, -depth, p1.y);
  62140. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  62141. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  62142. var v3 = v2.subtract(v1);
  62143. var v4 = new BABYLON.Vector3(0, 1, 0);
  62144. var vn = BABYLON.Vector3.Cross(v3, v4);
  62145. vn = vn.normalize();
  62146. uvs.push(ulength / bounds.width, 0);
  62147. uvs.push(ulength / bounds.width, 1);
  62148. ulength += v3.length();
  62149. uvs.push((ulength / bounds.width), 0);
  62150. uvs.push((ulength / bounds.width), 1);
  62151. if (!flip) {
  62152. normals.push(-vn.x, -vn.y, -vn.z);
  62153. normals.push(-vn.x, -vn.y, -vn.z);
  62154. normals.push(-vn.x, -vn.y, -vn.z);
  62155. normals.push(-vn.x, -vn.y, -vn.z);
  62156. indices.push(StartIndex);
  62157. indices.push(StartIndex + 1);
  62158. indices.push(StartIndex + 2);
  62159. indices.push(StartIndex + 1);
  62160. indices.push(StartIndex + 3);
  62161. indices.push(StartIndex + 2);
  62162. }
  62163. else {
  62164. normals.push(vn.x, vn.y, vn.z);
  62165. normals.push(vn.x, vn.y, vn.z);
  62166. normals.push(vn.x, vn.y, vn.z);
  62167. normals.push(vn.x, vn.y, vn.z);
  62168. indices.push(StartIndex);
  62169. indices.push(StartIndex + 2);
  62170. indices.push(StartIndex + 1);
  62171. indices.push(StartIndex + 1);
  62172. indices.push(StartIndex + 2);
  62173. indices.push(StartIndex + 3);
  62174. }
  62175. StartIndex += 4;
  62176. }
  62177. ;
  62178. };
  62179. return PolygonMeshBuilder;
  62180. }());
  62181. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  62182. })(BABYLON || (BABYLON = {}));
  62183. //# sourceMappingURL=babylon.polygonMesh.js.map
  62184. var BABYLON;
  62185. (function (BABYLON) {
  62186. // Unique ID when we import meshes from Babylon to CSG
  62187. var currentCSGMeshId = 0;
  62188. // # class Vertex
  62189. // Represents a vertex of a polygon. Use your own vertex class instead of this
  62190. // one to provide additional features like texture coordinates and vertex
  62191. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  62192. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  62193. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  62194. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  62195. // is not used anywhere else.
  62196. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  62197. var Vertex = (function () {
  62198. function Vertex(pos, normal, uv) {
  62199. this.pos = pos;
  62200. this.normal = normal;
  62201. this.uv = uv;
  62202. }
  62203. Vertex.prototype.clone = function () {
  62204. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  62205. };
  62206. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  62207. // orientation of a polygon is flipped.
  62208. Vertex.prototype.flip = function () {
  62209. this.normal = this.normal.scale(-1);
  62210. };
  62211. // Create a new vertex between this vertex and `other` by linearly
  62212. // interpolating all properties using a parameter of `t`. Subclasses should
  62213. // override this to interpolate additional properties.
  62214. Vertex.prototype.interpolate = function (other, t) {
  62215. 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));
  62216. };
  62217. return Vertex;
  62218. }());
  62219. // # class Plane
  62220. // Represents a plane in 3D space.
  62221. var Plane = (function () {
  62222. function Plane(normal, w) {
  62223. this.normal = normal;
  62224. this.w = w;
  62225. }
  62226. Plane.FromPoints = function (a, b, c) {
  62227. var v0 = c.subtract(a);
  62228. var v1 = b.subtract(a);
  62229. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  62230. return null;
  62231. }
  62232. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  62233. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  62234. };
  62235. Plane.prototype.clone = function () {
  62236. return new Plane(this.normal.clone(), this.w);
  62237. };
  62238. Plane.prototype.flip = function () {
  62239. this.normal.scaleInPlace(-1);
  62240. this.w = -this.w;
  62241. };
  62242. // Split `polygon` by this plane if needed, then put the polygon or polygon
  62243. // fragments in the appropriate lists. Coplanar polygons go into either
  62244. // `coplanarFront` or `coplanarBack` depending on their orientation with
  62245. // respect to this plane. Polygons in front or in back of this plane go into
  62246. // either `front` or `back`.
  62247. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  62248. var COPLANAR = 0;
  62249. var FRONT = 1;
  62250. var BACK = 2;
  62251. var SPANNING = 3;
  62252. // Classify each point as well as the entire polygon into one of the above
  62253. // four classes.
  62254. var polygonType = 0;
  62255. var types = [];
  62256. var i;
  62257. var t;
  62258. for (i = 0; i < polygon.vertices.length; i++) {
  62259. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  62260. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  62261. polygonType |= type;
  62262. types.push(type);
  62263. }
  62264. // Put the polygon in the correct list, splitting it when necessary.
  62265. switch (polygonType) {
  62266. case COPLANAR:
  62267. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  62268. break;
  62269. case FRONT:
  62270. front.push(polygon);
  62271. break;
  62272. case BACK:
  62273. back.push(polygon);
  62274. break;
  62275. case SPANNING:
  62276. var f = [], b = [];
  62277. for (i = 0; i < polygon.vertices.length; i++) {
  62278. var j = (i + 1) % polygon.vertices.length;
  62279. var ti = types[i], tj = types[j];
  62280. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  62281. if (ti !== BACK)
  62282. f.push(vi);
  62283. if (ti !== FRONT)
  62284. b.push(ti !== BACK ? vi.clone() : vi);
  62285. if ((ti | tj) === SPANNING) {
  62286. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  62287. var v = vi.interpolate(vj, t);
  62288. f.push(v);
  62289. b.push(v.clone());
  62290. }
  62291. }
  62292. var poly;
  62293. if (f.length >= 3) {
  62294. poly = new Polygon(f, polygon.shared);
  62295. if (poly.plane)
  62296. front.push(poly);
  62297. }
  62298. if (b.length >= 3) {
  62299. poly = new Polygon(b, polygon.shared);
  62300. if (poly.plane)
  62301. back.push(poly);
  62302. }
  62303. break;
  62304. }
  62305. };
  62306. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  62307. // point is on the plane.
  62308. Plane.EPSILON = 1e-5;
  62309. return Plane;
  62310. }());
  62311. // # class Polygon
  62312. // Represents a convex polygon. The vertices used to initialize a polygon must
  62313. // be coplanar and form a convex loop.
  62314. //
  62315. // Each convex polygon has a `shared` property, which is shared between all
  62316. // polygons that are clones of each other or were split from the same polygon.
  62317. // This can be used to define per-polygon properties (such as surface color).
  62318. var Polygon = (function () {
  62319. function Polygon(vertices, shared) {
  62320. this.vertices = vertices;
  62321. this.shared = shared;
  62322. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  62323. }
  62324. Polygon.prototype.clone = function () {
  62325. var vertices = this.vertices.map(function (v) { return v.clone(); });
  62326. return new Polygon(vertices, this.shared);
  62327. };
  62328. Polygon.prototype.flip = function () {
  62329. this.vertices.reverse().map(function (v) { v.flip(); });
  62330. this.plane.flip();
  62331. };
  62332. return Polygon;
  62333. }());
  62334. // # class Node
  62335. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  62336. // by picking a polygon to split along. That polygon (and all other coplanar
  62337. // polygons) are added directly to that node and the other polygons are added to
  62338. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  62339. // no distinction between internal and leaf nodes.
  62340. var Node = (function () {
  62341. function Node(polygons) {
  62342. this.plane = null;
  62343. this.front = null;
  62344. this.back = null;
  62345. this.polygons = new Array();
  62346. if (polygons) {
  62347. this.build(polygons);
  62348. }
  62349. }
  62350. Node.prototype.clone = function () {
  62351. var node = new Node();
  62352. node.plane = this.plane && this.plane.clone();
  62353. node.front = this.front && this.front.clone();
  62354. node.back = this.back && this.back.clone();
  62355. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  62356. return node;
  62357. };
  62358. // Convert solid space to empty space and empty space to solid space.
  62359. Node.prototype.invert = function () {
  62360. for (var i = 0; i < this.polygons.length; i++) {
  62361. this.polygons[i].flip();
  62362. }
  62363. if (this.plane) {
  62364. this.plane.flip();
  62365. }
  62366. if (this.front) {
  62367. this.front.invert();
  62368. }
  62369. if (this.back) {
  62370. this.back.invert();
  62371. }
  62372. var temp = this.front;
  62373. this.front = this.back;
  62374. this.back = temp;
  62375. };
  62376. // Recursively remove all polygons in `polygons` that are inside this BSP
  62377. // tree.
  62378. Node.prototype.clipPolygons = function (polygons) {
  62379. if (!this.plane)
  62380. return polygons.slice();
  62381. var front = new Array(), back = new Array();
  62382. for (var i = 0; i < polygons.length; i++) {
  62383. this.plane.splitPolygon(polygons[i], front, back, front, back);
  62384. }
  62385. if (this.front) {
  62386. front = this.front.clipPolygons(front);
  62387. }
  62388. if (this.back) {
  62389. back = this.back.clipPolygons(back);
  62390. }
  62391. else {
  62392. back = [];
  62393. }
  62394. return front.concat(back);
  62395. };
  62396. // Remove all polygons in this BSP tree that are inside the other BSP tree
  62397. // `bsp`.
  62398. Node.prototype.clipTo = function (bsp) {
  62399. this.polygons = bsp.clipPolygons(this.polygons);
  62400. if (this.front)
  62401. this.front.clipTo(bsp);
  62402. if (this.back)
  62403. this.back.clipTo(bsp);
  62404. };
  62405. // Return a list of all polygons in this BSP tree.
  62406. Node.prototype.allPolygons = function () {
  62407. var polygons = this.polygons.slice();
  62408. if (this.front)
  62409. polygons = polygons.concat(this.front.allPolygons());
  62410. if (this.back)
  62411. polygons = polygons.concat(this.back.allPolygons());
  62412. return polygons;
  62413. };
  62414. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  62415. // new polygons are filtered down to the bottom of the tree and become new
  62416. // nodes there. Each set of polygons is partitioned using the first polygon
  62417. // (no heuristic is used to pick a good split).
  62418. Node.prototype.build = function (polygons) {
  62419. if (!polygons.length)
  62420. return;
  62421. if (!this.plane)
  62422. this.plane = polygons[0].plane.clone();
  62423. var front = new Array(), back = new Array();
  62424. for (var i = 0; i < polygons.length; i++) {
  62425. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  62426. }
  62427. if (front.length) {
  62428. if (!this.front)
  62429. this.front = new Node();
  62430. this.front.build(front);
  62431. }
  62432. if (back.length) {
  62433. if (!this.back)
  62434. this.back = new Node();
  62435. this.back.build(back);
  62436. }
  62437. };
  62438. return Node;
  62439. }());
  62440. var CSG = (function () {
  62441. function CSG() {
  62442. this.polygons = new Array();
  62443. }
  62444. // Convert BABYLON.Mesh to BABYLON.CSG
  62445. CSG.FromMesh = function (mesh) {
  62446. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  62447. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  62448. if (mesh instanceof BABYLON.Mesh) {
  62449. mesh.computeWorldMatrix(true);
  62450. matrix = mesh.getWorldMatrix();
  62451. meshPosition = mesh.position.clone();
  62452. meshRotation = mesh.rotation.clone();
  62453. if (mesh.rotationQuaternion) {
  62454. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  62455. }
  62456. meshScaling = mesh.scaling.clone();
  62457. }
  62458. else {
  62459. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  62460. }
  62461. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62462. var subMeshes = mesh.subMeshes;
  62463. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  62464. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  62465. vertices = [];
  62466. for (var j = 0; j < 3; j++) {
  62467. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  62468. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  62469. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  62470. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  62471. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  62472. vertex = new Vertex(position, normal, uv);
  62473. vertices.push(vertex);
  62474. }
  62475. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  62476. // To handle the case of degenerated triangle
  62477. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  62478. if (polygon.plane)
  62479. polygons.push(polygon);
  62480. }
  62481. }
  62482. var csg = CSG.FromPolygons(polygons);
  62483. csg.matrix = matrix;
  62484. csg.position = meshPosition;
  62485. csg.rotation = meshRotation;
  62486. csg.scaling = meshScaling;
  62487. csg.rotationQuaternion = meshRotationQuaternion;
  62488. currentCSGMeshId++;
  62489. return csg;
  62490. };
  62491. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  62492. CSG.FromPolygons = function (polygons) {
  62493. var csg = new CSG();
  62494. csg.polygons = polygons;
  62495. return csg;
  62496. };
  62497. CSG.prototype.clone = function () {
  62498. var csg = new CSG();
  62499. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  62500. csg.copyTransformAttributes(this);
  62501. return csg;
  62502. };
  62503. CSG.prototype.toPolygons = function () {
  62504. return this.polygons;
  62505. };
  62506. CSG.prototype.union = function (csg) {
  62507. var a = new Node(this.clone().polygons);
  62508. var b = new Node(csg.clone().polygons);
  62509. a.clipTo(b);
  62510. b.clipTo(a);
  62511. b.invert();
  62512. b.clipTo(a);
  62513. b.invert();
  62514. a.build(b.allPolygons());
  62515. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  62516. };
  62517. CSG.prototype.unionInPlace = function (csg) {
  62518. var a = new Node(this.polygons);
  62519. var b = new Node(csg.polygons);
  62520. a.clipTo(b);
  62521. b.clipTo(a);
  62522. b.invert();
  62523. b.clipTo(a);
  62524. b.invert();
  62525. a.build(b.allPolygons());
  62526. this.polygons = a.allPolygons();
  62527. };
  62528. CSG.prototype.subtract = function (csg) {
  62529. var a = new Node(this.clone().polygons);
  62530. var b = new Node(csg.clone().polygons);
  62531. a.invert();
  62532. a.clipTo(b);
  62533. b.clipTo(a);
  62534. b.invert();
  62535. b.clipTo(a);
  62536. b.invert();
  62537. a.build(b.allPolygons());
  62538. a.invert();
  62539. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  62540. };
  62541. CSG.prototype.subtractInPlace = function (csg) {
  62542. var a = new Node(this.polygons);
  62543. var b = new Node(csg.polygons);
  62544. a.invert();
  62545. a.clipTo(b);
  62546. b.clipTo(a);
  62547. b.invert();
  62548. b.clipTo(a);
  62549. b.invert();
  62550. a.build(b.allPolygons());
  62551. a.invert();
  62552. this.polygons = a.allPolygons();
  62553. };
  62554. CSG.prototype.intersect = function (csg) {
  62555. var a = new Node(this.clone().polygons);
  62556. var b = new Node(csg.clone().polygons);
  62557. a.invert();
  62558. b.clipTo(a);
  62559. b.invert();
  62560. a.clipTo(b);
  62561. b.clipTo(a);
  62562. a.build(b.allPolygons());
  62563. a.invert();
  62564. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  62565. };
  62566. CSG.prototype.intersectInPlace = function (csg) {
  62567. var a = new Node(this.polygons);
  62568. var b = new Node(csg.polygons);
  62569. a.invert();
  62570. b.clipTo(a);
  62571. b.invert();
  62572. a.clipTo(b);
  62573. b.clipTo(a);
  62574. a.build(b.allPolygons());
  62575. a.invert();
  62576. this.polygons = a.allPolygons();
  62577. };
  62578. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  62579. // not modified.
  62580. CSG.prototype.inverse = function () {
  62581. var csg = this.clone();
  62582. csg.inverseInPlace();
  62583. return csg;
  62584. };
  62585. CSG.prototype.inverseInPlace = function () {
  62586. this.polygons.map(function (p) { p.flip(); });
  62587. };
  62588. // This is used to keep meshes transformations so they can be restored
  62589. // when we build back a Babylon Mesh
  62590. // NB : All CSG operations are performed in world coordinates
  62591. CSG.prototype.copyTransformAttributes = function (csg) {
  62592. this.matrix = csg.matrix;
  62593. this.position = csg.position;
  62594. this.rotation = csg.rotation;
  62595. this.scaling = csg.scaling;
  62596. this.rotationQuaternion = csg.rotationQuaternion;
  62597. return this;
  62598. };
  62599. // Build Raw mesh from CSG
  62600. // Coordinates here are in world space
  62601. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  62602. var matrix = this.matrix.clone();
  62603. matrix.invert();
  62604. 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;
  62605. if (keepSubMeshes) {
  62606. // Sort Polygons, since subMeshes are indices range
  62607. polygons.sort(function (a, b) {
  62608. if (a.shared.meshId === b.shared.meshId) {
  62609. return a.shared.subMeshId - b.shared.subMeshId;
  62610. }
  62611. else {
  62612. return a.shared.meshId - b.shared.meshId;
  62613. }
  62614. });
  62615. }
  62616. for (var i = 0, il = polygons.length; i < il; i++) {
  62617. polygon = polygons[i];
  62618. // Building SubMeshes
  62619. if (!subMesh_dict[polygon.shared.meshId]) {
  62620. subMesh_dict[polygon.shared.meshId] = {};
  62621. }
  62622. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  62623. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  62624. indexStart: +Infinity,
  62625. indexEnd: -Infinity,
  62626. materialIndex: polygon.shared.materialIndex
  62627. };
  62628. }
  62629. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  62630. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  62631. polygonIndices[0] = 0;
  62632. polygonIndices[1] = j - 1;
  62633. polygonIndices[2] = j;
  62634. for (var k = 0; k < 3; k++) {
  62635. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  62636. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  62637. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  62638. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  62639. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  62640. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  62641. // Check if 2 points can be merged
  62642. if (!(typeof vertex_idx !== 'undefined' &&
  62643. normals[vertex_idx * 3] === localNormal.x &&
  62644. normals[vertex_idx * 3 + 1] === localNormal.y &&
  62645. normals[vertex_idx * 3 + 2] === localNormal.z &&
  62646. uvs[vertex_idx * 2] === uv.x &&
  62647. uvs[vertex_idx * 2 + 1] === uv.y)) {
  62648. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  62649. uvs.push(uv.x, uv.y);
  62650. normals.push(normal.x, normal.y, normal.z);
  62651. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  62652. }
  62653. indices.push(vertex_idx);
  62654. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  62655. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  62656. currentIndex++;
  62657. }
  62658. }
  62659. }
  62660. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  62661. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  62662. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  62663. mesh.setIndices(indices);
  62664. if (keepSubMeshes) {
  62665. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  62666. var materialIndexOffset = 0, materialMaxIndex;
  62667. mesh.subMeshes = new Array();
  62668. for (var m in subMesh_dict) {
  62669. materialMaxIndex = -1;
  62670. for (var sm in subMesh_dict[m]) {
  62671. subMesh_obj = subMesh_dict[m][sm];
  62672. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  62673. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  62674. }
  62675. materialIndexOffset += ++materialMaxIndex;
  62676. }
  62677. }
  62678. return mesh;
  62679. };
  62680. // Build Mesh from CSG taking material and transforms into account
  62681. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  62682. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  62683. mesh.material = material;
  62684. mesh.position.copyFrom(this.position);
  62685. mesh.rotation.copyFrom(this.rotation);
  62686. if (this.rotationQuaternion) {
  62687. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  62688. }
  62689. mesh.scaling.copyFrom(this.scaling);
  62690. mesh.computeWorldMatrix(true);
  62691. return mesh;
  62692. };
  62693. return CSG;
  62694. }());
  62695. BABYLON.CSG = CSG;
  62696. })(BABYLON || (BABYLON = {}));
  62697. //# sourceMappingURL=babylon.csg.js.map
  62698. var BABYLON;
  62699. (function (BABYLON) {
  62700. var LensFlare = (function () {
  62701. function LensFlare(size, position, color, imgUrl, system) {
  62702. this.size = size;
  62703. this.position = position;
  62704. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  62705. this.dispose = function () {
  62706. if (this.texture) {
  62707. this.texture.dispose();
  62708. }
  62709. // Remove from scene
  62710. var index = this._system.lensFlares.indexOf(this);
  62711. this._system.lensFlares.splice(index, 1);
  62712. };
  62713. this.color = color || new BABYLON.Color3(1, 1, 1);
  62714. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  62715. this._system = system;
  62716. system.lensFlares.push(this);
  62717. }
  62718. return LensFlare;
  62719. }());
  62720. BABYLON.LensFlare = LensFlare;
  62721. })(BABYLON || (BABYLON = {}));
  62722. //# sourceMappingURL=babylon.lensFlare.js.map
  62723. var BABYLON;
  62724. (function (BABYLON) {
  62725. var LensFlareSystem = (function () {
  62726. function LensFlareSystem(name, emitter, scene) {
  62727. this.name = name;
  62728. this.lensFlares = new Array();
  62729. this.borderLimit = 300;
  62730. this.viewportBorder = 0;
  62731. this.layerMask = 0x0FFFFFFF;
  62732. this._vertexBuffers = {};
  62733. this._isEnabled = true;
  62734. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62735. this._emitter = emitter;
  62736. this.id = name;
  62737. scene.lensFlareSystems.push(this);
  62738. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  62739. var engine = scene.getEngine();
  62740. // VBO
  62741. var vertices = [];
  62742. vertices.push(1, 1);
  62743. vertices.push(-1, 1);
  62744. vertices.push(-1, -1);
  62745. vertices.push(1, -1);
  62746. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  62747. // Indices
  62748. var indices = [];
  62749. indices.push(0);
  62750. indices.push(1);
  62751. indices.push(2);
  62752. indices.push(0);
  62753. indices.push(2);
  62754. indices.push(3);
  62755. this._indexBuffer = engine.createIndexBuffer(indices);
  62756. // Effects
  62757. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  62758. }
  62759. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  62760. get: function () {
  62761. return this._isEnabled;
  62762. },
  62763. set: function (value) {
  62764. this._isEnabled = value;
  62765. },
  62766. enumerable: true,
  62767. configurable: true
  62768. });
  62769. LensFlareSystem.prototype.getScene = function () {
  62770. return this._scene;
  62771. };
  62772. LensFlareSystem.prototype.getEmitter = function () {
  62773. return this._emitter;
  62774. };
  62775. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  62776. this._emitter = newEmitter;
  62777. };
  62778. LensFlareSystem.prototype.getEmitterPosition = function () {
  62779. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  62780. };
  62781. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  62782. var position = this.getEmitterPosition();
  62783. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  62784. this._positionX = position.x;
  62785. this._positionY = position.y;
  62786. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  62787. if (this.viewportBorder > 0) {
  62788. globalViewport.x -= this.viewportBorder;
  62789. globalViewport.y -= this.viewportBorder;
  62790. globalViewport.width += this.viewportBorder * 2;
  62791. globalViewport.height += this.viewportBorder * 2;
  62792. position.x += this.viewportBorder;
  62793. position.y += this.viewportBorder;
  62794. this._positionX += this.viewportBorder;
  62795. this._positionY += this.viewportBorder;
  62796. }
  62797. if (position.z > 0) {
  62798. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  62799. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  62800. return true;
  62801. }
  62802. return true;
  62803. }
  62804. return false;
  62805. };
  62806. LensFlareSystem.prototype._isVisible = function () {
  62807. if (!this._isEnabled) {
  62808. return false;
  62809. }
  62810. var emitterPosition = this.getEmitterPosition();
  62811. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  62812. var distance = direction.length();
  62813. direction.normalize();
  62814. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  62815. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  62816. return !pickInfo.hit || pickInfo.distance > distance;
  62817. };
  62818. LensFlareSystem.prototype.render = function () {
  62819. if (!this._effect.isReady())
  62820. return false;
  62821. var engine = this._scene.getEngine();
  62822. var viewport = this._scene.activeCamera.viewport;
  62823. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  62824. // Position
  62825. if (!this.computeEffectivePosition(globalViewport)) {
  62826. return false;
  62827. }
  62828. // Visibility
  62829. if (!this._isVisible()) {
  62830. return false;
  62831. }
  62832. // Intensity
  62833. var awayX;
  62834. var awayY;
  62835. if (this._positionX < this.borderLimit + globalViewport.x) {
  62836. awayX = this.borderLimit + globalViewport.x - this._positionX;
  62837. }
  62838. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  62839. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  62840. }
  62841. else {
  62842. awayX = 0;
  62843. }
  62844. if (this._positionY < this.borderLimit + globalViewport.y) {
  62845. awayY = this.borderLimit + globalViewport.y - this._positionY;
  62846. }
  62847. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  62848. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  62849. }
  62850. else {
  62851. awayY = 0;
  62852. }
  62853. var away = (awayX > awayY) ? awayX : awayY;
  62854. away -= this.viewportBorder;
  62855. if (away > this.borderLimit) {
  62856. away = this.borderLimit;
  62857. }
  62858. var intensity = 1.0 - (away / this.borderLimit);
  62859. if (intensity < 0) {
  62860. return false;
  62861. }
  62862. if (intensity > 1.0) {
  62863. intensity = 1.0;
  62864. }
  62865. if (this.viewportBorder > 0) {
  62866. globalViewport.x += this.viewportBorder;
  62867. globalViewport.y += this.viewportBorder;
  62868. globalViewport.width -= this.viewportBorder * 2;
  62869. globalViewport.height -= this.viewportBorder * 2;
  62870. this._positionX -= this.viewportBorder;
  62871. this._positionY -= this.viewportBorder;
  62872. }
  62873. // Position
  62874. var centerX = globalViewport.x + globalViewport.width / 2;
  62875. var centerY = globalViewport.y + globalViewport.height / 2;
  62876. var distX = centerX - this._positionX;
  62877. var distY = centerY - this._positionY;
  62878. // Effects
  62879. engine.enableEffect(this._effect);
  62880. engine.setState(false);
  62881. engine.setDepthBuffer(false);
  62882. // VBOs
  62883. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  62884. // Flares
  62885. for (var index = 0; index < this.lensFlares.length; index++) {
  62886. var flare = this.lensFlares[index];
  62887. engine.setAlphaMode(flare.alphaMode);
  62888. var x = centerX - (distX * flare.position);
  62889. var y = centerY - (distY * flare.position);
  62890. var cw = flare.size;
  62891. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  62892. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  62893. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  62894. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  62895. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  62896. // Texture
  62897. this._effect.setTexture("textureSampler", flare.texture);
  62898. // Color
  62899. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  62900. // Draw order
  62901. engine.draw(true, 0, 6);
  62902. }
  62903. engine.setDepthBuffer(true);
  62904. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  62905. return true;
  62906. };
  62907. LensFlareSystem.prototype.dispose = function () {
  62908. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62909. if (vertexBuffer) {
  62910. vertexBuffer.dispose();
  62911. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  62912. }
  62913. if (this._indexBuffer) {
  62914. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  62915. this._indexBuffer = null;
  62916. }
  62917. while (this.lensFlares.length) {
  62918. this.lensFlares[0].dispose();
  62919. }
  62920. // Remove from scene
  62921. var index = this._scene.lensFlareSystems.indexOf(this);
  62922. this._scene.lensFlareSystems.splice(index, 1);
  62923. };
  62924. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  62925. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  62926. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  62927. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  62928. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  62929. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  62930. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  62931. var parsedFlare = parsedLensFlareSystem.flares[index];
  62932. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  62933. }
  62934. return lensFlareSystem;
  62935. };
  62936. LensFlareSystem.prototype.serialize = function () {
  62937. var serializationObject = {};
  62938. serializationObject.id = this.id;
  62939. serializationObject.name = this.name;
  62940. serializationObject.emitterId = this.getEmitter().id;
  62941. serializationObject.borderLimit = this.borderLimit;
  62942. serializationObject.flares = [];
  62943. for (var index = 0; index < this.lensFlares.length; index++) {
  62944. var flare = this.lensFlares[index];
  62945. serializationObject.flares.push({
  62946. size: flare.size,
  62947. position: flare.position,
  62948. color: flare.color.asArray(),
  62949. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  62950. });
  62951. }
  62952. return serializationObject;
  62953. };
  62954. return LensFlareSystem;
  62955. }());
  62956. BABYLON.LensFlareSystem = LensFlareSystem;
  62957. })(BABYLON || (BABYLON = {}));
  62958. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  62959. var BABYLON;
  62960. (function (BABYLON) {
  62961. /**
  62962. * This is a holder class for the physics joint created by the physics plugin.
  62963. * It holds a set of functions to control the underlying joint.
  62964. */
  62965. var PhysicsJoint = (function () {
  62966. function PhysicsJoint(type, jointData) {
  62967. this.type = type;
  62968. this.jointData = jointData;
  62969. jointData.nativeParams = jointData.nativeParams || {};
  62970. }
  62971. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  62972. get: function () {
  62973. return this._physicsJoint;
  62974. },
  62975. set: function (newJoint) {
  62976. if (this._physicsJoint) {
  62977. //remove from the wolrd
  62978. }
  62979. this._physicsJoint = newJoint;
  62980. },
  62981. enumerable: true,
  62982. configurable: true
  62983. });
  62984. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  62985. set: function (physicsPlugin) {
  62986. this._physicsPlugin = physicsPlugin;
  62987. },
  62988. enumerable: true,
  62989. configurable: true
  62990. });
  62991. /**
  62992. * Execute a function that is physics-plugin specific.
  62993. * @param {Function} func the function that will be executed.
  62994. * It accepts two parameters: the physics world and the physics joint.
  62995. */
  62996. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  62997. func(this._physicsPlugin.world, this._physicsJoint);
  62998. };
  62999. //TODO check if the native joints are the same
  63000. //Joint Types
  63001. PhysicsJoint.DistanceJoint = 0;
  63002. PhysicsJoint.HingeJoint = 1;
  63003. PhysicsJoint.BallAndSocketJoint = 2;
  63004. PhysicsJoint.WheelJoint = 3;
  63005. PhysicsJoint.SliderJoint = 4;
  63006. //OIMO
  63007. PhysicsJoint.PrismaticJoint = 5;
  63008. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  63009. PhysicsJoint.UniversalJoint = 6;
  63010. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  63011. //Cannon
  63012. //Similar to a Ball-Joint. Different in params
  63013. PhysicsJoint.PointToPointJoint = 8;
  63014. //Cannon only at the moment
  63015. PhysicsJoint.SpringJoint = 9;
  63016. PhysicsJoint.LockJoint = 10;
  63017. return PhysicsJoint;
  63018. }());
  63019. BABYLON.PhysicsJoint = PhysicsJoint;
  63020. /**
  63021. * A class representing a physics distance joint.
  63022. */
  63023. var DistanceJoint = (function (_super) {
  63024. __extends(DistanceJoint, _super);
  63025. function DistanceJoint(jointData) {
  63026. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  63027. }
  63028. /**
  63029. * Update the predefined distance.
  63030. */
  63031. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  63032. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  63033. };
  63034. return DistanceJoint;
  63035. }(PhysicsJoint));
  63036. BABYLON.DistanceJoint = DistanceJoint;
  63037. var MotorEnabledJoint = (function (_super) {
  63038. __extends(MotorEnabledJoint, _super);
  63039. function MotorEnabledJoint(type, jointData) {
  63040. return _super.call(this, type, jointData) || this;
  63041. }
  63042. /**
  63043. * Set the motor values.
  63044. * Attention, this function is plugin specific. Engines won't react 100% the same.
  63045. * @param {number} force the force to apply
  63046. * @param {number} maxForce max force for this motor.
  63047. */
  63048. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  63049. this._physicsPlugin.setMotor(this, force, maxForce);
  63050. };
  63051. /**
  63052. * Set the motor's limits.
  63053. * Attention, this function is plugin specific. Engines won't react 100% the same.
  63054. */
  63055. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  63056. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  63057. };
  63058. return MotorEnabledJoint;
  63059. }(PhysicsJoint));
  63060. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  63061. /**
  63062. * This class represents a single hinge physics joint
  63063. */
  63064. var HingeJoint = (function (_super) {
  63065. __extends(HingeJoint, _super);
  63066. function HingeJoint(jointData) {
  63067. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  63068. }
  63069. /**
  63070. * Set the motor values.
  63071. * Attention, this function is plugin specific. Engines won't react 100% the same.
  63072. * @param {number} force the force to apply
  63073. * @param {number} maxForce max force for this motor.
  63074. */
  63075. HingeJoint.prototype.setMotor = function (force, maxForce) {
  63076. this._physicsPlugin.setMotor(this, force, maxForce);
  63077. };
  63078. /**
  63079. * Set the motor's limits.
  63080. * Attention, this function is plugin specific. Engines won't react 100% the same.
  63081. */
  63082. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  63083. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  63084. };
  63085. return HingeJoint;
  63086. }(MotorEnabledJoint));
  63087. BABYLON.HingeJoint = HingeJoint;
  63088. /**
  63089. * This class represents a dual hinge physics joint (same as wheel joint)
  63090. */
  63091. var Hinge2Joint = (function (_super) {
  63092. __extends(Hinge2Joint, _super);
  63093. function Hinge2Joint(jointData) {
  63094. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  63095. }
  63096. /**
  63097. * Set the motor values.
  63098. * Attention, this function is plugin specific. Engines won't react 100% the same.
  63099. * @param {number} force the force to apply
  63100. * @param {number} maxForce max force for this motor.
  63101. * @param {motorIndex} the motor's index, 0 or 1.
  63102. */
  63103. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  63104. if (motorIndex === void 0) { motorIndex = 0; }
  63105. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  63106. };
  63107. /**
  63108. * Set the motor limits.
  63109. * Attention, this function is plugin specific. Engines won't react 100% the same.
  63110. * @param {number} upperLimit the upper limit
  63111. * @param {number} lowerLimit lower limit
  63112. * @param {motorIndex} the motor's index, 0 or 1.
  63113. */
  63114. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  63115. if (motorIndex === void 0) { motorIndex = 0; }
  63116. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  63117. };
  63118. return Hinge2Joint;
  63119. }(MotorEnabledJoint));
  63120. BABYLON.Hinge2Joint = Hinge2Joint;
  63121. })(BABYLON || (BABYLON = {}));
  63122. //# sourceMappingURL=babylon.physicsJoint.js.map
  63123. var BABYLON;
  63124. (function (BABYLON) {
  63125. var PhysicsImpostor = (function () {
  63126. function PhysicsImpostor(object, type, _options, _scene) {
  63127. if (_options === void 0) { _options = { mass: 0 }; }
  63128. var _this = this;
  63129. this.object = object;
  63130. this.type = type;
  63131. this._options = _options;
  63132. this._scene = _scene;
  63133. this._bodyUpdateRequired = false;
  63134. this._onBeforePhysicsStepCallbacks = new Array();
  63135. this._onAfterPhysicsStepCallbacks = new Array();
  63136. this._onPhysicsCollideCallbacks = [];
  63137. this._deltaPosition = BABYLON.Vector3.Zero();
  63138. this._isDisposed = false;
  63139. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  63140. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  63141. /**
  63142. * this function is executed by the physics engine.
  63143. */
  63144. this.beforeStep = function () {
  63145. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  63146. //conjugate deltaRotation
  63147. if (_this._deltaRotationConjugated) {
  63148. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  63149. }
  63150. else {
  63151. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  63152. }
  63153. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  63154. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  63155. func(_this);
  63156. });
  63157. };
  63158. /**
  63159. * this function is executed by the physics engine.
  63160. */
  63161. this.afterStep = function () {
  63162. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  63163. func(_this);
  63164. });
  63165. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  63166. _this.object.position.addInPlace(_this._deltaPosition);
  63167. if (_this._deltaRotation) {
  63168. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  63169. }
  63170. };
  63171. /**
  63172. * Legacy collision detection event support
  63173. */
  63174. this.onCollideEvent = null;
  63175. //event and body object due to cannon's event-based architecture.
  63176. this.onCollide = function (e) {
  63177. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  63178. return;
  63179. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  63180. if (otherImpostor) {
  63181. // Legacy collision detection event support
  63182. if (_this.onCollideEvent) {
  63183. _this.onCollideEvent(_this, otherImpostor);
  63184. }
  63185. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  63186. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  63187. }).forEach(function (obj) {
  63188. obj.callback(_this, otherImpostor);
  63189. });
  63190. }
  63191. };
  63192. //sanity check!
  63193. if (!this.object) {
  63194. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  63195. return;
  63196. }
  63197. //legacy support for old syntax.
  63198. if (!this._scene && object.getScene) {
  63199. this._scene = object.getScene();
  63200. }
  63201. this._physicsEngine = this._scene.getPhysicsEngine();
  63202. if (!this._physicsEngine) {
  63203. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  63204. }
  63205. else {
  63206. //set the object's quaternion, if not set
  63207. if (!this.object.rotationQuaternion) {
  63208. if (this.object.rotation) {
  63209. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  63210. }
  63211. else {
  63212. this.object.rotationQuaternion = new BABYLON.Quaternion();
  63213. }
  63214. }
  63215. //default options params
  63216. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  63217. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  63218. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  63219. this._joints = [];
  63220. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  63221. if (!this.object.parent) {
  63222. this._init();
  63223. }
  63224. else if (this.object.parent.physicsImpostor) {
  63225. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  63226. }
  63227. }
  63228. }
  63229. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  63230. get: function () {
  63231. return this._isDisposed;
  63232. },
  63233. enumerable: true,
  63234. configurable: true
  63235. });
  63236. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  63237. get: function () {
  63238. return this._physicsEngine.getPhysicsPlugin().getBodyMass(this);
  63239. },
  63240. set: function (value) {
  63241. this.setMass(value);
  63242. },
  63243. enumerable: true,
  63244. configurable: true
  63245. });
  63246. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  63247. get: function () {
  63248. return this._physicsEngine.getPhysicsPlugin().getBodyFriction(this);
  63249. },
  63250. set: function (value) {
  63251. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  63252. },
  63253. enumerable: true,
  63254. configurable: true
  63255. });
  63256. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  63257. get: function () {
  63258. return this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this);
  63259. },
  63260. set: function (value) {
  63261. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  63262. },
  63263. enumerable: true,
  63264. configurable: true
  63265. });
  63266. /**
  63267. * This function will completly initialize this impostor.
  63268. * It will create a new body - but only if this mesh has no parent.
  63269. * If it has, this impostor will not be used other than to define the impostor
  63270. * of the child mesh.
  63271. */
  63272. PhysicsImpostor.prototype._init = function () {
  63273. this._physicsEngine.removeImpostor(this);
  63274. this.physicsBody = null;
  63275. this._parent = this._parent || this._getPhysicsParent();
  63276. if (!this.parent) {
  63277. this._physicsEngine.addImpostor(this);
  63278. }
  63279. };
  63280. PhysicsImpostor.prototype._getPhysicsParent = function () {
  63281. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  63282. var parentMesh = this.object.parent;
  63283. return parentMesh.physicsImpostor;
  63284. }
  63285. return;
  63286. };
  63287. /**
  63288. * Should a new body be generated.
  63289. */
  63290. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  63291. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  63292. };
  63293. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  63294. this.forceUpdate();
  63295. };
  63296. /**
  63297. * Force a regeneration of this or the parent's impostor's body.
  63298. * Use under cautious - This will remove all joints already implemented.
  63299. */
  63300. PhysicsImpostor.prototype.forceUpdate = function () {
  63301. this._init();
  63302. if (this.parent) {
  63303. this.parent.forceUpdate();
  63304. }
  63305. };
  63306. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  63307. /*public get mesh(): AbstractMesh {
  63308. return this._mesh;
  63309. }*/
  63310. /**
  63311. * Gets the body that holds this impostor. Either its own, or its parent.
  63312. */
  63313. get: function () {
  63314. return this._parent ? this._parent.physicsBody : this._physicsBody;
  63315. },
  63316. /**
  63317. * Set the physics body. Used mainly by the physics engine/plugin
  63318. */
  63319. set: function (physicsBody) {
  63320. if (this._physicsBody) {
  63321. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  63322. }
  63323. this._physicsBody = physicsBody;
  63324. this.resetUpdateFlags();
  63325. },
  63326. enumerable: true,
  63327. configurable: true
  63328. });
  63329. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  63330. get: function () {
  63331. return this._parent;
  63332. },
  63333. set: function (value) {
  63334. this._parent = value;
  63335. },
  63336. enumerable: true,
  63337. configurable: true
  63338. });
  63339. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  63340. this._bodyUpdateRequired = false;
  63341. };
  63342. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  63343. if (this.object.getBoundingInfo) {
  63344. var q = this.object.rotationQuaternion;
  63345. //reset rotation
  63346. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  63347. //calculate the world matrix with no rotation
  63348. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  63349. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  63350. //bring back the rotation
  63351. this.object.rotationQuaternion = q;
  63352. //calculate the world matrix with the new rotation
  63353. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  63354. return size;
  63355. }
  63356. else {
  63357. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  63358. }
  63359. };
  63360. PhysicsImpostor.prototype.getObjectCenter = function () {
  63361. if (this.object.getBoundingInfo) {
  63362. return this.object.getBoundingInfo().boundingBox.centerWorld;
  63363. }
  63364. else {
  63365. return this.object.position;
  63366. }
  63367. };
  63368. /**
  63369. * Get a specific parametes from the options parameter.
  63370. */
  63371. PhysicsImpostor.prototype.getParam = function (paramName) {
  63372. return this._options[paramName];
  63373. };
  63374. /**
  63375. * Sets a specific parameter in the options given to the physics plugin
  63376. */
  63377. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  63378. this._options[paramName] = value;
  63379. this._bodyUpdateRequired = true;
  63380. };
  63381. /**
  63382. * Specifically change the body's mass option. Won't recreate the physics body object
  63383. */
  63384. PhysicsImpostor.prototype.setMass = function (mass) {
  63385. if (this.getParam("mass") !== mass) {
  63386. this.setParam("mass", mass);
  63387. }
  63388. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  63389. };
  63390. PhysicsImpostor.prototype.getLinearVelocity = function () {
  63391. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  63392. };
  63393. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  63394. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  63395. };
  63396. PhysicsImpostor.prototype.getAngularVelocity = function () {
  63397. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  63398. };
  63399. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  63400. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  63401. };
  63402. /**
  63403. * Execute a function with the physics plugin native code.
  63404. * Provide a function the will have two variables - the world object and the physics body object.
  63405. */
  63406. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  63407. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  63408. };
  63409. /**
  63410. * Register a function that will be executed before the physics world is stepping forward.
  63411. */
  63412. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  63413. this._onBeforePhysicsStepCallbacks.push(func);
  63414. };
  63415. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  63416. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  63417. if (index > -1) {
  63418. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  63419. }
  63420. else {
  63421. BABYLON.Tools.Warn("Function to remove was not found");
  63422. }
  63423. };
  63424. /**
  63425. * Register a function that will be executed after the physics step
  63426. */
  63427. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  63428. this._onAfterPhysicsStepCallbacks.push(func);
  63429. };
  63430. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  63431. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  63432. if (index > -1) {
  63433. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  63434. }
  63435. else {
  63436. BABYLON.Tools.Warn("Function to remove was not found");
  63437. }
  63438. };
  63439. /**
  63440. * register a function that will be executed when this impostor collides against a different body.
  63441. */
  63442. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  63443. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  63444. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  63445. };
  63446. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  63447. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  63448. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  63449. if (index > -1) {
  63450. this._onPhysicsCollideCallbacks.splice(index, 1);
  63451. }
  63452. else {
  63453. BABYLON.Tools.Warn("Function to remove was not found");
  63454. }
  63455. };
  63456. /**
  63457. * Apply a force
  63458. */
  63459. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  63460. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  63461. };
  63462. /**
  63463. * Apply an impulse
  63464. */
  63465. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  63466. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  63467. };
  63468. /**
  63469. * A help function to create a joint.
  63470. */
  63471. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  63472. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  63473. this.addJoint(otherImpostor, joint);
  63474. };
  63475. /**
  63476. * Add a joint to this impostor with a different impostor.
  63477. */
  63478. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  63479. this._joints.push({
  63480. otherImpostor: otherImpostor,
  63481. joint: joint
  63482. });
  63483. this._physicsEngine.addJoint(this, otherImpostor, joint);
  63484. };
  63485. /**
  63486. * Will keep this body still, in a sleep mode.
  63487. */
  63488. PhysicsImpostor.prototype.sleep = function () {
  63489. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  63490. };
  63491. /**
  63492. * Wake the body up.
  63493. */
  63494. PhysicsImpostor.prototype.wakeUp = function () {
  63495. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  63496. };
  63497. PhysicsImpostor.prototype.clone = function (newObject) {
  63498. if (!newObject)
  63499. return null;
  63500. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  63501. };
  63502. PhysicsImpostor.prototype.dispose = function () {
  63503. var _this = this;
  63504. //no dispose if no physics engine is available.
  63505. if (!this._physicsEngine) {
  63506. return;
  63507. }
  63508. this._joints.forEach(function (j) {
  63509. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  63510. });
  63511. //dispose the physics body
  63512. this._physicsEngine.removeImpostor(this);
  63513. if (this.parent) {
  63514. this.parent.forceUpdate();
  63515. }
  63516. else {
  63517. /*this._object.getChildMeshes().forEach(function(mesh) {
  63518. if (mesh.physicsImpostor) {
  63519. if (disposeChildren) {
  63520. mesh.physicsImpostor.dispose();
  63521. mesh.physicsImpostor = null;
  63522. }
  63523. }
  63524. })*/
  63525. }
  63526. this._isDisposed = true;
  63527. };
  63528. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  63529. this._deltaPosition.copyFrom(position);
  63530. };
  63531. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  63532. if (!this._deltaRotation) {
  63533. this._deltaRotation = new BABYLON.Quaternion();
  63534. }
  63535. this._deltaRotation.copyFrom(rotation);
  63536. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  63537. };
  63538. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  63539. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  63540. };
  63541. PhysicsImpostor.prototype.getRadius = function () {
  63542. return this._physicsEngine.getPhysicsPlugin().getRadius(this);
  63543. };
  63544. /**
  63545. * Sync a bone with this impostor
  63546. * @param bone The bone to sync to the impostor.
  63547. * @param boneMesh The mesh that the bone is influencing.
  63548. * @param jointPivot The pivot of the joint / bone in local space.
  63549. * @param distToJoint Optional distance from the impostor to the joint.
  63550. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  63551. */
  63552. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  63553. var tempVec = PhysicsImpostor._tmpVecs[0];
  63554. var mesh = this.object;
  63555. if (adjustRotation) {
  63556. var tempQuat = PhysicsImpostor._tmpQuat;
  63557. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  63558. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  63559. }
  63560. else {
  63561. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  63562. }
  63563. tempVec.x = 0;
  63564. tempVec.y = 0;
  63565. tempVec.z = 0;
  63566. if (jointPivot) {
  63567. tempVec.x = jointPivot.x;
  63568. tempVec.y = jointPivot.y;
  63569. tempVec.z = jointPivot.z;
  63570. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  63571. if (distToJoint === undefined || distToJoint === null) {
  63572. distToJoint = jointPivot.length();
  63573. }
  63574. tempVec.x *= distToJoint;
  63575. tempVec.y *= distToJoint;
  63576. tempVec.z *= distToJoint;
  63577. }
  63578. if (bone.getParent()) {
  63579. tempVec.addInPlace(mesh.getAbsolutePosition());
  63580. bone.setAbsolutePosition(tempVec, boneMesh);
  63581. }
  63582. else {
  63583. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  63584. boneMesh.position.x -= tempVec.x;
  63585. boneMesh.position.y -= tempVec.y;
  63586. boneMesh.position.z -= tempVec.z;
  63587. }
  63588. };
  63589. /**
  63590. * Sync impostor to a bone
  63591. * @param bone The bone that the impostor will be synced to.
  63592. * @param boneMesh The mesh that the bone is influencing.
  63593. * @param jointPivot The pivot of the joint / bone in local space.
  63594. * @param distToJoint Optional distance from the impostor to the joint.
  63595. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  63596. * @param boneAxis Optional vector3 axis the bone is aligned with
  63597. */
  63598. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  63599. var mesh = this.object;
  63600. if (adjustRotation) {
  63601. var tempQuat = PhysicsImpostor._tmpQuat;
  63602. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  63603. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  63604. }
  63605. else {
  63606. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  63607. }
  63608. var pos = PhysicsImpostor._tmpVecs[0];
  63609. var boneDir = PhysicsImpostor._tmpVecs[1];
  63610. if (!boneAxis) {
  63611. boneAxis = PhysicsImpostor._tmpVecs[2];
  63612. boneAxis.x = 0;
  63613. boneAxis.y = 1;
  63614. boneAxis.z = 0;
  63615. }
  63616. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  63617. bone.getAbsolutePositionToRef(boneMesh, pos);
  63618. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  63619. distToJoint = jointPivot.length();
  63620. }
  63621. if (distToJoint !== undefined && distToJoint !== null) {
  63622. pos.x += boneDir.x * distToJoint;
  63623. pos.y += boneDir.y * distToJoint;
  63624. pos.z += boneDir.z * distToJoint;
  63625. }
  63626. mesh.setAbsolutePosition(pos);
  63627. };
  63628. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  63629. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  63630. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63631. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  63632. //Impostor types
  63633. PhysicsImpostor.NoImpostor = 0;
  63634. PhysicsImpostor.SphereImpostor = 1;
  63635. PhysicsImpostor.BoxImpostor = 2;
  63636. PhysicsImpostor.PlaneImpostor = 3;
  63637. PhysicsImpostor.MeshImpostor = 4;
  63638. PhysicsImpostor.CylinderImpostor = 7;
  63639. PhysicsImpostor.ParticleImpostor = 8;
  63640. PhysicsImpostor.HeightmapImpostor = 9;
  63641. return PhysicsImpostor;
  63642. }());
  63643. BABYLON.PhysicsImpostor = PhysicsImpostor;
  63644. })(BABYLON || (BABYLON = {}));
  63645. //# sourceMappingURL=babylon.physicsImpostor.js.map
  63646. var BABYLON;
  63647. (function (BABYLON) {
  63648. var PhysicsEngine = (function () {
  63649. function PhysicsEngine(gravity, _physicsPlugin) {
  63650. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  63651. this._physicsPlugin = _physicsPlugin;
  63652. //new methods and parameters
  63653. this._impostors = [];
  63654. this._joints = [];
  63655. if (!this._physicsPlugin.isSupported()) {
  63656. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  63657. + "Please make sure it is included.");
  63658. }
  63659. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  63660. this.setGravity(gravity);
  63661. this.setTimeStep();
  63662. }
  63663. PhysicsEngine.prototype.setGravity = function (gravity) {
  63664. this.gravity = gravity;
  63665. this._physicsPlugin.setGravity(this.gravity);
  63666. };
  63667. /**
  63668. * Set the time step of the physics engine.
  63669. * default is 1/60.
  63670. * To slow it down, enter 1/600 for example.
  63671. * To speed it up, 1/30
  63672. * @param {number} newTimeStep the new timestep to apply to this world.
  63673. */
  63674. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  63675. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  63676. this._physicsPlugin.setTimeStep(newTimeStep);
  63677. };
  63678. /**
  63679. * Get the time step of the physics engine.
  63680. */
  63681. PhysicsEngine.prototype.getTimeStep = function () {
  63682. return this._physicsPlugin.getTimeStep();
  63683. };
  63684. PhysicsEngine.prototype.dispose = function () {
  63685. this._impostors.forEach(function (impostor) {
  63686. impostor.dispose();
  63687. });
  63688. this._physicsPlugin.dispose();
  63689. };
  63690. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  63691. return this._physicsPlugin.name;
  63692. };
  63693. /**
  63694. * Adding a new impostor for the impostor tracking.
  63695. * This will be done by the impostor itself.
  63696. * @param {PhysicsImpostor} impostor the impostor to add
  63697. */
  63698. PhysicsEngine.prototype.addImpostor = function (impostor) {
  63699. impostor.uniqueId = this._impostors.push(impostor);
  63700. //if no parent, generate the body
  63701. if (!impostor.parent) {
  63702. this._physicsPlugin.generatePhysicsBody(impostor);
  63703. }
  63704. };
  63705. /**
  63706. * Remove an impostor from the engine.
  63707. * This impostor and its mesh will not longer be updated by the physics engine.
  63708. * @param {PhysicsImpostor} impostor the impostor to remove
  63709. */
  63710. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  63711. var index = this._impostors.indexOf(impostor);
  63712. if (index > -1) {
  63713. var removed = this._impostors.splice(index, 1);
  63714. //Is it needed?
  63715. if (removed.length) {
  63716. //this will also remove it from the world.
  63717. removed[0].physicsBody = null;
  63718. }
  63719. }
  63720. };
  63721. /**
  63722. * Add a joint to the physics engine
  63723. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  63724. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  63725. * @param {PhysicsJoint} the joint that will connect both impostors.
  63726. */
  63727. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  63728. var impostorJoint = {
  63729. mainImpostor: mainImpostor,
  63730. connectedImpostor: connectedImpostor,
  63731. joint: joint
  63732. };
  63733. joint.physicsPlugin = this._physicsPlugin;
  63734. this._joints.push(impostorJoint);
  63735. this._physicsPlugin.generateJoint(impostorJoint);
  63736. };
  63737. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  63738. var matchingJoints = this._joints.filter(function (impostorJoint) {
  63739. return (impostorJoint.connectedImpostor === connectedImpostor
  63740. && impostorJoint.joint === joint
  63741. && impostorJoint.mainImpostor === mainImpostor);
  63742. });
  63743. if (matchingJoints.length) {
  63744. this._physicsPlugin.removeJoint(matchingJoints[0]);
  63745. //TODO remove it from the list as well
  63746. }
  63747. };
  63748. /**
  63749. * Called by the scene. no need to call it.
  63750. */
  63751. PhysicsEngine.prototype._step = function (delta) {
  63752. var _this = this;
  63753. //check if any mesh has no body / requires an update
  63754. this._impostors.forEach(function (impostor) {
  63755. if (impostor.isBodyInitRequired()) {
  63756. _this._physicsPlugin.generatePhysicsBody(impostor);
  63757. }
  63758. });
  63759. if (delta > 0.1) {
  63760. delta = 0.1;
  63761. }
  63762. else if (delta <= 0) {
  63763. delta = 1.0 / 60.0;
  63764. }
  63765. this._physicsPlugin.executeStep(delta, this._impostors);
  63766. };
  63767. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  63768. return this._physicsPlugin;
  63769. };
  63770. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  63771. for (var i = 0; i < this._impostors.length; ++i) {
  63772. if (this._impostors[i].object === object) {
  63773. return this._impostors[i];
  63774. }
  63775. }
  63776. };
  63777. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  63778. for (var i = 0; i < this._impostors.length; ++i) {
  63779. if (this._impostors[i].physicsBody === body) {
  63780. return this._impostors[i];
  63781. }
  63782. }
  63783. };
  63784. // Statics
  63785. PhysicsEngine.Epsilon = 0.001;
  63786. return PhysicsEngine;
  63787. }());
  63788. BABYLON.PhysicsEngine = PhysicsEngine;
  63789. })(BABYLON || (BABYLON = {}));
  63790. //# sourceMappingURL=babylon.physicsEngine.js.map
  63791. var BABYLON;
  63792. (function (BABYLON) {
  63793. var CannonJSPlugin = (function () {
  63794. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  63795. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  63796. if (iterations === void 0) { iterations = 10; }
  63797. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  63798. this.name = "CannonJSPlugin";
  63799. this._physicsMaterials = new Array();
  63800. this._fixedTimeStep = 1 / 60;
  63801. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  63802. this._currentCollisionGroup = 2;
  63803. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  63804. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  63805. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  63806. this._tmpPosition = BABYLON.Vector3.Zero();
  63807. this._tmpQuaternion = new BABYLON.Quaternion();
  63808. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  63809. this._tmpDeltaRotation = new BABYLON.Quaternion();
  63810. this._tmpUnityRotation = new BABYLON.Quaternion();
  63811. if (!this.isSupported()) {
  63812. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  63813. return;
  63814. }
  63815. this.world = new this.BJSCANNON.World();
  63816. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  63817. this.world.solver.iterations = iterations;
  63818. }
  63819. CannonJSPlugin.prototype.setGravity = function (gravity) {
  63820. this.world.gravity.copy(gravity);
  63821. };
  63822. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  63823. this._fixedTimeStep = timeStep;
  63824. };
  63825. CannonJSPlugin.prototype.getTimeStep = function () {
  63826. return this._fixedTimeStep;
  63827. };
  63828. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  63829. // Delta is in seconds, should be provided in milliseconds
  63830. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  63831. };
  63832. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  63833. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  63834. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  63835. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  63836. };
  63837. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  63838. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  63839. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  63840. impostor.physicsBody.applyForce(impulse, worldPoint);
  63841. };
  63842. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  63843. //parent-child relationship. Does this impostor has a parent impostor?
  63844. if (impostor.parent) {
  63845. if (impostor.physicsBody) {
  63846. this.removePhysicsBody(impostor);
  63847. //TODO is that needed?
  63848. impostor.forceUpdate();
  63849. }
  63850. return;
  63851. }
  63852. //should a new body be created for this impostor?
  63853. if (impostor.isBodyInitRequired()) {
  63854. var shape = this._createShape(impostor);
  63855. //unregister events, if body is being changed
  63856. var oldBody = impostor.physicsBody;
  63857. if (oldBody) {
  63858. this.removePhysicsBody(impostor);
  63859. }
  63860. //create the body and material
  63861. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  63862. var bodyCreationObject = {
  63863. mass: impostor.getParam("mass"),
  63864. material: material
  63865. };
  63866. // A simple extend, in case native options were used.
  63867. var nativeOptions = impostor.getParam("nativeOptions");
  63868. for (var key in nativeOptions) {
  63869. if (nativeOptions.hasOwnProperty(key)) {
  63870. bodyCreationObject[key] = nativeOptions[key];
  63871. }
  63872. }
  63873. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  63874. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  63875. this.world.addEventListener("preStep", impostor.beforeStep);
  63876. this.world.addEventListener("postStep", impostor.afterStep);
  63877. impostor.physicsBody.addShape(shape);
  63878. this.world.add(impostor.physicsBody);
  63879. //try to keep the body moving in the right direction by taking old properties.
  63880. //Should be tested!
  63881. if (oldBody) {
  63882. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  63883. impostor.physicsBody[param].copy(oldBody[param]);
  63884. });
  63885. }
  63886. this._processChildMeshes(impostor);
  63887. }
  63888. //now update the body's transformation
  63889. this._updatePhysicsBodyTransformation(impostor);
  63890. };
  63891. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  63892. var _this = this;
  63893. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  63894. var currentRotation = mainImpostor.object.rotationQuaternion;
  63895. if (meshChildren.length) {
  63896. var processMesh = function (localPosition, mesh) {
  63897. var childImpostor = mesh.getPhysicsImpostor();
  63898. if (childImpostor) {
  63899. var parent = childImpostor.parent;
  63900. if (parent !== mainImpostor) {
  63901. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  63902. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  63903. if (childImpostor.physicsBody) {
  63904. _this.removePhysicsBody(childImpostor);
  63905. childImpostor.physicsBody = null;
  63906. }
  63907. childImpostor.parent = mainImpostor;
  63908. childImpostor.resetUpdateFlags();
  63909. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new _this.BJSCANNON.Vec3(pPosition.x, pPosition.y, pPosition.z), new _this.BJSCANNON.Quaternion(localRotation.x, localRotation.y, localRotation.z, localRotation.w));
  63910. //Add the mass of the children.
  63911. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  63912. }
  63913. }
  63914. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  63915. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  63916. };
  63917. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  63918. }
  63919. };
  63920. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  63921. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  63922. this.world.removeEventListener("preStep", impostor.beforeStep);
  63923. this.world.removeEventListener("postStep", impostor.afterStep);
  63924. this.world.remove(impostor.physicsBody);
  63925. };
  63926. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  63927. var mainBody = impostorJoint.mainImpostor.physicsBody;
  63928. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  63929. if (!mainBody || !connectedBody) {
  63930. return;
  63931. }
  63932. var constraint;
  63933. var jointData = impostorJoint.joint.jointData;
  63934. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  63935. var constraintData = {
  63936. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  63937. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  63938. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  63939. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  63940. maxForce: jointData.nativeParams.maxForce,
  63941. collideConnected: !!jointData.collision
  63942. };
  63943. switch (impostorJoint.joint.type) {
  63944. case BABYLON.PhysicsJoint.HingeJoint:
  63945. case BABYLON.PhysicsJoint.Hinge2Joint:
  63946. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  63947. break;
  63948. case BABYLON.PhysicsJoint.DistanceJoint:
  63949. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  63950. break;
  63951. case BABYLON.PhysicsJoint.SpringJoint:
  63952. var springData = jointData;
  63953. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  63954. restLength: springData.length,
  63955. stiffness: springData.stiffness,
  63956. damping: springData.damping,
  63957. localAnchorA: constraintData.pivotA,
  63958. localAnchorB: constraintData.pivotB
  63959. });
  63960. break;
  63961. case BABYLON.PhysicsJoint.LockJoint:
  63962. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  63963. break;
  63964. case BABYLON.PhysicsJoint.PointToPointJoint:
  63965. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  63966. default:
  63967. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  63968. break;
  63969. }
  63970. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  63971. constraint.collideConnected = !!jointData.collision;
  63972. impostorJoint.joint.physicsJoint = constraint;
  63973. //don't add spring as constraint, as it is not one.
  63974. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  63975. this.world.addConstraint(constraint);
  63976. }
  63977. else {
  63978. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  63979. constraint.applyForce();
  63980. });
  63981. }
  63982. };
  63983. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  63984. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  63985. };
  63986. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  63987. var index;
  63988. var mat;
  63989. for (index = 0; index < this._physicsMaterials.length; index++) {
  63990. mat = this._physicsMaterials[index];
  63991. if (mat.friction === friction && mat.restitution === restitution) {
  63992. return mat;
  63993. }
  63994. }
  63995. var currentMat = new this.BJSCANNON.Material(name);
  63996. currentMat.friction = friction;
  63997. currentMat.restitution = restitution;
  63998. this._physicsMaterials.push(currentMat);
  63999. return currentMat;
  64000. };
  64001. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  64002. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  64003. };
  64004. CannonJSPlugin.prototype._createShape = function (impostor) {
  64005. var object = impostor.object;
  64006. var returnValue;
  64007. var extendSize = impostor.getObjectExtendSize();
  64008. switch (impostor.type) {
  64009. case BABYLON.PhysicsImpostor.SphereImpostor:
  64010. var radiusX = extendSize.x;
  64011. var radiusY = extendSize.y;
  64012. var radiusZ = extendSize.z;
  64013. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  64014. break;
  64015. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  64016. case BABYLON.PhysicsImpostor.CylinderImpostor:
  64017. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  64018. break;
  64019. case BABYLON.PhysicsImpostor.BoxImpostor:
  64020. var box = extendSize.scale(0.5);
  64021. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  64022. break;
  64023. case BABYLON.PhysicsImpostor.PlaneImpostor:
  64024. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  64025. returnValue = new this.BJSCANNON.Plane();
  64026. break;
  64027. case BABYLON.PhysicsImpostor.MeshImpostor:
  64028. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  64029. var rawFaces = object.getIndices ? object.getIndices() : [];
  64030. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  64031. returnValue = new this.BJSCANNON.Trimesh(rawVerts, rawFaces);
  64032. break;
  64033. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  64034. returnValue = this._createHeightmap(object);
  64035. break;
  64036. case BABYLON.PhysicsImpostor.ParticleImpostor:
  64037. returnValue = new this.BJSCANNON.Particle();
  64038. break;
  64039. }
  64040. return returnValue;
  64041. };
  64042. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  64043. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64044. var matrix = new Array();
  64045. //For now pointDepth will not be used and will be automatically calculated.
  64046. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  64047. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  64048. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSizeWorld.x, object.getBoundingInfo().boundingBox.extendSizeWorld.z);
  64049. var elementSize = dim * 2 / arraySize;
  64050. var minY = object.getBoundingInfo().boundingBox.extendSizeWorld.y;
  64051. for (var i = 0; i < pos.length; i = i + 3) {
  64052. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  64053. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  64054. var y = pos[i + 1] + minY;
  64055. if (!matrix[x]) {
  64056. matrix[x] = [];
  64057. }
  64058. if (!matrix[x][z]) {
  64059. matrix[x][z] = y;
  64060. }
  64061. matrix[x][z] = Math.max(y, matrix[x][z]);
  64062. }
  64063. for (var x = 0; x <= arraySize; ++x) {
  64064. if (!matrix[x]) {
  64065. var loc = 1;
  64066. while (!matrix[(x + loc) % arraySize]) {
  64067. loc++;
  64068. }
  64069. matrix[x] = matrix[(x + loc) % arraySize].slice();
  64070. //console.log("missing x", x);
  64071. }
  64072. for (var z = 0; z <= arraySize; ++z) {
  64073. if (!matrix[x][z]) {
  64074. var loc = 1;
  64075. var newValue;
  64076. while (newValue === undefined) {
  64077. newValue = matrix[x][(z + loc++) % arraySize];
  64078. }
  64079. matrix[x][z] = newValue;
  64080. }
  64081. }
  64082. }
  64083. var shape = new this.BJSCANNON.Heightfield(matrix, {
  64084. elementSize: elementSize
  64085. });
  64086. //For future reference, needed for body transformation
  64087. shape.minY = minY;
  64088. return shape;
  64089. };
  64090. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  64091. var object = impostor.object;
  64092. //make sure it is updated...
  64093. object.computeWorldMatrix && object.computeWorldMatrix(true);
  64094. // The delta between the mesh position and the mesh bounding box center
  64095. var center = impostor.getObjectCenter();
  64096. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  64097. this._tmpPosition.copyFrom(center);
  64098. var quaternion = object.rotationQuaternion;
  64099. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  64100. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  64101. //-90 DEG in X, precalculated
  64102. quaternion = quaternion.multiply(this._minus90X);
  64103. //Invert! (Precalculated, 90 deg in X)
  64104. //No need to clone. this will never change.
  64105. impostor.setDeltaRotation(this._plus90X);
  64106. }
  64107. //If it is a heightfield, if should be centered.
  64108. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  64109. var mesh = object;
  64110. //calculate the correct body position:
  64111. var rotationQuaternion = mesh.rotationQuaternion;
  64112. mesh.rotationQuaternion = this._tmpUnityRotation;
  64113. mesh.computeWorldMatrix(true);
  64114. //get original center with no rotation
  64115. var c = center.clone();
  64116. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  64117. //rotation is back
  64118. mesh.rotationQuaternion = rotationQuaternion;
  64119. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  64120. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSizeWorld.x, 0, -mesh.getBoundingInfo().boundingBox.extendSizeWorld.z);
  64121. mesh.setPivotMatrix(p);
  64122. mesh.computeWorldMatrix(true);
  64123. //calculate the translation
  64124. var translation = mesh.getBoundingInfo().boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  64125. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSizeWorld.y, translation.z);
  64126. //add it inverted to the delta
  64127. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.centerWorld.subtract(c));
  64128. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSizeWorld.y;
  64129. mesh.setPivotMatrix(oldPivot);
  64130. mesh.computeWorldMatrix(true);
  64131. }
  64132. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  64133. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  64134. this._tmpPosition.copyFrom(object.position);
  64135. }
  64136. impostor.setDeltaPosition(this._tmpDeltaPosition);
  64137. //Now update the impostor object
  64138. impostor.physicsBody.position.copy(this._tmpPosition);
  64139. impostor.physicsBody.quaternion.copy(quaternion);
  64140. };
  64141. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  64142. impostor.object.position.copyFrom(impostor.physicsBody.position);
  64143. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  64144. };
  64145. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  64146. impostor.physicsBody.position.copy(newPosition);
  64147. impostor.physicsBody.quaternion.copy(newRotation);
  64148. };
  64149. CannonJSPlugin.prototype.isSupported = function () {
  64150. return this.BJSCANNON !== undefined;
  64151. };
  64152. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  64153. impostor.physicsBody.velocity.copy(velocity);
  64154. };
  64155. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  64156. impostor.physicsBody.angularVelocity.copy(velocity);
  64157. };
  64158. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  64159. var v = impostor.physicsBody.velocity;
  64160. if (!v)
  64161. return null;
  64162. return new BABYLON.Vector3(v.x, v.y, v.z);
  64163. };
  64164. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  64165. var v = impostor.physicsBody.angularVelocity;
  64166. if (!v)
  64167. return null;
  64168. return new BABYLON.Vector3(v.x, v.y, v.z);
  64169. };
  64170. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  64171. impostor.physicsBody.mass = mass;
  64172. impostor.physicsBody.updateMassProperties();
  64173. };
  64174. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  64175. return impostor.physicsBody.mass;
  64176. };
  64177. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  64178. return impostor.physicsBody.material.friction;
  64179. };
  64180. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  64181. impostor.physicsBody.material.friction = friction;
  64182. };
  64183. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  64184. return impostor.physicsBody.material.restitution;
  64185. };
  64186. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  64187. impostor.physicsBody.material.restitution = restitution;
  64188. };
  64189. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  64190. impostor.physicsBody.sleep();
  64191. };
  64192. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  64193. impostor.physicsBody.wakeUp();
  64194. };
  64195. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  64196. joint.physicsJoint.distance = maxDistance;
  64197. };
  64198. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  64199. if (!motorIndex) {
  64200. joint.physicsJoint.enableMotor();
  64201. }
  64202. };
  64203. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  64204. if (!motorIndex) {
  64205. joint.physicsJoint.disableMotor();
  64206. }
  64207. };
  64208. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  64209. if (!motorIndex) {
  64210. joint.physicsJoint.enableMotor();
  64211. joint.physicsJoint.setMotorSpeed(speed);
  64212. if (maxForce) {
  64213. this.setLimit(joint, maxForce);
  64214. }
  64215. }
  64216. };
  64217. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  64218. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  64219. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  64220. };
  64221. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  64222. var body = impostor.physicsBody;
  64223. mesh.position.x = body.position.x;
  64224. mesh.position.y = body.position.y;
  64225. mesh.position.z = body.position.z;
  64226. mesh.rotationQuaternion.x = body.quaternion.x;
  64227. mesh.rotationQuaternion.y = body.quaternion.y;
  64228. mesh.rotationQuaternion.z = body.quaternion.z;
  64229. mesh.rotationQuaternion.w = body.quaternion.w;
  64230. };
  64231. CannonJSPlugin.prototype.getRadius = function (impostor) {
  64232. var shape = impostor.physicsBody.shapes[0];
  64233. return shape.boundingSphereRadius;
  64234. };
  64235. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  64236. var shape = impostor.physicsBody.shapes[0];
  64237. result.x = shape.halfExtents.x * 2;
  64238. result.y = shape.halfExtents.y * 2;
  64239. result.z = shape.halfExtents.z * 2;
  64240. };
  64241. CannonJSPlugin.prototype.dispose = function () {
  64242. };
  64243. return CannonJSPlugin;
  64244. }());
  64245. BABYLON.CannonJSPlugin = CannonJSPlugin;
  64246. })(BABYLON || (BABYLON = {}));
  64247. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  64248. var BABYLON;
  64249. (function (BABYLON) {
  64250. var OimoJSPlugin = (function () {
  64251. function OimoJSPlugin(iterations) {
  64252. this.name = "OimoJSPlugin";
  64253. this._tmpImpostorsArray = [];
  64254. this._tmpPositionVector = BABYLON.Vector3.Zero();
  64255. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  64256. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  64257. this.world.worldscale(1);
  64258. this.world.clear();
  64259. //making sure no stats are calculated
  64260. this.world.isNoStat = true;
  64261. }
  64262. OimoJSPlugin.prototype.setGravity = function (gravity) {
  64263. this.world.gravity.copy(gravity);
  64264. };
  64265. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  64266. this.world.timeStep = timeStep;
  64267. };
  64268. OimoJSPlugin.prototype.getTimeStep = function () {
  64269. return this.world.timeStep;
  64270. };
  64271. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  64272. var _this = this;
  64273. impostors.forEach(function (impostor) {
  64274. impostor.beforeStep();
  64275. });
  64276. this.world.step();
  64277. impostors.forEach(function (impostor) {
  64278. impostor.afterStep();
  64279. //update the ordered impostors array
  64280. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  64281. });
  64282. //check for collisions
  64283. var contact = this.world.contacts;
  64284. while (contact !== null) {
  64285. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  64286. contact = contact.next;
  64287. continue;
  64288. }
  64289. //is this body colliding with any other? get the impostor
  64290. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  64291. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  64292. if (!mainImpostor || !collidingImpostor) {
  64293. contact = contact.next;
  64294. continue;
  64295. }
  64296. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  64297. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  64298. contact = contact.next;
  64299. }
  64300. };
  64301. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  64302. var mass = impostor.physicsBody.massInfo.mass;
  64303. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  64304. };
  64305. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  64306. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  64307. this.applyImpulse(impostor, force, contactPoint);
  64308. };
  64309. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  64310. var _this = this;
  64311. //parent-child relationship. Does this impostor has a parent impostor?
  64312. if (impostor.parent) {
  64313. if (impostor.physicsBody) {
  64314. this.removePhysicsBody(impostor);
  64315. //TODO is that needed?
  64316. impostor.forceUpdate();
  64317. }
  64318. return;
  64319. }
  64320. if (impostor.isBodyInitRequired()) {
  64321. var bodyConfig = {
  64322. name: impostor.uniqueId,
  64323. //Oimo must have mass, also for static objects.
  64324. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  64325. size: [],
  64326. type: [],
  64327. pos: [],
  64328. rot: [],
  64329. move: impostor.getParam("mass") !== 0,
  64330. //Supporting older versions of Oimo
  64331. world: this.world
  64332. };
  64333. var impostors = [impostor];
  64334. var addToArray = function (parent) {
  64335. if (!parent.getChildMeshes)
  64336. return;
  64337. parent.getChildMeshes().forEach(function (m) {
  64338. if (m.physicsImpostor) {
  64339. impostors.push(m.physicsImpostor);
  64340. //m.physicsImpostor._init();
  64341. }
  64342. });
  64343. };
  64344. addToArray(impostor.object);
  64345. var checkWithEpsilon_1 = function (value) {
  64346. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  64347. };
  64348. impostors.forEach(function (i) {
  64349. //get the correct bounding box
  64350. var oldQuaternion = i.object.rotationQuaternion;
  64351. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  64352. x: impostor.object.rotationQuaternion.x,
  64353. y: impostor.object.rotationQuaternion.y,
  64354. z: impostor.object.rotationQuaternion.z,
  64355. s: impostor.object.rotationQuaternion.w
  64356. });
  64357. var extendSize = i.getObjectExtendSize();
  64358. if (i === impostor) {
  64359. var center = impostor.getObjectCenter();
  64360. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  64361. //Can also use Array.prototype.push.apply
  64362. bodyConfig.pos.push(center.x);
  64363. bodyConfig.pos.push(center.y);
  64364. bodyConfig.pos.push(center.z);
  64365. //tmp solution
  64366. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  64367. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  64368. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  64369. }
  64370. else {
  64371. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  64372. bodyConfig.pos.push(localPosition.x);
  64373. bodyConfig.pos.push(localPosition.y);
  64374. bodyConfig.pos.push(localPosition.z);
  64375. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  64376. bodyConfig.rot.push(0);
  64377. bodyConfig.rot.push(0);
  64378. bodyConfig.rot.push(0);
  64379. }
  64380. // register mesh
  64381. switch (i.type) {
  64382. case BABYLON.PhysicsImpostor.ParticleImpostor:
  64383. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  64384. case BABYLON.PhysicsImpostor.SphereImpostor:
  64385. var radiusX = extendSize.x;
  64386. var radiusY = extendSize.y;
  64387. var radiusZ = extendSize.z;
  64388. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  64389. bodyConfig.type.push('sphere');
  64390. //due to the way oimo works with compounds, add 3 times
  64391. bodyConfig.size.push(size);
  64392. bodyConfig.size.push(size);
  64393. bodyConfig.size.push(size);
  64394. break;
  64395. case BABYLON.PhysicsImpostor.CylinderImpostor:
  64396. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  64397. var sizeY = checkWithEpsilon_1(extendSize.y);
  64398. bodyConfig.type.push('cylinder');
  64399. bodyConfig.size.push(sizeX);
  64400. bodyConfig.size.push(sizeY);
  64401. //due to the way oimo works with compounds, add one more value.
  64402. bodyConfig.size.push(sizeY);
  64403. break;
  64404. case BABYLON.PhysicsImpostor.PlaneImpostor:
  64405. case BABYLON.PhysicsImpostor.BoxImpostor:
  64406. default:
  64407. var sizeX = checkWithEpsilon_1(extendSize.x);
  64408. var sizeY = checkWithEpsilon_1(extendSize.y);
  64409. var sizeZ = checkWithEpsilon_1(extendSize.z);
  64410. bodyConfig.type.push('box');
  64411. bodyConfig.size.push(sizeX);
  64412. bodyConfig.size.push(sizeY);
  64413. bodyConfig.size.push(sizeZ);
  64414. break;
  64415. }
  64416. //actually not needed, but hey...
  64417. i.object.rotationQuaternion = oldQuaternion;
  64418. });
  64419. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  64420. }
  64421. else {
  64422. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  64423. }
  64424. impostor.setDeltaPosition(this._tmpPositionVector);
  64425. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  64426. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  64427. };
  64428. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  64429. //impostor.physicsBody.dispose();
  64430. //Same as : (older oimo versions)
  64431. this.world.removeRigidBody(impostor.physicsBody);
  64432. };
  64433. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  64434. var mainBody = impostorJoint.mainImpostor.physicsBody;
  64435. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  64436. if (!mainBody || !connectedBody) {
  64437. return;
  64438. }
  64439. var jointData = impostorJoint.joint.jointData;
  64440. var options = jointData.nativeParams || {};
  64441. var type;
  64442. var nativeJointData = {
  64443. body1: mainBody,
  64444. body2: connectedBody,
  64445. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  64446. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  64447. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  64448. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  64449. min: options.min,
  64450. max: options.max,
  64451. collision: options.collision || jointData.collision,
  64452. spring: options.spring,
  64453. //supporting older version of Oimo
  64454. world: this.world
  64455. };
  64456. switch (impostorJoint.joint.type) {
  64457. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  64458. type = "jointBall";
  64459. break;
  64460. case BABYLON.PhysicsJoint.SpringJoint:
  64461. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  64462. var springData = jointData;
  64463. nativeJointData.min = springData.length || nativeJointData.min;
  64464. //Max should also be set, just make sure it is at least min
  64465. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  64466. case BABYLON.PhysicsJoint.DistanceJoint:
  64467. type = "jointDistance";
  64468. nativeJointData.max = jointData.maxDistance;
  64469. break;
  64470. case BABYLON.PhysicsJoint.PrismaticJoint:
  64471. type = "jointPrisme";
  64472. break;
  64473. case BABYLON.PhysicsJoint.SliderJoint:
  64474. type = "jointSlide";
  64475. break;
  64476. case BABYLON.PhysicsJoint.WheelJoint:
  64477. type = "jointWheel";
  64478. break;
  64479. case BABYLON.PhysicsJoint.HingeJoint:
  64480. default:
  64481. type = "jointHinge";
  64482. break;
  64483. }
  64484. nativeJointData.type = type;
  64485. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  64486. };
  64487. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  64488. //Bug in Oimo prevents us from disposing a joint in the playground
  64489. //joint.joint.physicsJoint.dispose();
  64490. //So we will bruteforce it!
  64491. try {
  64492. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  64493. }
  64494. catch (e) {
  64495. BABYLON.Tools.Warn(e);
  64496. }
  64497. };
  64498. OimoJSPlugin.prototype.isSupported = function () {
  64499. return this.BJSOIMO !== undefined;
  64500. };
  64501. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  64502. if (!impostor.physicsBody.sleeping) {
  64503. //TODO check that
  64504. if (impostor.physicsBody.shapes.next) {
  64505. var parentShape = this._getLastShape(impostor.physicsBody);
  64506. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  64507. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  64508. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  64509. }
  64510. else {
  64511. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  64512. }
  64513. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  64514. impostor.object.rotationQuaternion.normalize();
  64515. }
  64516. };
  64517. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  64518. var body = impostor.physicsBody;
  64519. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  64520. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  64521. body.syncShapes();
  64522. body.awake();
  64523. };
  64524. OimoJSPlugin.prototype._getLastShape = function (body) {
  64525. var lastShape = body.shapes;
  64526. while (lastShape.next) {
  64527. lastShape = lastShape.next;
  64528. }
  64529. return lastShape;
  64530. };
  64531. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  64532. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  64533. };
  64534. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  64535. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  64536. };
  64537. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  64538. var v = impostor.physicsBody.linearVelocity;
  64539. if (!v)
  64540. return null;
  64541. return new BABYLON.Vector3(v.x, v.y, v.z);
  64542. };
  64543. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  64544. var v = impostor.physicsBody.angularVelocity;
  64545. if (!v)
  64546. return null;
  64547. return new BABYLON.Vector3(v.x, v.y, v.z);
  64548. };
  64549. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  64550. var staticBody = mass === 0;
  64551. //this will actually set the body's density and not its mass.
  64552. //But this is how oimo treats the mass variable.
  64553. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  64554. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  64555. };
  64556. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  64557. return impostor.physicsBody.shapes.density;
  64558. };
  64559. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  64560. return impostor.physicsBody.shapes.friction;
  64561. };
  64562. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  64563. impostor.physicsBody.shapes.friction = friction;
  64564. };
  64565. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  64566. return impostor.physicsBody.shapes.restitution;
  64567. };
  64568. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  64569. impostor.physicsBody.shapes.restitution = restitution;
  64570. };
  64571. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  64572. impostor.physicsBody.sleep();
  64573. };
  64574. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  64575. impostor.physicsBody.awake();
  64576. };
  64577. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  64578. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  64579. if (minDistance !== void 0) {
  64580. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  64581. }
  64582. };
  64583. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  64584. //TODO separate rotational and transational motors.
  64585. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  64586. if (motor) {
  64587. motor.setMotor(speed, maxForce);
  64588. }
  64589. };
  64590. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  64591. //TODO separate rotational and transational motors.
  64592. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  64593. if (motor) {
  64594. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  64595. }
  64596. };
  64597. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  64598. var body = impostor.physicsBody;
  64599. mesh.position.x = body.position.x;
  64600. mesh.position.y = body.position.y;
  64601. mesh.position.z = body.position.z;
  64602. mesh.rotationQuaternion.x = body.orientation.x;
  64603. mesh.rotationQuaternion.y = body.orientation.y;
  64604. mesh.rotationQuaternion.z = body.orientation.z;
  64605. mesh.rotationQuaternion.w = body.orientation.s;
  64606. };
  64607. OimoJSPlugin.prototype.getRadius = function (impostor) {
  64608. return impostor.physicsBody.shapes.radius;
  64609. };
  64610. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  64611. var shape = impostor.physicsBody.shapes;
  64612. result.x = shape.halfWidth * 2;
  64613. result.y = shape.halfHeight * 2;
  64614. result.z = shape.halfDepth * 2;
  64615. };
  64616. OimoJSPlugin.prototype.dispose = function () {
  64617. this.world.clear();
  64618. };
  64619. return OimoJSPlugin;
  64620. }());
  64621. BABYLON.OimoJSPlugin = OimoJSPlugin;
  64622. })(BABYLON || (BABYLON = {}));
  64623. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  64624. var BABYLON;
  64625. (function (BABYLON) {
  64626. var Internals;
  64627. (function (Internals) {
  64628. /*
  64629. * Based on jsTGALoader - Javascript loader for TGA file
  64630. * By Vincent Thibault
  64631. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  64632. */
  64633. var TGATools = (function () {
  64634. function TGATools() {
  64635. }
  64636. TGATools.GetTGAHeader = function (data) {
  64637. var offset = 0;
  64638. var header = {
  64639. id_length: data[offset++],
  64640. colormap_type: data[offset++],
  64641. image_type: data[offset++],
  64642. colormap_index: data[offset++] | data[offset++] << 8,
  64643. colormap_length: data[offset++] | data[offset++] << 8,
  64644. colormap_size: data[offset++],
  64645. origin: [
  64646. data[offset++] | data[offset++] << 8,
  64647. data[offset++] | data[offset++] << 8
  64648. ],
  64649. width: data[offset++] | data[offset++] << 8,
  64650. height: data[offset++] | data[offset++] << 8,
  64651. pixel_size: data[offset++],
  64652. flags: data[offset++]
  64653. };
  64654. return header;
  64655. };
  64656. TGATools.UploadContent = function (gl, data) {
  64657. // Not enough data to contain header ?
  64658. if (data.length < 19) {
  64659. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  64660. return;
  64661. }
  64662. // Read Header
  64663. var offset = 18;
  64664. var header = TGATools.GetTGAHeader(data);
  64665. // Assume it's a valid Targa file.
  64666. if (header.id_length + offset > data.length) {
  64667. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  64668. return;
  64669. }
  64670. // Skip not needed data
  64671. offset += header.id_length;
  64672. var use_rle = false;
  64673. var use_pal = false;
  64674. var use_rgb = false;
  64675. var use_grey = false;
  64676. // Get some informations.
  64677. switch (header.image_type) {
  64678. case TGATools._TYPE_RLE_INDEXED:
  64679. use_rle = true;
  64680. case TGATools._TYPE_INDEXED:
  64681. use_pal = true;
  64682. break;
  64683. case TGATools._TYPE_RLE_RGB:
  64684. use_rle = true;
  64685. case TGATools._TYPE_RGB:
  64686. use_rgb = true;
  64687. break;
  64688. case TGATools._TYPE_RLE_GREY:
  64689. use_rle = true;
  64690. case TGATools._TYPE_GREY:
  64691. use_grey = true;
  64692. break;
  64693. }
  64694. var pixel_data;
  64695. var numAlphaBits = header.flags & 0xf;
  64696. var pixel_size = header.pixel_size >> 3;
  64697. var pixel_total = header.width * header.height * pixel_size;
  64698. // Read palettes
  64699. var palettes;
  64700. if (use_pal) {
  64701. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  64702. }
  64703. // Read LRE
  64704. if (use_rle) {
  64705. pixel_data = new Uint8Array(pixel_total);
  64706. var c, count, i;
  64707. var localOffset = 0;
  64708. var pixels = new Uint8Array(pixel_size);
  64709. while (offset < pixel_total && localOffset < pixel_total) {
  64710. c = data[offset++];
  64711. count = (c & 0x7f) + 1;
  64712. // RLE pixels
  64713. if (c & 0x80) {
  64714. // Bind pixel tmp array
  64715. for (i = 0; i < pixel_size; ++i) {
  64716. pixels[i] = data[offset++];
  64717. }
  64718. // Copy pixel array
  64719. for (i = 0; i < count; ++i) {
  64720. pixel_data.set(pixels, localOffset + i * pixel_size);
  64721. }
  64722. localOffset += pixel_size * count;
  64723. }
  64724. else {
  64725. count *= pixel_size;
  64726. for (i = 0; i < count; ++i) {
  64727. pixel_data[localOffset + i] = data[offset++];
  64728. }
  64729. localOffset += count;
  64730. }
  64731. }
  64732. }
  64733. else {
  64734. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  64735. }
  64736. // Load to texture
  64737. var x_start, y_start, x_step, y_step, y_end, x_end;
  64738. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  64739. default:
  64740. case TGATools._ORIGIN_UL:
  64741. x_start = 0;
  64742. x_step = 1;
  64743. x_end = header.width;
  64744. y_start = 0;
  64745. y_step = 1;
  64746. y_end = header.height;
  64747. break;
  64748. case TGATools._ORIGIN_BL:
  64749. x_start = 0;
  64750. x_step = 1;
  64751. x_end = header.width;
  64752. y_start = header.height - 1;
  64753. y_step = -1;
  64754. y_end = -1;
  64755. break;
  64756. case TGATools._ORIGIN_UR:
  64757. x_start = header.width - 1;
  64758. x_step = -1;
  64759. x_end = -1;
  64760. y_start = 0;
  64761. y_step = 1;
  64762. y_end = header.height;
  64763. break;
  64764. case TGATools._ORIGIN_BR:
  64765. x_start = header.width - 1;
  64766. x_step = -1;
  64767. x_end = -1;
  64768. y_start = header.height - 1;
  64769. y_step = -1;
  64770. y_end = -1;
  64771. break;
  64772. }
  64773. // Load the specify method
  64774. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  64775. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  64776. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  64777. };
  64778. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  64779. var image = pixel_data, colormap = palettes;
  64780. var width = header.width, height = header.height;
  64781. var color, i = 0, x, y;
  64782. var imageData = new Uint8Array(width * height * 4);
  64783. for (y = y_start; y !== y_end; y += y_step) {
  64784. for (x = x_start; x !== x_end; x += x_step, i++) {
  64785. color = image[i];
  64786. imageData[(x + width * y) * 4 + 3] = 255;
  64787. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  64788. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  64789. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  64790. }
  64791. }
  64792. return imageData;
  64793. };
  64794. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  64795. var image = pixel_data;
  64796. var width = header.width, height = header.height;
  64797. var color, i = 0, x, y;
  64798. var imageData = new Uint8Array(width * height * 4);
  64799. for (y = y_start; y !== y_end; y += y_step) {
  64800. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  64801. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  64802. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  64803. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  64804. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  64805. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  64806. }
  64807. }
  64808. return imageData;
  64809. };
  64810. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  64811. var image = pixel_data;
  64812. var width = header.width, height = header.height;
  64813. var i = 0, x, y;
  64814. var imageData = new Uint8Array(width * height * 4);
  64815. for (y = y_start; y !== y_end; y += y_step) {
  64816. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  64817. imageData[(x + width * y) * 4 + 3] = 255;
  64818. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  64819. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  64820. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  64821. }
  64822. }
  64823. return imageData;
  64824. };
  64825. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  64826. var image = pixel_data;
  64827. var width = header.width, height = header.height;
  64828. var i = 0, x, y;
  64829. var imageData = new Uint8Array(width * height * 4);
  64830. for (y = y_start; y !== y_end; y += y_step) {
  64831. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  64832. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  64833. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  64834. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  64835. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  64836. }
  64837. }
  64838. return imageData;
  64839. };
  64840. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  64841. var image = pixel_data;
  64842. var width = header.width, height = header.height;
  64843. var color, i = 0, x, y;
  64844. var imageData = new Uint8Array(width * height * 4);
  64845. for (y = y_start; y !== y_end; y += y_step) {
  64846. for (x = x_start; x !== x_end; x += x_step, i++) {
  64847. color = image[i];
  64848. imageData[(x + width * y) * 4 + 0] = color;
  64849. imageData[(x + width * y) * 4 + 1] = color;
  64850. imageData[(x + width * y) * 4 + 2] = color;
  64851. imageData[(x + width * y) * 4 + 3] = 255;
  64852. }
  64853. }
  64854. return imageData;
  64855. };
  64856. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  64857. var image = pixel_data;
  64858. var width = header.width, height = header.height;
  64859. var i = 0, x, y;
  64860. var imageData = new Uint8Array(width * height * 4);
  64861. for (y = y_start; y !== y_end; y += y_step) {
  64862. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  64863. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  64864. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  64865. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  64866. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  64867. }
  64868. }
  64869. return imageData;
  64870. };
  64871. TGATools._TYPE_NO_DATA = 0;
  64872. TGATools._TYPE_INDEXED = 1;
  64873. TGATools._TYPE_RGB = 2;
  64874. TGATools._TYPE_GREY = 3;
  64875. TGATools._TYPE_RLE_INDEXED = 9;
  64876. TGATools._TYPE_RLE_RGB = 10;
  64877. TGATools._TYPE_RLE_GREY = 11;
  64878. TGATools._ORIGIN_MASK = 0x30;
  64879. TGATools._ORIGIN_SHIFT = 0x04;
  64880. TGATools._ORIGIN_BL = 0x00;
  64881. TGATools._ORIGIN_BR = 0x01;
  64882. TGATools._ORIGIN_UL = 0x02;
  64883. TGATools._ORIGIN_UR = 0x03;
  64884. return TGATools;
  64885. }());
  64886. Internals.TGATools = TGATools;
  64887. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  64888. })(BABYLON || (BABYLON = {}));
  64889. //# sourceMappingURL=babylon.tga.js.map
  64890. var BABYLON;
  64891. (function (BABYLON) {
  64892. var Internals;
  64893. (function (Internals) {
  64894. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  64895. // All values and structures referenced from:
  64896. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  64897. var DDS_MAGIC = 0x20534444;
  64898. 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;
  64899. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  64900. 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;
  64901. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  64902. function FourCCToInt32(value) {
  64903. return value.charCodeAt(0) +
  64904. (value.charCodeAt(1) << 8) +
  64905. (value.charCodeAt(2) << 16) +
  64906. (value.charCodeAt(3) << 24);
  64907. }
  64908. function Int32ToFourCC(value) {
  64909. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  64910. }
  64911. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  64912. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  64913. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  64914. var FOURCC_DX10 = FourCCToInt32("DX10");
  64915. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  64916. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  64917. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  64918. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  64919. var headerLengthInt = 31; // The header length in 32 bit ints
  64920. // Offsets into the header array
  64921. var off_magic = 0;
  64922. var off_size = 1;
  64923. var off_flags = 2;
  64924. var off_height = 3;
  64925. var off_width = 4;
  64926. var off_mipmapCount = 7;
  64927. var off_pfFlags = 20;
  64928. var off_pfFourCC = 21;
  64929. var off_RGBbpp = 22;
  64930. var off_RMask = 23;
  64931. var off_GMask = 24;
  64932. var off_BMask = 25;
  64933. var off_AMask = 26;
  64934. var off_caps1 = 27;
  64935. var off_caps2 = 28;
  64936. var off_caps3 = 29;
  64937. var off_caps4 = 30;
  64938. var off_dxgiFormat = 32;
  64939. ;
  64940. var DDSTools = (function () {
  64941. function DDSTools() {
  64942. }
  64943. DDSTools.GetDDSInfo = function (arrayBuffer) {
  64944. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  64945. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  64946. var mipmapCount = 1;
  64947. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  64948. mipmapCount = Math.max(1, header[off_mipmapCount]);
  64949. }
  64950. var fourCC = header[off_pfFourCC];
  64951. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  64952. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64953. switch (fourCC) {
  64954. case FOURCC_D3DFMT_R16G16B16A16F:
  64955. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64956. break;
  64957. case FOURCC_D3DFMT_R32G32B32A32F:
  64958. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64959. break;
  64960. case FOURCC_DX10:
  64961. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  64962. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64963. break;
  64964. }
  64965. }
  64966. return {
  64967. width: header[off_width],
  64968. height: header[off_height],
  64969. mipmapCount: mipmapCount,
  64970. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  64971. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  64972. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  64973. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  64974. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  64975. dxgiFormat: dxgiFormat,
  64976. textureType: textureType
  64977. };
  64978. };
  64979. DDSTools._ToHalfFloat = function (value) {
  64980. if (!DDSTools._FloatView) {
  64981. DDSTools._FloatView = new Float32Array(1);
  64982. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  64983. }
  64984. DDSTools._FloatView[0] = value;
  64985. var x = DDSTools._Int32View[0];
  64986. var bits = (x >> 16) & 0x8000; /* Get the sign */
  64987. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  64988. var e = (x >> 23) & 0xff; /* Using int is faster here */
  64989. /* If zero, or denormal, or exponent underflows too much for a denormal
  64990. * half, return signed zero. */
  64991. if (e < 103) {
  64992. return bits;
  64993. }
  64994. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  64995. if (e > 142) {
  64996. bits |= 0x7c00;
  64997. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  64998. * not Inf, so make sure we set one mantissa bit too. */
  64999. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  65000. return bits;
  65001. }
  65002. /* If exponent underflows but not too much, return a denormal */
  65003. if (e < 113) {
  65004. m |= 0x0800;
  65005. /* Extra rounding may overflow and set mantissa to 0 and exponent
  65006. * to 1, which is OK. */
  65007. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  65008. return bits;
  65009. }
  65010. bits |= ((e - 112) << 10) | (m >> 1);
  65011. bits += m & 1;
  65012. return bits;
  65013. };
  65014. DDSTools._FromHalfFloat = function (value) {
  65015. var s = (value & 0x8000) >> 15;
  65016. var e = (value & 0x7C00) >> 10;
  65017. var f = value & 0x03FF;
  65018. if (e === 0) {
  65019. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  65020. }
  65021. else if (e == 0x1F) {
  65022. return f ? NaN : ((s ? -1 : 1) * Infinity);
  65023. }
  65024. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  65025. };
  65026. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  65027. var destArray = new Float32Array(dataLength);
  65028. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  65029. var index = 0;
  65030. for (var y = 0; y < height; y++) {
  65031. for (var x = 0; x < width; x++) {
  65032. var srcPos = (x + y * width) * 4;
  65033. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  65034. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  65035. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  65036. if (DDSTools.StoreLODInAlphaChannel) {
  65037. destArray[index + 3] = lod;
  65038. }
  65039. else {
  65040. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  65041. }
  65042. index += 4;
  65043. }
  65044. }
  65045. return destArray;
  65046. };
  65047. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  65048. if (DDSTools.StoreLODInAlphaChannel) {
  65049. var destArray = new Uint16Array(dataLength);
  65050. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  65051. var index = 0;
  65052. for (var y = 0; y < height; y++) {
  65053. for (var x = 0; x < width; x++) {
  65054. var srcPos = (x + y * width) * 4;
  65055. destArray[index] = srcData[srcPos];
  65056. destArray[index + 1] = srcData[srcPos + 1];
  65057. destArray[index + 2] = srcData[srcPos + 2];
  65058. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  65059. index += 4;
  65060. }
  65061. }
  65062. return destArray;
  65063. }
  65064. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  65065. };
  65066. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  65067. if (DDSTools.StoreLODInAlphaChannel) {
  65068. var destArray = new Float32Array(dataLength);
  65069. var srcData = new Float32Array(arrayBuffer, dataOffset);
  65070. var index = 0;
  65071. for (var y = 0; y < height; y++) {
  65072. for (var x = 0; x < width; x++) {
  65073. var srcPos = (x + y * width) * 4;
  65074. destArray[index] = srcData[srcPos];
  65075. destArray[index + 1] = srcData[srcPos + 1];
  65076. destArray[index + 2] = srcData[srcPos + 2];
  65077. destArray[index + 3] = lod;
  65078. index += 4;
  65079. }
  65080. }
  65081. return destArray;
  65082. }
  65083. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  65084. };
  65085. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  65086. var destArray = new Uint8Array(dataLength);
  65087. var srcData = new Float32Array(arrayBuffer, dataOffset);
  65088. var index = 0;
  65089. for (var y = 0; y < height; y++) {
  65090. for (var x = 0; x < width; x++) {
  65091. var srcPos = (x + y * width) * 4;
  65092. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  65093. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  65094. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  65095. if (DDSTools.StoreLODInAlphaChannel) {
  65096. destArray[index + 3] = lod;
  65097. }
  65098. else {
  65099. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  65100. }
  65101. index += 4;
  65102. }
  65103. }
  65104. return destArray;
  65105. };
  65106. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  65107. var destArray = new Uint8Array(dataLength);
  65108. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  65109. var index = 0;
  65110. for (var y = 0; y < height; y++) {
  65111. for (var x = 0; x < width; x++) {
  65112. var srcPos = (x + y * width) * 4;
  65113. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  65114. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  65115. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  65116. if (DDSTools.StoreLODInAlphaChannel) {
  65117. destArray[index + 3] = lod;
  65118. }
  65119. else {
  65120. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  65121. }
  65122. index += 4;
  65123. }
  65124. }
  65125. return destArray;
  65126. };
  65127. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  65128. var byteArray = new Uint8Array(dataLength);
  65129. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  65130. var index = 0;
  65131. for (var y = 0; y < height; y++) {
  65132. for (var x = 0; x < width; x++) {
  65133. var srcPos = (x + y * width) * 4;
  65134. byteArray[index] = srcData[srcPos + 2];
  65135. byteArray[index + 1] = srcData[srcPos + 1];
  65136. byteArray[index + 2] = srcData[srcPos];
  65137. byteArray[index + 3] = srcData[srcPos + 3];
  65138. index += 4;
  65139. }
  65140. }
  65141. return byteArray;
  65142. };
  65143. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  65144. var byteArray = new Uint8Array(dataLength);
  65145. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  65146. var index = 0;
  65147. for (var y = 0; y < height; y++) {
  65148. for (var x = 0; x < width; x++) {
  65149. var srcPos = (x + y * width) * 3;
  65150. byteArray[index] = srcData[srcPos + 2];
  65151. byteArray[index + 1] = srcData[srcPos + 1];
  65152. byteArray[index + 2] = srcData[srcPos];
  65153. index += 3;
  65154. }
  65155. }
  65156. return byteArray;
  65157. };
  65158. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  65159. var byteArray = new Uint8Array(dataLength);
  65160. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  65161. var index = 0;
  65162. for (var y = 0; y < height; y++) {
  65163. for (var x = 0; x < width; x++) {
  65164. var srcPos = (x + y * width);
  65165. byteArray[index] = srcData[srcPos];
  65166. index++;
  65167. }
  65168. }
  65169. return byteArray;
  65170. };
  65171. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  65172. if (lodIndex === void 0) { lodIndex = -1; }
  65173. var ext = engine.getCaps().s3tc;
  65174. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  65175. if (header[off_magic] != DDS_MAGIC) {
  65176. BABYLON.Tools.Error("Invalid magic number in DDS header");
  65177. return;
  65178. }
  65179. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  65180. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  65181. return;
  65182. }
  65183. if (info.isCompressed && !ext) {
  65184. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  65185. return;
  65186. }
  65187. var bpp = header[off_RGBbpp];
  65188. dataOffset = header[off_size] + 4;
  65189. var computeFormats = false;
  65190. if (info.isFourCC) {
  65191. fourCC = header[off_pfFourCC];
  65192. switch (fourCC) {
  65193. case FOURCC_DXT1:
  65194. blockBytes = 8;
  65195. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  65196. break;
  65197. case FOURCC_DXT3:
  65198. blockBytes = 16;
  65199. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  65200. break;
  65201. case FOURCC_DXT5:
  65202. blockBytes = 16;
  65203. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  65204. break;
  65205. case FOURCC_D3DFMT_R16G16B16A16F:
  65206. computeFormats = true;
  65207. break;
  65208. case FOURCC_D3DFMT_R32G32B32A32F:
  65209. computeFormats = true;
  65210. break;
  65211. case FOURCC_DX10:
  65212. // There is an additionnal header so dataOffset need to be changed
  65213. dataOffset += 5 * 4; // 5 uints
  65214. var supported = false;
  65215. switch (info.dxgiFormat) {
  65216. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  65217. computeFormats = true;
  65218. supported = true;
  65219. break;
  65220. case DXGI_FORMAT_B8G8R8X8_UNORM:
  65221. info.isRGB = true;
  65222. info.isFourCC = false;
  65223. bpp = 32;
  65224. supported = true;
  65225. break;
  65226. }
  65227. if (supported) {
  65228. break;
  65229. }
  65230. default:
  65231. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  65232. return;
  65233. }
  65234. }
  65235. if (computeFormats) {
  65236. format = engine._getWebGLTextureType(info.textureType);
  65237. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  65238. }
  65239. mipmapCount = 1;
  65240. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  65241. mipmapCount = Math.max(1, header[off_mipmapCount]);
  65242. }
  65243. for (var face = 0; face < faces; face++) {
  65244. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  65245. width = header[off_width];
  65246. height = header[off_height];
  65247. for (mip = 0; mip < mipmapCount; ++mip) {
  65248. if (lodIndex === -1 || lodIndex === mip) {
  65249. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  65250. var i = (lodIndex === -1) ? mip : 0;
  65251. if (!info.isCompressed && info.isFourCC) {
  65252. dataLength = width * height * 4;
  65253. var floatArray;
  65254. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  65255. if (bpp === 128) {
  65256. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  65257. }
  65258. else if (bpp === 64) {
  65259. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  65260. }
  65261. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65262. format = engine._getWebGLTextureType(info.textureType);
  65263. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  65264. }
  65265. else {
  65266. if (bpp === 128) {
  65267. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  65268. }
  65269. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  65270. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  65271. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65272. format = engine._getWebGLTextureType(info.textureType);
  65273. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  65274. }
  65275. else {
  65276. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  65277. }
  65278. }
  65279. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  65280. }
  65281. else if (info.isRGB) {
  65282. if (bpp === 24) {
  65283. dataLength = width * height * 3;
  65284. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  65285. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  65286. }
  65287. else {
  65288. dataLength = width * height * 4;
  65289. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  65290. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  65291. }
  65292. }
  65293. else if (info.isLuminance) {
  65294. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  65295. var unpaddedRowSize = width;
  65296. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  65297. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  65298. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  65299. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  65300. }
  65301. else {
  65302. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  65303. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  65304. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  65305. }
  65306. }
  65307. dataOffset += width * height * (bpp / 8);
  65308. width *= 0.5;
  65309. height *= 0.5;
  65310. width = Math.max(1.0, width);
  65311. height = Math.max(1.0, height);
  65312. }
  65313. }
  65314. };
  65315. DDSTools.StoreLODInAlphaChannel = false;
  65316. return DDSTools;
  65317. }());
  65318. Internals.DDSTools = DDSTools;
  65319. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  65320. })(BABYLON || (BABYLON = {}));
  65321. //# sourceMappingURL=babylon.dds.js.map
  65322. var BABYLON;
  65323. (function (BABYLON) {
  65324. var Internals;
  65325. (function (Internals) {
  65326. /**
  65327. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  65328. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  65329. */
  65330. var KhronosTextureContainer = (function () {
  65331. /**
  65332. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  65333. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  65334. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  65335. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  65336. */
  65337. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  65338. this.arrayBuffer = arrayBuffer;
  65339. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  65340. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  65341. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  65342. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  65343. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  65344. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  65345. BABYLON.Tools.Error("texture missing KTX identifier");
  65346. return;
  65347. }
  65348. // load the reset of the header in native 32 bit int
  65349. var header = new Int32Array(this.arrayBuffer, 12, 13);
  65350. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  65351. var oppositeEndianess = header[0] === 0x01020304;
  65352. // read all the header elements in order they exist in the file, without modification (sans endainness)
  65353. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  65354. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  65355. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  65356. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  65357. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  65358. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  65359. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  65360. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  65361. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  65362. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  65363. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  65364. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  65365. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  65366. if (this.glType !== 0) {
  65367. BABYLON.Tools.Error("only compressed formats currently supported");
  65368. return;
  65369. }
  65370. else {
  65371. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  65372. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  65373. }
  65374. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  65375. BABYLON.Tools.Error("only 2D textures currently supported");
  65376. return;
  65377. }
  65378. if (this.numberOfArrayElements !== 0) {
  65379. BABYLON.Tools.Error("texture arrays not currently supported");
  65380. return;
  65381. }
  65382. if (this.numberOfFaces !== facesExpected) {
  65383. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  65384. return;
  65385. }
  65386. // we now have a completely validated file, so could use existence of loadType as success
  65387. // would need to make this more elaborate & adjust checks above to support more than one load type
  65388. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  65389. }
  65390. // not as fast hardware based, but will probably never need to use
  65391. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  65392. return ((val & 0xFF) << 24)
  65393. | ((val & 0xFF00) << 8)
  65394. | ((val >> 8) & 0xFF00)
  65395. | ((val >> 24) & 0xFF);
  65396. };
  65397. /**
  65398. * It is assumed that the texture has already been created & is currently bound
  65399. */
  65400. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  65401. switch (this.loadType) {
  65402. case KhronosTextureContainer.COMPRESSED_2D:
  65403. this._upload2DCompressedLevels(gl, loadMipmaps);
  65404. break;
  65405. case KhronosTextureContainer.TEX_2D:
  65406. case KhronosTextureContainer.COMPRESSED_3D:
  65407. case KhronosTextureContainer.TEX_3D:
  65408. }
  65409. };
  65410. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  65411. // initialize width & height for level 1
  65412. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  65413. var width = this.pixelWidth;
  65414. var height = this.pixelHeight;
  65415. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  65416. for (var level = 0; level < mipmapCount; level++) {
  65417. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  65418. for (var face = 0; face < this.numberOfFaces; face++) {
  65419. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  65420. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  65421. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  65422. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  65423. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  65424. }
  65425. width = Math.max(1.0, width * 0.5);
  65426. height = Math.max(1.0, height * 0.5);
  65427. }
  65428. };
  65429. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  65430. // load types
  65431. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  65432. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  65433. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  65434. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  65435. return KhronosTextureContainer;
  65436. }());
  65437. Internals.KhronosTextureContainer = KhronosTextureContainer;
  65438. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  65439. })(BABYLON || (BABYLON = {}));
  65440. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  65441. var BABYLON;
  65442. (function (BABYLON) {
  65443. var DynamicFloatArrayElementInfo = (function () {
  65444. function DynamicFloatArrayElementInfo() {
  65445. }
  65446. return DynamicFloatArrayElementInfo;
  65447. }());
  65448. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  65449. /**
  65450. * 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.
  65451. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  65452. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  65453. * 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.
  65454. * 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.
  65455. * 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".
  65456. */
  65457. var DynamicFloatArray = (function () {
  65458. /**
  65459. * Construct an instance of the dynamic float array
  65460. * @param stride size of one element in float (i.e. not bytes!)
  65461. * @param initialElementCount the number of available entries at construction
  65462. */
  65463. function DynamicFloatArray(stride, initialElementCount) {
  65464. this.compareValueOffset = null;
  65465. this.sortingAscending = true;
  65466. this._stride = stride;
  65467. this.buffer = new Float32Array(stride * initialElementCount);
  65468. this._lastUsed = 0;
  65469. this._firstFree = 0;
  65470. this._allEntries = new Array(initialElementCount);
  65471. this._freeEntries = new Array(initialElementCount);
  65472. for (var i = 0; i < initialElementCount; i++) {
  65473. var element = new DynamicFloatArrayElementInfo();
  65474. element.offset = i * stride;
  65475. this._allEntries[i] = element;
  65476. this._freeEntries[initialElementCount - i - 1] = element;
  65477. }
  65478. }
  65479. /**
  65480. * Allocate an element in the array.
  65481. * @return the element info instance that contains the offset into the main buffer of the element's location.
  65482. * Beware, this offset may change when you call pack()
  65483. */
  65484. DynamicFloatArray.prototype.allocElement = function () {
  65485. if (this._freeEntries.length === 0) {
  65486. this._growBuffer();
  65487. }
  65488. var el = this._freeEntries.pop();
  65489. this._lastUsed = Math.max(el.offset, this._lastUsed);
  65490. if (el.offset === this._firstFree) {
  65491. if (this._freeEntries.length > 0) {
  65492. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  65493. }
  65494. else {
  65495. this._firstFree += this._stride;
  65496. }
  65497. }
  65498. return el;
  65499. };
  65500. /**
  65501. * Free the element corresponding to the given element info
  65502. * @param elInfo the element that describe the allocated element
  65503. */
  65504. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  65505. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  65506. this._freeEntries.push(elInfo);
  65507. };
  65508. /**
  65509. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  65510. * 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().
  65511. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  65512. */
  65513. DynamicFloatArray.prototype.pack = function () {
  65514. // no free slot? no need to pack
  65515. if (this._freeEntries.length === 0) {
  65516. return this.buffer;
  65517. }
  65518. // If the buffer is already packed the last used will always be lower than the first free
  65519. // 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.
  65520. if (this._lastUsed < this._firstFree) {
  65521. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  65522. return elementsBuffer_1;
  65523. }
  65524. var s = this._stride;
  65525. // 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
  65526. var lastFree = new DynamicFloatArrayElementInfo();
  65527. lastFree.offset = this.totalElementCount * s;
  65528. this._freeEntries.push(lastFree);
  65529. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  65530. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  65531. var firstFreeSlotOffset = sortedFree[0].offset;
  65532. var freeZoneSize = 1;
  65533. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  65534. var prevOffset = sortedFree[0].offset;
  65535. for (var i = 1; i < sortedFree.length; i++) {
  65536. // 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
  65537. if (firstFreeSlotOffset >= occupiedZoneSize) {
  65538. break;
  65539. }
  65540. var curFree = sortedFree[i];
  65541. var curOffset = curFree.offset;
  65542. // Compute the distance between this offset and the previous
  65543. var distance = curOffset - prevOffset;
  65544. // If the distance is the stride size, they are adjacent, it good, move to the next
  65545. if (distance === s) {
  65546. // Free zone is one element bigger
  65547. ++freeZoneSize;
  65548. // as we're about to iterate to the next, the cur becomes the previous...
  65549. prevOffset = curOffset;
  65550. continue;
  65551. }
  65552. // Distance is bigger, which means there's x element between the previous free and this one
  65553. var usedRange = (distance / s) - 1;
  65554. // Two cases the free zone is smaller than the data to move or bigger
  65555. // Copy what can fit in the free zone
  65556. var curMoveOffset = curOffset - s;
  65557. var copyCount = Math.min(freeZoneSize, usedRange);
  65558. for (var j = 0; j < copyCount; j++) {
  65559. var freeI = firstFreeSlotOffset / s;
  65560. var curI = curMoveOffset / s;
  65561. var moveEl = sortedAll[curI];
  65562. this._moveElement(moveEl, firstFreeSlotOffset);
  65563. var replacedEl = sortedAll[freeI];
  65564. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  65565. replacedEl.offset = curMoveOffset;
  65566. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  65567. sortedAll[freeI] = moveEl;
  65568. sortedAll[curI] = replacedEl;
  65569. curMoveOffset -= s;
  65570. firstFreeSlotOffset += s;
  65571. }
  65572. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  65573. if (freeZoneSize <= usedRange) {
  65574. firstFreeSlotOffset = curMoveOffset + s;
  65575. freeZoneSize = 1 + copyCount;
  65576. }
  65577. else {
  65578. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  65579. }
  65580. // as we're about to iterate to the next, the cur becomes the previous...
  65581. prevOffset = curOffset;
  65582. }
  65583. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  65584. this._lastUsed = firstFreeSlotOffset - s;
  65585. this._firstFree = firstFreeSlotOffset;
  65586. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  65587. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  65588. this._allEntries = sortedAll;
  65589. return elementsBuffer;
  65590. };
  65591. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  65592. for (var i = 0; i < this._stride; i++) {
  65593. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  65594. }
  65595. element.offset = destOffset;
  65596. };
  65597. DynamicFloatArray.prototype._growBuffer = function () {
  65598. // Allocate the new buffer with 50% more entries, copy the content of the current one
  65599. var newElCount = Math.floor(this.totalElementCount * 1.5);
  65600. var newBuffer = new Float32Array(newElCount * this._stride);
  65601. newBuffer.set(this.buffer);
  65602. var curCount = this.totalElementCount;
  65603. var addedCount = newElCount - this.totalElementCount;
  65604. for (var i = 0; i < addedCount; i++) {
  65605. var element = new DynamicFloatArrayElementInfo();
  65606. element.offset = (curCount + i) * this.stride;
  65607. this._allEntries.push(element);
  65608. this._freeEntries[addedCount - i - 1] = element;
  65609. }
  65610. this._firstFree = curCount * this.stride;
  65611. this.buffer = newBuffer;
  65612. };
  65613. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  65614. /**
  65615. * Get the total count of entries that can fit in the current buffer
  65616. * @returns the elements count
  65617. */
  65618. get: function () {
  65619. return this._allEntries.length;
  65620. },
  65621. enumerable: true,
  65622. configurable: true
  65623. });
  65624. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  65625. /**
  65626. * Get the count of free entries that can still be allocated without resizing the buffer
  65627. * @returns the free elements count
  65628. */
  65629. get: function () {
  65630. return this._freeEntries.length;
  65631. },
  65632. enumerable: true,
  65633. configurable: true
  65634. });
  65635. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  65636. /**
  65637. * Get the count of allocated elements
  65638. * @returns the allocated elements count
  65639. */
  65640. get: function () {
  65641. return this._allEntries.length - this._freeEntries.length;
  65642. },
  65643. enumerable: true,
  65644. configurable: true
  65645. });
  65646. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  65647. /**
  65648. * Return the size of one element in float
  65649. * @returns the size in float
  65650. */
  65651. get: function () {
  65652. return this._stride;
  65653. },
  65654. enumerable: true,
  65655. configurable: true
  65656. });
  65657. DynamicFloatArray.prototype.sort = function () {
  65658. var _this = this;
  65659. if (!this.compareValueOffset) {
  65660. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  65661. }
  65662. var count = this.usedElementCount;
  65663. // Do we have to (re)create the sort table?
  65664. if (!this._sortTable || this._sortTable.length < count) {
  65665. // 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...
  65666. var newCount = Math.min(this.totalElementCount, count * 2);
  65667. this._sortTable = new Array(newCount);
  65668. }
  65669. if (!this._sortedTable || this._sortedTable.length !== count) {
  65670. this._sortedTable = new Array(count);
  65671. }
  65672. // Because, you know...
  65673. this.pack();
  65674. //let stride = this.stride;
  65675. //for (let i = 0; i < count; i++) {
  65676. // let si = this._sortTable[i];
  65677. // if (!si) {
  65678. // si = new SortInfo();
  65679. // this._sortTable[i] = si;
  65680. // }
  65681. // si.entry = this._allEntries[i];
  65682. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  65683. // si.swapedOffset = null;
  65684. // this._sortedTable[i] = si;
  65685. //}
  65686. var curOffset = 0;
  65687. var stride = this.stride;
  65688. for (var i = 0; i < count; i++, curOffset += stride) {
  65689. var si = this._sortTable[i];
  65690. if (!si) {
  65691. si = new SortInfo();
  65692. this._sortTable[i] = si;
  65693. }
  65694. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  65695. si.offset = curOffset;
  65696. si.swapedOffset = null;
  65697. this._sortedTable[i] = si;
  65698. }
  65699. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  65700. if (this.sortingAscending) {
  65701. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  65702. }
  65703. else {
  65704. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  65705. }
  65706. var swapElements = function (src, dst) {
  65707. for (var i = 0; i < stride; i++) {
  65708. var tps = _this.buffer[dst + i];
  65709. _this.buffer[dst + i] = _this.buffer[src + i];
  65710. _this.buffer[src + i] = tps;
  65711. }
  65712. };
  65713. // 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:
  65714. // 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),
  65715. // and I still want something with a good algorithm complexity.
  65716. // 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,
  65717. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  65718. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  65719. // 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
  65720. // until we find a SortInfo object without a swapedOffset which means we got the right location
  65721. // 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
  65722. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  65723. for (var i = 0; i < count; i++) {
  65724. // Get the element to move
  65725. var sourceSI = this._sortedTable[i];
  65726. var destSI = this._sortTable[i];
  65727. var sourceOff = sourceSI.offset;
  65728. // If the source changed location, find the new one
  65729. if (sourceSI.swapedOffset) {
  65730. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  65731. var curSI = sourceSI;
  65732. while (curSI.swapedOffset) {
  65733. curSI = this._sortTable[curSI.swapedOffset / stride];
  65734. }
  65735. // Finally get the right location
  65736. sourceOff = curSI.offset;
  65737. }
  65738. // Tag the element being replaced with its new location
  65739. destSI.swapedOffset = sourceOff;
  65740. // Swap elements (only if needed)
  65741. if (sourceOff !== destSI.offset) {
  65742. swapElements(sourceOff, destSI.offset);
  65743. }
  65744. // Update the offset in the corresponding DFAE
  65745. //sourceSI.entry.offset = destSI.entry.offset;
  65746. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  65747. }
  65748. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  65749. return true;
  65750. };
  65751. return DynamicFloatArray;
  65752. }());
  65753. BABYLON.DynamicFloatArray = DynamicFloatArray;
  65754. var SortInfo = (function () {
  65755. function SortInfo() {
  65756. this.compareData = this.offset = this.swapedOffset = null;
  65757. }
  65758. return SortInfo;
  65759. }());
  65760. })(BABYLON || (BABYLON = {}));
  65761. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  65762. var BABYLON;
  65763. (function (BABYLON) {
  65764. var Debug;
  65765. (function (Debug) {
  65766. /**
  65767. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  65768. */
  65769. var SkeletonViewer = (function () {
  65770. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  65771. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  65772. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  65773. this.skeleton = skeleton;
  65774. this.mesh = mesh;
  65775. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  65776. this.renderingGroupId = renderingGroupId;
  65777. this.color = BABYLON.Color3.White();
  65778. this._debugLines = new Array();
  65779. this._isEnabled = false;
  65780. this._scene = scene;
  65781. this.update();
  65782. this._renderFunction = this.update.bind(this);
  65783. }
  65784. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  65785. get: function () {
  65786. return this._isEnabled;
  65787. },
  65788. set: function (value) {
  65789. if (this._isEnabled === value) {
  65790. return;
  65791. }
  65792. this._isEnabled = value;
  65793. if (value) {
  65794. this._scene.registerBeforeRender(this._renderFunction);
  65795. }
  65796. else {
  65797. this._scene.unregisterBeforeRender(this._renderFunction);
  65798. }
  65799. },
  65800. enumerable: true,
  65801. configurable: true
  65802. });
  65803. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  65804. if (x === void 0) { x = 0; }
  65805. if (y === void 0) { y = 0; }
  65806. if (z === void 0) { z = 0; }
  65807. var tmat = BABYLON.Tmp.Matrix[0];
  65808. var parentBone = bone.getParent();
  65809. tmat.copyFrom(bone.getLocalMatrix());
  65810. if (x !== 0 || y !== 0 || z !== 0) {
  65811. var tmat2 = BABYLON.Tmp.Matrix[1];
  65812. BABYLON.Matrix.IdentityToRef(tmat2);
  65813. tmat2.m[12] = x;
  65814. tmat2.m[13] = y;
  65815. tmat2.m[14] = z;
  65816. tmat2.multiplyToRef(tmat, tmat);
  65817. }
  65818. if (parentBone) {
  65819. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  65820. }
  65821. tmat.multiplyToRef(meshMat, tmat);
  65822. position.x = tmat.m[12];
  65823. position.y = tmat.m[13];
  65824. position.z = tmat.m[14];
  65825. };
  65826. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  65827. var len = bones.length;
  65828. var meshPos = this.mesh.position;
  65829. for (var i = 0; i < len; i++) {
  65830. var bone = bones[i];
  65831. var points = this._debugLines[i];
  65832. if (!points) {
  65833. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65834. this._debugLines[i] = points;
  65835. }
  65836. this._getBonePosition(points[0], bone, meshMat);
  65837. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  65838. points[0].subtractInPlace(meshPos);
  65839. points[1].subtractInPlace(meshPos);
  65840. }
  65841. };
  65842. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  65843. var len = bones.length;
  65844. var boneNum = 0;
  65845. var meshPos = this.mesh.position;
  65846. for (var i = len - 1; i >= 0; i--) {
  65847. var childBone = bones[i];
  65848. var parentBone = childBone.getParent();
  65849. if (!parentBone) {
  65850. continue;
  65851. }
  65852. var points = this._debugLines[boneNum];
  65853. if (!points) {
  65854. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65855. this._debugLines[boneNum] = points;
  65856. }
  65857. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  65858. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  65859. points[0].subtractInPlace(meshPos);
  65860. points[1].subtractInPlace(meshPos);
  65861. boneNum++;
  65862. }
  65863. };
  65864. SkeletonViewer.prototype.update = function () {
  65865. if (this.autoUpdateBonesMatrices) {
  65866. this.skeleton.computeAbsoluteTransforms();
  65867. }
  65868. if (this.skeleton.bones[0].length === undefined) {
  65869. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  65870. }
  65871. else {
  65872. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  65873. }
  65874. if (!this._debugMesh) {
  65875. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  65876. this._debugMesh.renderingGroupId = this.renderingGroupId;
  65877. }
  65878. else {
  65879. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  65880. }
  65881. this._debugMesh.position.copyFrom(this.mesh.position);
  65882. this._debugMesh.color = this.color;
  65883. };
  65884. SkeletonViewer.prototype.dispose = function () {
  65885. if (this._debugMesh) {
  65886. this.isEnabled = false;
  65887. this._debugMesh.dispose();
  65888. this._debugMesh = null;
  65889. }
  65890. };
  65891. return SkeletonViewer;
  65892. }());
  65893. Debug.SkeletonViewer = SkeletonViewer;
  65894. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  65895. })(BABYLON || (BABYLON = {}));
  65896. //# sourceMappingURL=babylon.skeletonViewer.js.map
  65897. var BABYLON;
  65898. (function (BABYLON) {
  65899. var Debug;
  65900. (function (Debug) {
  65901. var AxesViewer = (function () {
  65902. function AxesViewer(scene, scaleLines) {
  65903. if (scaleLines === void 0) { scaleLines = 1; }
  65904. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65905. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65906. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65907. this.scaleLines = 1;
  65908. this.scaleLines = scaleLines;
  65909. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  65910. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  65911. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  65912. this._xmesh.renderingGroupId = 2;
  65913. this._ymesh.renderingGroupId = 2;
  65914. this._zmesh.renderingGroupId = 2;
  65915. this._xmesh.material.checkReadyOnlyOnce = true;
  65916. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  65917. this._ymesh.material.checkReadyOnlyOnce = true;
  65918. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  65919. this._zmesh.material.checkReadyOnlyOnce = true;
  65920. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  65921. this.scene = scene;
  65922. }
  65923. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  65924. var scaleLines = this.scaleLines;
  65925. this._xmesh.position.copyFrom(position);
  65926. this._ymesh.position.copyFrom(position);
  65927. this._zmesh.position.copyFrom(position);
  65928. var point2 = this._xline[1];
  65929. point2.x = xaxis.x * scaleLines;
  65930. point2.y = xaxis.y * scaleLines;
  65931. point2.z = xaxis.z * scaleLines;
  65932. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  65933. point2 = this._yline[1];
  65934. point2.x = yaxis.x * scaleLines;
  65935. point2.y = yaxis.y * scaleLines;
  65936. point2.z = yaxis.z * scaleLines;
  65937. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  65938. point2 = this._zline[1];
  65939. point2.x = zaxis.x * scaleLines;
  65940. point2.y = zaxis.y * scaleLines;
  65941. point2.z = zaxis.z * scaleLines;
  65942. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  65943. };
  65944. AxesViewer.prototype.dispose = function () {
  65945. if (this._xmesh) {
  65946. this._xmesh.dispose();
  65947. this._ymesh.dispose();
  65948. this._zmesh.dispose();
  65949. this._xmesh = null;
  65950. this._ymesh = null;
  65951. this._zmesh = null;
  65952. this._xline = null;
  65953. this._yline = null;
  65954. this._zline = null;
  65955. this.scene = null;
  65956. }
  65957. };
  65958. return AxesViewer;
  65959. }());
  65960. Debug.AxesViewer = AxesViewer;
  65961. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  65962. })(BABYLON || (BABYLON = {}));
  65963. //# sourceMappingURL=babylon.axesViewer.js.map
  65964. var BABYLON;
  65965. (function (BABYLON) {
  65966. var Debug;
  65967. (function (Debug) {
  65968. var BoneAxesViewer = (function (_super) {
  65969. __extends(BoneAxesViewer, _super);
  65970. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  65971. if (scaleLines === void 0) { scaleLines = 1; }
  65972. var _this = _super.call(this, scene, scaleLines) || this;
  65973. _this.pos = BABYLON.Vector3.Zero();
  65974. _this.xaxis = BABYLON.Vector3.Zero();
  65975. _this.yaxis = BABYLON.Vector3.Zero();
  65976. _this.zaxis = BABYLON.Vector3.Zero();
  65977. _this.mesh = mesh;
  65978. _this.bone = bone;
  65979. return _this;
  65980. }
  65981. BoneAxesViewer.prototype.update = function () {
  65982. var bone = this.bone;
  65983. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  65984. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  65985. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  65986. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  65987. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  65988. };
  65989. BoneAxesViewer.prototype.dispose = function () {
  65990. if (this.pos) {
  65991. this.pos = null;
  65992. this.xaxis = null;
  65993. this.yaxis = null;
  65994. this.zaxis = null;
  65995. this.mesh = null;
  65996. this.bone = null;
  65997. _super.prototype.dispose.call(this);
  65998. }
  65999. };
  66000. return BoneAxesViewer;
  66001. }(Debug.AxesViewer));
  66002. Debug.BoneAxesViewer = BoneAxesViewer;
  66003. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  66004. })(BABYLON || (BABYLON = {}));
  66005. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  66006. var BABYLON;
  66007. (function (BABYLON) {
  66008. var RayHelper = (function () {
  66009. function RayHelper(ray) {
  66010. this.ray = ray;
  66011. }
  66012. RayHelper.CreateAndShow = function (ray, scene, color) {
  66013. var helper = new RayHelper(ray);
  66014. helper.show(scene, color);
  66015. return helper;
  66016. };
  66017. RayHelper.prototype.show = function (scene, color) {
  66018. if (!this._renderFunction) {
  66019. var ray = this.ray;
  66020. this._renderFunction = this._render.bind(this);
  66021. this._scene = scene;
  66022. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  66023. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  66024. this._scene.registerBeforeRender(this._renderFunction);
  66025. }
  66026. if (color) {
  66027. this._renderLine.color.copyFrom(color);
  66028. }
  66029. };
  66030. RayHelper.prototype.hide = function () {
  66031. if (this._renderFunction) {
  66032. this._scene.unregisterBeforeRender(this._renderFunction);
  66033. this._scene = null;
  66034. this._renderFunction = null;
  66035. this._renderLine.dispose();
  66036. this._renderLine = null;
  66037. this._renderPoints = null;
  66038. }
  66039. };
  66040. RayHelper.prototype._render = function () {
  66041. var ray = this.ray;
  66042. var point = this._renderPoints[1];
  66043. var len = Math.min(ray.length, 1000000);
  66044. point.copyFrom(ray.direction);
  66045. point.scaleInPlace(len);
  66046. point.addInPlace(ray.origin);
  66047. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  66048. };
  66049. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  66050. this._attachedToMesh = mesh;
  66051. var ray = this.ray;
  66052. if (!ray.direction) {
  66053. ray.direction = BABYLON.Vector3.Zero();
  66054. }
  66055. if (!ray.origin) {
  66056. ray.origin = BABYLON.Vector3.Zero();
  66057. }
  66058. if (length) {
  66059. ray.length = length;
  66060. }
  66061. if (!meshSpaceOrigin) {
  66062. meshSpaceOrigin = BABYLON.Vector3.Zero();
  66063. }
  66064. if (!meshSpaceDirection) {
  66065. // -1 so that this will work with Mesh.lookAt
  66066. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  66067. }
  66068. if (!this._meshSpaceDirection) {
  66069. this._meshSpaceDirection = meshSpaceDirection.clone();
  66070. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  66071. }
  66072. else {
  66073. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  66074. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  66075. }
  66076. if (!this._updateToMeshFunction) {
  66077. this._updateToMeshFunction = this._updateToMesh.bind(this);
  66078. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  66079. }
  66080. this._updateToMesh();
  66081. };
  66082. RayHelper.prototype.detachFromMesh = function () {
  66083. if (this._attachedToMesh) {
  66084. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  66085. this._attachedToMesh = null;
  66086. this._updateToMeshFunction = null;
  66087. }
  66088. };
  66089. RayHelper.prototype._updateToMesh = function () {
  66090. var ray = this.ray;
  66091. if (this._attachedToMesh._isDisposed) {
  66092. this.detachFromMesh();
  66093. return;
  66094. }
  66095. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  66096. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  66097. };
  66098. RayHelper.prototype.dispose = function () {
  66099. this.hide();
  66100. this.detachFromMesh();
  66101. this.ray = null;
  66102. };
  66103. return RayHelper;
  66104. }());
  66105. BABYLON.RayHelper = RayHelper;
  66106. })(BABYLON || (BABYLON = {}));
  66107. //# sourceMappingURL=babylon.rayHelper.js.map
  66108. var BABYLON;
  66109. (function (BABYLON) {
  66110. var DebugLayer = (function () {
  66111. function DebugLayer(scene) {
  66112. this._scene = scene;
  66113. }
  66114. /** Creates the inspector window. */
  66115. DebugLayer.prototype._createInspector = function (config) {
  66116. if (config === void 0) { config = {}; }
  66117. var popup = config.popup || false;
  66118. var initialTab = config.initialTab || 0;
  66119. var parentElement = config.parentElement || null;
  66120. if (!this._inspector) {
  66121. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  66122. } // else nothing to do,; instance is already existing
  66123. };
  66124. DebugLayer.prototype.isVisible = function () {
  66125. if (!this._inspector) {
  66126. return false;
  66127. }
  66128. return true;
  66129. };
  66130. DebugLayer.prototype.hide = function () {
  66131. if (this._inspector) {
  66132. try {
  66133. this._inspector.dispose();
  66134. }
  66135. catch (e) {
  66136. // If the inspector has been removed directly from the inspector tool
  66137. }
  66138. this._inspector = null;
  66139. }
  66140. };
  66141. DebugLayer.prototype.show = function (config) {
  66142. if (config === void 0) { config = {}; }
  66143. if (typeof INSPECTOR == 'undefined') {
  66144. // Load inspector and add it to the DOM
  66145. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  66146. }
  66147. else {
  66148. // Otherwise creates the inspector
  66149. this._createInspector(config);
  66150. }
  66151. };
  66152. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  66153. return DebugLayer;
  66154. }());
  66155. BABYLON.DebugLayer = DebugLayer;
  66156. })(BABYLON || (BABYLON = {}));
  66157. //# sourceMappingURL=babylon.debugLayer.js.map
  66158. var BABYLON;
  66159. (function (BABYLON) {
  66160. var Debug;
  66161. (function (Debug) {
  66162. var PhysicsViewer = (function () {
  66163. function PhysicsViewer(scene) {
  66164. this._impostors = [];
  66165. this._meshes = [];
  66166. this._numMeshes = 0;
  66167. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66168. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  66169. }
  66170. PhysicsViewer.prototype._updateDebugMeshes = function () {
  66171. var plugin = this._physicsEnginePlugin;
  66172. for (var i = 0; i < this._numMeshes; i++) {
  66173. if (this._impostors[i].isDisposed) {
  66174. this.hideImpostor(this._impostors[i--]);
  66175. }
  66176. else {
  66177. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  66178. }
  66179. }
  66180. };
  66181. PhysicsViewer.prototype.showImpostor = function (impostor) {
  66182. for (var i = 0; i < this._numMeshes; i++) {
  66183. if (this._impostors[i] == impostor) {
  66184. return;
  66185. }
  66186. }
  66187. var debugMesh = this._getDebugMesh(impostor, this._scene);
  66188. if (debugMesh) {
  66189. this._impostors[this._numMeshes] = impostor;
  66190. this._meshes[this._numMeshes] = debugMesh;
  66191. if (this._numMeshes === 0) {
  66192. this._renderFunction = this._updateDebugMeshes.bind(this);
  66193. this._scene.registerBeforeRender(this._renderFunction);
  66194. }
  66195. this._numMeshes++;
  66196. }
  66197. };
  66198. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  66199. var removed = false;
  66200. for (var i = 0; i < this._numMeshes; i++) {
  66201. if (this._impostors[i] == impostor) {
  66202. this._scene.removeMesh(this._meshes[i]);
  66203. this._meshes[i].dispose();
  66204. this._numMeshes--;
  66205. if (this._numMeshes > 0) {
  66206. this._meshes[i] = this._meshes[this._numMeshes];
  66207. this._impostors[i] = this._impostors[this._numMeshes];
  66208. this._meshes[this._numMeshes] = null;
  66209. this._impostors[this._numMeshes] = null;
  66210. }
  66211. else {
  66212. this._meshes[0] = null;
  66213. this._impostors[0] = null;
  66214. }
  66215. removed = true;
  66216. break;
  66217. }
  66218. }
  66219. if (removed && this._numMeshes === 0) {
  66220. this._scene.unregisterBeforeRender(this._renderFunction);
  66221. }
  66222. };
  66223. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  66224. if (!this._debugMaterial) {
  66225. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  66226. this._debugMaterial.wireframe = true;
  66227. }
  66228. return this._debugMaterial;
  66229. };
  66230. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  66231. if (!this._debugBoxMesh) {
  66232. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  66233. this._debugBoxMesh.renderingGroupId = 1;
  66234. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  66235. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  66236. scene.removeMesh(this._debugBoxMesh);
  66237. }
  66238. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  66239. };
  66240. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  66241. if (!this._debugSphereMesh) {
  66242. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  66243. this._debugSphereMesh.renderingGroupId = 1;
  66244. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  66245. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  66246. scene.removeMesh(this._debugSphereMesh);
  66247. }
  66248. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  66249. };
  66250. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  66251. var body = impostor.physicsBody;
  66252. var shape = body.shapes[0];
  66253. var mesh;
  66254. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  66255. mesh = this._getDebugBoxMesh(scene);
  66256. impostor.getBoxSizeToRef(mesh.scaling);
  66257. }
  66258. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  66259. mesh = this._getDebugSphereMesh(scene);
  66260. var radius = impostor.getRadius();
  66261. mesh.scaling.x = radius * 2;
  66262. mesh.scaling.y = radius * 2;
  66263. mesh.scaling.z = radius * 2;
  66264. }
  66265. return mesh;
  66266. };
  66267. PhysicsViewer.prototype.dispose = function () {
  66268. for (var i = 0; i < this._numMeshes; i++) {
  66269. this.hideImpostor(this._impostors[i]);
  66270. }
  66271. if (this._debugBoxMesh) {
  66272. this._debugBoxMesh.dispose();
  66273. }
  66274. if (this._debugSphereMesh) {
  66275. this._debugSphereMesh.dispose();
  66276. }
  66277. if (this._debugMaterial) {
  66278. this._debugMaterial.dispose();
  66279. }
  66280. this._impostors.length = 0;
  66281. this._scene = null;
  66282. this._physicsEnginePlugin = null;
  66283. };
  66284. return PhysicsViewer;
  66285. }());
  66286. Debug.PhysicsViewer = PhysicsViewer;
  66287. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  66288. })(BABYLON || (BABYLON = {}));
  66289. //# sourceMappingURL=babylon.physicsViewer.js.map
  66290. var BABYLON;
  66291. (function (BABYLON) {
  66292. var BoundingBoxRenderer = (function () {
  66293. function BoundingBoxRenderer(scene) {
  66294. this.frontColor = new BABYLON.Color3(1, 1, 1);
  66295. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  66296. this.showBackLines = true;
  66297. this.renderList = new BABYLON.SmartArray(32);
  66298. this._vertexBuffers = {};
  66299. this._scene = scene;
  66300. }
  66301. BoundingBoxRenderer.prototype._prepareRessources = function () {
  66302. if (this._colorShader) {
  66303. return;
  66304. }
  66305. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  66306. attributes: [BABYLON.VertexBuffer.PositionKind],
  66307. uniforms: ["world", "viewProjection", "color"]
  66308. });
  66309. var engine = this._scene.getEngine();
  66310. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  66311. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  66312. this._createIndexBuffer();
  66313. };
  66314. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  66315. var engine = this._scene.getEngine();
  66316. 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]);
  66317. };
  66318. BoundingBoxRenderer.prototype._rebuild = function () {
  66319. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  66320. this._createIndexBuffer();
  66321. };
  66322. BoundingBoxRenderer.prototype.reset = function () {
  66323. this.renderList.reset();
  66324. };
  66325. BoundingBoxRenderer.prototype.render = function () {
  66326. if (this.renderList.length === 0) {
  66327. return;
  66328. }
  66329. this._prepareRessources();
  66330. if (!this._colorShader.isReady()) {
  66331. return;
  66332. }
  66333. var engine = this._scene.getEngine();
  66334. engine.setDepthWrite(false);
  66335. this._colorShader._preBind();
  66336. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  66337. var boundingBox = this.renderList.data[boundingBoxIndex];
  66338. var min = boundingBox.minimum;
  66339. var max = boundingBox.maximum;
  66340. var diff = max.subtract(min);
  66341. var median = min.add(diff.scale(0.5));
  66342. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  66343. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  66344. .multiply(boundingBox.getWorldMatrix());
  66345. // VBOs
  66346. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  66347. if (this.showBackLines) {
  66348. // Back
  66349. engine.setDepthFunctionToGreaterOrEqual();
  66350. this._scene.resetCachedMaterial();
  66351. this._colorShader.setColor4("color", this.backColor.toColor4());
  66352. this._colorShader.bind(worldMatrix);
  66353. // Draw order
  66354. engine.draw(false, 0, 24);
  66355. }
  66356. // Front
  66357. engine.setDepthFunctionToLess();
  66358. this._scene.resetCachedMaterial();
  66359. this._colorShader.setColor4("color", this.frontColor.toColor4());
  66360. this._colorShader.bind(worldMatrix);
  66361. // Draw order
  66362. engine.draw(false, 0, 24);
  66363. }
  66364. this._colorShader.unbind();
  66365. engine.setDepthFunctionToLessOrEqual();
  66366. engine.setDepthWrite(true);
  66367. };
  66368. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  66369. this._prepareRessources();
  66370. if (!this._colorShader.isReady()) {
  66371. return;
  66372. }
  66373. var engine = this._scene.getEngine();
  66374. engine.setDepthWrite(false);
  66375. engine.setColorWrite(false);
  66376. this._colorShader._preBind();
  66377. var boundingBox = mesh._boundingInfo.boundingBox;
  66378. var min = boundingBox.minimum;
  66379. var max = boundingBox.maximum;
  66380. var diff = max.subtract(min);
  66381. var median = min.add(diff.scale(0.5));
  66382. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  66383. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  66384. .multiply(boundingBox.getWorldMatrix());
  66385. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  66386. engine.setDepthFunctionToLess();
  66387. this._scene.resetCachedMaterial();
  66388. this._colorShader.bind(worldMatrix);
  66389. engine.draw(false, 0, 24);
  66390. this._colorShader.unbind();
  66391. engine.setDepthFunctionToLessOrEqual();
  66392. engine.setDepthWrite(true);
  66393. engine.setColorWrite(true);
  66394. };
  66395. BoundingBoxRenderer.prototype.dispose = function () {
  66396. if (!this._colorShader) {
  66397. return;
  66398. }
  66399. this.renderList.dispose();
  66400. this._colorShader.dispose();
  66401. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66402. if (buffer) {
  66403. buffer.dispose();
  66404. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66405. }
  66406. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  66407. };
  66408. return BoundingBoxRenderer;
  66409. }());
  66410. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  66411. })(BABYLON || (BABYLON = {}));
  66412. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  66413. var BABYLON;
  66414. (function (BABYLON) {
  66415. var MorphTarget = (function () {
  66416. function MorphTarget(name, influence) {
  66417. if (influence === void 0) { influence = 0; }
  66418. this.name = name;
  66419. this.animations = new Array();
  66420. this.onInfluenceChanged = new BABYLON.Observable();
  66421. this.influence = influence;
  66422. }
  66423. Object.defineProperty(MorphTarget.prototype, "influence", {
  66424. get: function () {
  66425. return this._influence;
  66426. },
  66427. set: function (influence) {
  66428. if (this._influence === influence) {
  66429. return;
  66430. }
  66431. var previous = this._influence;
  66432. this._influence = influence;
  66433. if (this.onInfluenceChanged.hasObservers) {
  66434. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  66435. }
  66436. },
  66437. enumerable: true,
  66438. configurable: true
  66439. });
  66440. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  66441. get: function () {
  66442. return this._normals !== undefined;
  66443. },
  66444. enumerable: true,
  66445. configurable: true
  66446. });
  66447. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  66448. get: function () {
  66449. return this._tangents !== undefined;
  66450. },
  66451. enumerable: true,
  66452. configurable: true
  66453. });
  66454. MorphTarget.prototype.setPositions = function (data) {
  66455. this._positions = new Float32Array(data);
  66456. };
  66457. MorphTarget.prototype.getPositions = function () {
  66458. return this._positions;
  66459. };
  66460. MorphTarget.prototype.setNormals = function (data) {
  66461. this._normals = new Float32Array(data);
  66462. };
  66463. MorphTarget.prototype.getNormals = function () {
  66464. return this._normals;
  66465. };
  66466. MorphTarget.prototype.setTangents = function (data) {
  66467. this._tangents = new Float32Array(data);
  66468. };
  66469. MorphTarget.prototype.getTangents = function () {
  66470. return this._tangents;
  66471. };
  66472. /**
  66473. * Serializes the current target into a Serialization object.
  66474. * Returns the serialized object.
  66475. */
  66476. MorphTarget.prototype.serialize = function () {
  66477. var serializationObject = {};
  66478. serializationObject.name = this.name;
  66479. serializationObject.influence = this.influence;
  66480. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  66481. if (this.hasNormals) {
  66482. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  66483. }
  66484. if (this.hasTangents) {
  66485. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  66486. }
  66487. // Animations
  66488. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  66489. return serializationObject;
  66490. };
  66491. // Statics
  66492. MorphTarget.Parse = function (serializationObject) {
  66493. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  66494. result.setPositions(serializationObject.positions);
  66495. if (serializationObject.normals) {
  66496. result.setNormals(serializationObject.normals);
  66497. }
  66498. if (serializationObject.tangents) {
  66499. result.setTangents(serializationObject.tangents);
  66500. }
  66501. // Animations
  66502. if (serializationObject.animations) {
  66503. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  66504. var parsedAnimation = serializationObject.animations[animationIndex];
  66505. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  66506. }
  66507. }
  66508. return result;
  66509. };
  66510. MorphTarget.FromMesh = function (mesh, name, influence) {
  66511. if (!name) {
  66512. name = mesh.name;
  66513. }
  66514. var result = new MorphTarget(name, influence);
  66515. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  66516. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66517. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  66518. }
  66519. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  66520. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  66521. }
  66522. return result;
  66523. };
  66524. return MorphTarget;
  66525. }());
  66526. BABYLON.MorphTarget = MorphTarget;
  66527. })(BABYLON || (BABYLON = {}));
  66528. //# sourceMappingURL=babylon.morphTarget.js.map
  66529. var BABYLON;
  66530. (function (BABYLON) {
  66531. var MorphTargetManager = (function () {
  66532. function MorphTargetManager(scene) {
  66533. this._targets = new Array();
  66534. this._targetObservable = new Array();
  66535. this._activeTargets = new BABYLON.SmartArray(16);
  66536. this._supportsNormals = false;
  66537. this._supportsTangents = false;
  66538. this._vertexCount = 0;
  66539. this._uniqueId = 0;
  66540. this._tempInfluences = new Array();
  66541. if (!scene) {
  66542. scene = BABYLON.Engine.LastCreatedScene;
  66543. }
  66544. this._scene = scene;
  66545. this._scene.morphTargetManagers.push(this);
  66546. this._uniqueId = scene.getUniqueId();
  66547. }
  66548. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  66549. get: function () {
  66550. return this._uniqueId;
  66551. },
  66552. enumerable: true,
  66553. configurable: true
  66554. });
  66555. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  66556. get: function () {
  66557. return this._vertexCount;
  66558. },
  66559. enumerable: true,
  66560. configurable: true
  66561. });
  66562. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  66563. get: function () {
  66564. return this._supportsNormals;
  66565. },
  66566. enumerable: true,
  66567. configurable: true
  66568. });
  66569. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  66570. get: function () {
  66571. return this._supportsTangents;
  66572. },
  66573. enumerable: true,
  66574. configurable: true
  66575. });
  66576. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  66577. get: function () {
  66578. return this._targets.length;
  66579. },
  66580. enumerable: true,
  66581. configurable: true
  66582. });
  66583. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  66584. get: function () {
  66585. return this._activeTargets.length;
  66586. },
  66587. enumerable: true,
  66588. configurable: true
  66589. });
  66590. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  66591. get: function () {
  66592. return this._influences;
  66593. },
  66594. enumerable: true,
  66595. configurable: true
  66596. });
  66597. MorphTargetManager.prototype.getActiveTarget = function (index) {
  66598. return this._activeTargets.data[index];
  66599. };
  66600. MorphTargetManager.prototype.getTarget = function (index) {
  66601. return this._targets[index];
  66602. };
  66603. MorphTargetManager.prototype.addTarget = function (target) {
  66604. var _this = this;
  66605. if (this._vertexCount) {
  66606. if (this._vertexCount !== target.getPositions().length / 3) {
  66607. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  66608. return;
  66609. }
  66610. }
  66611. this._targets.push(target);
  66612. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  66613. _this._syncActiveTargets(needUpdate);
  66614. }));
  66615. this._syncActiveTargets(true);
  66616. };
  66617. MorphTargetManager.prototype.removeTarget = function (target) {
  66618. var index = this._targets.indexOf(target);
  66619. if (index >= 0) {
  66620. this._targets.splice(index, 1);
  66621. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  66622. this._vertexCount = 0;
  66623. this._syncActiveTargets(true);
  66624. }
  66625. };
  66626. /**
  66627. * Serializes the current manager into a Serialization object.
  66628. * Returns the serialized object.
  66629. */
  66630. MorphTargetManager.prototype.serialize = function () {
  66631. var serializationObject = {};
  66632. serializationObject.id = this.uniqueId;
  66633. serializationObject.targets = [];
  66634. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  66635. var target = _a[_i];
  66636. serializationObject.targets.push(target.serialize());
  66637. }
  66638. return serializationObject;
  66639. };
  66640. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  66641. this._syncActiveTargets(needUpdate);
  66642. };
  66643. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  66644. var influenceCount = 0;
  66645. this._activeTargets.reset();
  66646. this._supportsNormals = true;
  66647. this._supportsTangents = true;
  66648. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  66649. var target = _a[_i];
  66650. if (target.influence > 0) {
  66651. this._activeTargets.push(target);
  66652. this._tempInfluences[influenceCount++] = target.influence;
  66653. this._supportsNormals = this._supportsNormals && target.hasNormals;
  66654. this._supportsTangents = this._supportsTangents && target.hasTangents;
  66655. if (this._vertexCount === 0) {
  66656. this._vertexCount = target.getPositions().length / 3;
  66657. }
  66658. }
  66659. }
  66660. if (!this._influences || this._influences.length !== influenceCount) {
  66661. this._influences = new Float32Array(influenceCount);
  66662. }
  66663. for (var index = 0; index < influenceCount; index++) {
  66664. this._influences[index] = this._tempInfluences[index];
  66665. }
  66666. if (needUpdate) {
  66667. // Flag meshes as dirty to resync with the active targets
  66668. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  66669. var mesh = _c[_b];
  66670. if (mesh.morphTargetManager === this) {
  66671. mesh._syncGeometryWithMorphTargetManager();
  66672. }
  66673. }
  66674. }
  66675. };
  66676. // Statics
  66677. MorphTargetManager.Parse = function (serializationObject, scene) {
  66678. var result = new MorphTargetManager(scene);
  66679. result._uniqueId = serializationObject.id;
  66680. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  66681. var targetData = _a[_i];
  66682. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  66683. }
  66684. return result;
  66685. };
  66686. return MorphTargetManager;
  66687. }());
  66688. BABYLON.MorphTargetManager = MorphTargetManager;
  66689. })(BABYLON || (BABYLON = {}));
  66690. //# sourceMappingURL=babylon.morphTargetManager.js.map
  66691. var BABYLON;
  66692. (function (BABYLON) {
  66693. var Octree = (function () {
  66694. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  66695. if (maxDepth === void 0) { maxDepth = 2; }
  66696. this.maxDepth = maxDepth;
  66697. this.dynamicContent = new Array();
  66698. this._maxBlockCapacity = maxBlockCapacity || 64;
  66699. this._selectionContent = new BABYLON.SmartArray(1024);
  66700. this._creationFunc = creationFunc;
  66701. }
  66702. // Methods
  66703. Octree.prototype.update = function (worldMin, worldMax, entries) {
  66704. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  66705. };
  66706. Octree.prototype.addMesh = function (entry) {
  66707. for (var index = 0; index < this.blocks.length; index++) {
  66708. var block = this.blocks[index];
  66709. block.addEntry(entry);
  66710. }
  66711. };
  66712. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  66713. this._selectionContent.reset();
  66714. for (var index = 0; index < this.blocks.length; index++) {
  66715. var block = this.blocks[index];
  66716. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  66717. }
  66718. if (allowDuplicate) {
  66719. this._selectionContent.concat(this.dynamicContent);
  66720. }
  66721. else {
  66722. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  66723. }
  66724. return this._selectionContent;
  66725. };
  66726. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  66727. this._selectionContent.reset();
  66728. for (var index = 0; index < this.blocks.length; index++) {
  66729. var block = this.blocks[index];
  66730. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  66731. }
  66732. if (allowDuplicate) {
  66733. this._selectionContent.concat(this.dynamicContent);
  66734. }
  66735. else {
  66736. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  66737. }
  66738. return this._selectionContent;
  66739. };
  66740. Octree.prototype.intersectsRay = function (ray) {
  66741. this._selectionContent.reset();
  66742. for (var index = 0; index < this.blocks.length; index++) {
  66743. var block = this.blocks[index];
  66744. block.intersectsRay(ray, this._selectionContent);
  66745. }
  66746. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  66747. return this._selectionContent;
  66748. };
  66749. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  66750. target.blocks = new Array();
  66751. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  66752. // Segmenting space
  66753. for (var x = 0; x < 2; x++) {
  66754. for (var y = 0; y < 2; y++) {
  66755. for (var z = 0; z < 2; z++) {
  66756. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  66757. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  66758. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  66759. block.addEntries(entries);
  66760. target.blocks.push(block);
  66761. }
  66762. }
  66763. }
  66764. };
  66765. Octree.CreationFuncForMeshes = function (entry, block) {
  66766. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  66767. block.entries.push(entry);
  66768. }
  66769. };
  66770. Octree.CreationFuncForSubMeshes = function (entry, block) {
  66771. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  66772. block.entries.push(entry);
  66773. }
  66774. };
  66775. return Octree;
  66776. }());
  66777. BABYLON.Octree = Octree;
  66778. })(BABYLON || (BABYLON = {}));
  66779. //# sourceMappingURL=babylon.octree.js.map
  66780. var BABYLON;
  66781. (function (BABYLON) {
  66782. var OctreeBlock = (function () {
  66783. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  66784. this.entries = new Array();
  66785. this._boundingVectors = new Array();
  66786. this._capacity = capacity;
  66787. this._depth = depth;
  66788. this._maxDepth = maxDepth;
  66789. this._creationFunc = creationFunc;
  66790. this._minPoint = minPoint;
  66791. this._maxPoint = maxPoint;
  66792. this._boundingVectors.push(minPoint.clone());
  66793. this._boundingVectors.push(maxPoint.clone());
  66794. this._boundingVectors.push(minPoint.clone());
  66795. this._boundingVectors[2].x = maxPoint.x;
  66796. this._boundingVectors.push(minPoint.clone());
  66797. this._boundingVectors[3].y = maxPoint.y;
  66798. this._boundingVectors.push(minPoint.clone());
  66799. this._boundingVectors[4].z = maxPoint.z;
  66800. this._boundingVectors.push(maxPoint.clone());
  66801. this._boundingVectors[5].z = minPoint.z;
  66802. this._boundingVectors.push(maxPoint.clone());
  66803. this._boundingVectors[6].x = minPoint.x;
  66804. this._boundingVectors.push(maxPoint.clone());
  66805. this._boundingVectors[7].y = minPoint.y;
  66806. }
  66807. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  66808. // Property
  66809. get: function () {
  66810. return this._capacity;
  66811. },
  66812. enumerable: true,
  66813. configurable: true
  66814. });
  66815. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  66816. get: function () {
  66817. return this._minPoint;
  66818. },
  66819. enumerable: true,
  66820. configurable: true
  66821. });
  66822. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  66823. get: function () {
  66824. return this._maxPoint;
  66825. },
  66826. enumerable: true,
  66827. configurable: true
  66828. });
  66829. // Methods
  66830. OctreeBlock.prototype.addEntry = function (entry) {
  66831. if (this.blocks) {
  66832. for (var index = 0; index < this.blocks.length; index++) {
  66833. var block = this.blocks[index];
  66834. block.addEntry(entry);
  66835. }
  66836. return;
  66837. }
  66838. this._creationFunc(entry, this);
  66839. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  66840. this.createInnerBlocks();
  66841. }
  66842. };
  66843. OctreeBlock.prototype.addEntries = function (entries) {
  66844. for (var index = 0; index < entries.length; index++) {
  66845. var mesh = entries[index];
  66846. this.addEntry(mesh);
  66847. }
  66848. };
  66849. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  66850. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  66851. if (this.blocks) {
  66852. for (var index = 0; index < this.blocks.length; index++) {
  66853. var block = this.blocks[index];
  66854. block.select(frustumPlanes, selection, allowDuplicate);
  66855. }
  66856. return;
  66857. }
  66858. if (allowDuplicate) {
  66859. selection.concat(this.entries);
  66860. }
  66861. else {
  66862. selection.concatWithNoDuplicate(this.entries);
  66863. }
  66864. }
  66865. };
  66866. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  66867. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  66868. if (this.blocks) {
  66869. for (var index = 0; index < this.blocks.length; index++) {
  66870. var block = this.blocks[index];
  66871. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  66872. }
  66873. return;
  66874. }
  66875. if (allowDuplicate) {
  66876. selection.concat(this.entries);
  66877. }
  66878. else {
  66879. selection.concatWithNoDuplicate(this.entries);
  66880. }
  66881. }
  66882. };
  66883. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  66884. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  66885. if (this.blocks) {
  66886. for (var index = 0; index < this.blocks.length; index++) {
  66887. var block = this.blocks[index];
  66888. block.intersectsRay(ray, selection);
  66889. }
  66890. return;
  66891. }
  66892. selection.concatWithNoDuplicate(this.entries);
  66893. }
  66894. };
  66895. OctreeBlock.prototype.createInnerBlocks = function () {
  66896. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  66897. };
  66898. return OctreeBlock;
  66899. }());
  66900. BABYLON.OctreeBlock = OctreeBlock;
  66901. })(BABYLON || (BABYLON = {}));
  66902. //# sourceMappingURL=babylon.octreeBlock.js.map
  66903. var BABYLON;
  66904. (function (BABYLON) {
  66905. var SIMDVector3 = (function () {
  66906. function SIMDVector3() {
  66907. }
  66908. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  66909. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  66910. };
  66911. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  66912. var m = transformation.m;
  66913. var m0 = SIMD.Float32x4.load(m, 0);
  66914. var m1 = SIMD.Float32x4.load(m, 4);
  66915. var m2 = SIMD.Float32x4.load(m, 8);
  66916. var m3 = SIMD.Float32x4.load(m, 12);
  66917. 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));
  66918. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  66919. result.x = SIMD.Float32x4.extractLane(r, 0);
  66920. result.y = SIMD.Float32x4.extractLane(r, 1);
  66921. result.z = SIMD.Float32x4.extractLane(r, 2);
  66922. };
  66923. return SIMDVector3;
  66924. }());
  66925. var SIMDMatrix = (function () {
  66926. function SIMDMatrix() {
  66927. }
  66928. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  66929. var tm = this.m;
  66930. var om = other.m;
  66931. var m0 = SIMD.Float32x4.load(om, 0);
  66932. var m1 = SIMD.Float32x4.load(om, 4);
  66933. var m2 = SIMD.Float32x4.load(om, 8);
  66934. var m3 = SIMD.Float32x4.load(om, 12);
  66935. for (var i = 0; i < 16; i += 4) {
  66936. 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)))));
  66937. }
  66938. return this;
  66939. };
  66940. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  66941. var src = this.m;
  66942. var dest = other.m;
  66943. // Load the 4 rows
  66944. var src0 = SIMD.Float32x4.load(src, 0);
  66945. var src1 = SIMD.Float32x4.load(src, 4);
  66946. var src2 = SIMD.Float32x4.load(src, 8);
  66947. var src3 = SIMD.Float32x4.load(src, 12);
  66948. // Transpose the source matrix. Sort of. Not a true transpose operation
  66949. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  66950. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  66951. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  66952. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  66953. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  66954. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  66955. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  66956. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  66957. // This is a true transposition, but it will lead to an incorrect result
  66958. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  66959. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  66960. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  66961. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  66962. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  66963. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  66964. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  66965. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  66966. // ----
  66967. tmp1 = SIMD.Float32x4.mul(row2, row3);
  66968. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  66969. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  66970. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  66971. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  66972. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  66973. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  66974. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  66975. // ----
  66976. tmp1 = SIMD.Float32x4.mul(row1, row2);
  66977. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  66978. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  66979. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  66980. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  66981. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  66982. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  66983. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  66984. // ----
  66985. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  66986. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  66987. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  66988. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  66989. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  66990. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  66991. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  66992. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  66993. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  66994. // ----
  66995. tmp1 = SIMD.Float32x4.mul(row0, row1);
  66996. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  66997. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  66998. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  66999. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  67000. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  67001. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  67002. // ----
  67003. tmp1 = SIMD.Float32x4.mul(row0, row3);
  67004. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  67005. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  67006. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  67007. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  67008. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  67009. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  67010. // ----
  67011. tmp1 = SIMD.Float32x4.mul(row0, row2);
  67012. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  67013. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  67014. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  67015. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  67016. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  67017. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  67018. // Compute determinant
  67019. var det = SIMD.Float32x4.mul(row0, minor0);
  67020. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  67021. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  67022. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  67023. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  67024. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  67025. // These shuffles aren't necessary if the faulty transposition is done
  67026. // up at the top of this function.
  67027. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  67028. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  67029. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  67030. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  67031. // Compute final values by multiplying with 1/det
  67032. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  67033. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  67034. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  67035. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  67036. return this;
  67037. };
  67038. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  67039. var out = result.m;
  67040. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  67041. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  67042. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  67043. // cc.kmVec3Subtract(f, pCenter, pEye);
  67044. var f = SIMD.Float32x4.sub(center, eye);
  67045. // cc.kmVec3Normalize(f, f);
  67046. var tmp = SIMD.Float32x4.mul(f, f);
  67047. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  67048. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  67049. // cc.kmVec3Assign(up, pUp);
  67050. // cc.kmVec3Normalize(up, up);
  67051. tmp = SIMD.Float32x4.mul(up, up);
  67052. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  67053. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  67054. // cc.kmVec3Cross(s, f, up);
  67055. 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)));
  67056. // cc.kmVec3Normalize(s, s);
  67057. tmp = SIMD.Float32x4.mul(s, s);
  67058. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  67059. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  67060. // cc.kmVec3Cross(u, s, f);
  67061. 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)));
  67062. // cc.kmVec3Normalize(s, s);
  67063. tmp = SIMD.Float32x4.mul(s, s);
  67064. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  67065. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  67066. var zero = SIMD.Float32x4.splat(0.0);
  67067. s = SIMD.Float32x4.neg(s);
  67068. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  67069. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  67070. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  67071. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  67072. 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);
  67073. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  67074. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  67075. 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)))));
  67076. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  67077. 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)))));
  67078. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  67079. 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)))));
  67080. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  67081. 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)))));
  67082. };
  67083. return SIMDMatrix;
  67084. }());
  67085. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  67086. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  67087. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  67088. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  67089. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  67090. var SIMDHelper = (function () {
  67091. function SIMDHelper() {
  67092. }
  67093. Object.defineProperty(SIMDHelper, "IsEnabled", {
  67094. get: function () {
  67095. return SIMDHelper._isEnabled;
  67096. },
  67097. enumerable: true,
  67098. configurable: true
  67099. });
  67100. SIMDHelper.DisableSIMD = function () {
  67101. // Replace functions
  67102. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  67103. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  67104. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  67105. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  67106. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  67107. SIMDHelper._isEnabled = false;
  67108. };
  67109. SIMDHelper.EnableSIMD = function () {
  67110. if (self.SIMD === undefined) {
  67111. return;
  67112. }
  67113. // check if polyfills needed
  67114. if (!self.Math.fround) {
  67115. self.Math.fround = (function (array) { return function (x) {
  67116. return array[0] = x, array[0];
  67117. }; })(new Float32Array(1));
  67118. }
  67119. if (!self.Math.imul) {
  67120. self.Math.imul = function (a, b) {
  67121. var ah = (a >>> 16) & 0xffff;
  67122. var al = a & 0xffff;
  67123. var bh = (b >>> 16) & 0xffff;
  67124. var bl = b & 0xffff;
  67125. // the shift by 0 fixes the sign on the high part
  67126. // the final |0 converts the unsigned value into a signed value
  67127. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  67128. };
  67129. }
  67130. // Replace functions
  67131. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  67132. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  67133. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  67134. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  67135. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  67136. SIMDHelper._isEnabled = true;
  67137. };
  67138. SIMDHelper._isEnabled = false;
  67139. return SIMDHelper;
  67140. }());
  67141. BABYLON.SIMDHelper = SIMDHelper;
  67142. })(BABYLON || (BABYLON = {}));
  67143. //# sourceMappingURL=babylon.math.SIMD.js.map
  67144. var BABYLON;
  67145. (function (BABYLON) {
  67146. var VRDistortionCorrectionPostProcess = (function (_super) {
  67147. __extends(VRDistortionCorrectionPostProcess, _super);
  67148. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  67149. var _this = _super.call(this, name, "vrDistortionCorrection", [
  67150. 'LensCenter',
  67151. 'Scale',
  67152. 'ScaleIn',
  67153. 'HmdWarpParam'
  67154. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  67155. _this._isRightEye = isRightEye;
  67156. _this._distortionFactors = vrMetrics.distortionK;
  67157. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  67158. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  67159. _this.adaptScaleToCurrentViewport = true;
  67160. _this.onSizeChangedObservable.add(function () {
  67161. _this.aspectRatio = _this.width * .5 / _this.height;
  67162. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  67163. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  67164. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  67165. });
  67166. _this.onApplyObservable.add(function (effect) {
  67167. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  67168. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  67169. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  67170. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  67171. });
  67172. return _this;
  67173. }
  67174. return VRDistortionCorrectionPostProcess;
  67175. }(BABYLON.PostProcess));
  67176. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  67177. })(BABYLON || (BABYLON = {}));
  67178. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  67179. var BABYLON;
  67180. (function (BABYLON) {
  67181. var AnaglyphPostProcess = (function (_super) {
  67182. __extends(AnaglyphPostProcess, _super);
  67183. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  67184. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  67185. _this._passedProcess = rigCameras[0]._rigPostProcess;
  67186. _this.onApplyObservable.add(function (effect) {
  67187. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  67188. });
  67189. return _this;
  67190. }
  67191. return AnaglyphPostProcess;
  67192. }(BABYLON.PostProcess));
  67193. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  67194. })(BABYLON || (BABYLON = {}));
  67195. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  67196. var BABYLON;
  67197. (function (BABYLON) {
  67198. var StereoscopicInterlacePostProcess = (function (_super) {
  67199. __extends(StereoscopicInterlacePostProcess, _super);
  67200. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  67201. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  67202. _this._passedProcess = rigCameras[0]._rigPostProcess;
  67203. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  67204. _this.onSizeChangedObservable.add(function () {
  67205. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  67206. });
  67207. _this.onApplyObservable.add(function (effect) {
  67208. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  67209. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  67210. });
  67211. return _this;
  67212. }
  67213. return StereoscopicInterlacePostProcess;
  67214. }(BABYLON.PostProcess));
  67215. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  67216. })(BABYLON || (BABYLON = {}));
  67217. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  67218. var BABYLON;
  67219. (function (BABYLON) {
  67220. var FreeCameraDeviceOrientationInput = (function () {
  67221. function FreeCameraDeviceOrientationInput() {
  67222. var _this = this;
  67223. this._screenOrientationAngle = 0;
  67224. this._screenQuaternion = new BABYLON.Quaternion();
  67225. this._alpha = 0;
  67226. this._beta = 0;
  67227. this._gamma = 0;
  67228. this._orientationChanged = function () {
  67229. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  67230. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  67231. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  67232. };
  67233. this._deviceOrientation = function (evt) {
  67234. _this._alpha = evt.alpha;
  67235. _this._beta = evt.beta;
  67236. _this._gamma = evt.gamma;
  67237. };
  67238. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  67239. this._orientationChanged();
  67240. }
  67241. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  67242. get: function () {
  67243. return this._camera;
  67244. },
  67245. set: function (camera) {
  67246. this._camera = camera;
  67247. if (this._camera != null && !this._camera.rotationQuaternion) {
  67248. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  67249. }
  67250. },
  67251. enumerable: true,
  67252. configurable: true
  67253. });
  67254. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  67255. window.addEventListener("orientationchange", this._orientationChanged);
  67256. window.addEventListener("deviceorientation", this._deviceOrientation);
  67257. //In certain cases, the attach control is called AFTER orientation was changed,
  67258. //So this is needed.
  67259. this._orientationChanged();
  67260. };
  67261. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  67262. window.removeEventListener("orientationchange", this._orientationChanged);
  67263. window.removeEventListener("deviceorientation", this._deviceOrientation);
  67264. };
  67265. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  67266. //if no device orientation provided, don't update the rotation.
  67267. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  67268. if (!this._alpha)
  67269. return;
  67270. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  67271. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  67272. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  67273. //Mirror on XY Plane
  67274. this._camera.rotationQuaternion.z *= -1;
  67275. this._camera.rotationQuaternion.w *= -1;
  67276. };
  67277. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  67278. return "FreeCameraDeviceOrientationInput";
  67279. };
  67280. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  67281. return "deviceOrientation";
  67282. };
  67283. return FreeCameraDeviceOrientationInput;
  67284. }());
  67285. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  67286. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  67287. })(BABYLON || (BABYLON = {}));
  67288. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  67289. var BABYLON;
  67290. (function (BABYLON) {
  67291. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  67292. function ArcRotateCameraVRDeviceOrientationInput() {
  67293. this.alphaCorrection = 1;
  67294. this.betaCorrection = 1;
  67295. this.gammaCorrection = 1;
  67296. this._alpha = 0;
  67297. this._beta = 0;
  67298. this._gamma = 0;
  67299. this._dirty = false;
  67300. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  67301. }
  67302. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  67303. this.camera.attachControl(element, noPreventDefault);
  67304. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  67305. };
  67306. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  67307. var camera = this.camera;
  67308. this._alpha = +evt.alpha | 0;
  67309. this._beta = +evt.beta | 0;
  67310. this._gamma = +evt.gamma | 0;
  67311. this._dirty = true;
  67312. };
  67313. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  67314. if (this._dirty) {
  67315. this._dirty = false;
  67316. if (this._gamma < 0) {
  67317. this._gamma = 180 + this._gamma;
  67318. }
  67319. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  67320. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  67321. }
  67322. };
  67323. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  67324. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  67325. };
  67326. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  67327. return "ArcRotateCameraVRDeviceOrientationInput";
  67328. };
  67329. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  67330. return "VRDeviceOrientation";
  67331. };
  67332. return ArcRotateCameraVRDeviceOrientationInput;
  67333. }());
  67334. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  67335. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  67336. })(BABYLON || (BABYLON = {}));
  67337. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  67338. var BABYLON;
  67339. (function (BABYLON) {
  67340. var VRCameraMetrics = (function () {
  67341. function VRCameraMetrics() {
  67342. this.compensateDistortion = true;
  67343. }
  67344. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  67345. get: function () {
  67346. return this.hResolution / (2 * this.vResolution);
  67347. },
  67348. enumerable: true,
  67349. configurable: true
  67350. });
  67351. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  67352. get: function () {
  67353. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  67354. },
  67355. enumerable: true,
  67356. configurable: true
  67357. });
  67358. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  67359. get: function () {
  67360. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  67361. var h = (4 * meters) / this.hScreenSize;
  67362. return BABYLON.Matrix.Translation(h, 0, 0);
  67363. },
  67364. enumerable: true,
  67365. configurable: true
  67366. });
  67367. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  67368. get: function () {
  67369. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  67370. var h = (4 * meters) / this.hScreenSize;
  67371. return BABYLON.Matrix.Translation(-h, 0, 0);
  67372. },
  67373. enumerable: true,
  67374. configurable: true
  67375. });
  67376. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  67377. get: function () {
  67378. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  67379. },
  67380. enumerable: true,
  67381. configurable: true
  67382. });
  67383. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  67384. get: function () {
  67385. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  67386. },
  67387. enumerable: true,
  67388. configurable: true
  67389. });
  67390. VRCameraMetrics.GetDefault = function () {
  67391. var result = new VRCameraMetrics();
  67392. result.hResolution = 1280;
  67393. result.vResolution = 800;
  67394. result.hScreenSize = 0.149759993;
  67395. result.vScreenSize = 0.0935999975;
  67396. result.vScreenCenter = 0.0467999987;
  67397. result.eyeToScreenDistance = 0.0410000011;
  67398. result.lensSeparationDistance = 0.0635000020;
  67399. result.interpupillaryDistance = 0.0640000030;
  67400. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  67401. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  67402. result.postProcessScaleFactor = 1.714605507808412;
  67403. result.lensCenterOffset = 0.151976421;
  67404. return result;
  67405. };
  67406. return VRCameraMetrics;
  67407. }());
  67408. BABYLON.VRCameraMetrics = VRCameraMetrics;
  67409. })(BABYLON || (BABYLON = {}));
  67410. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  67411. var BABYLON;
  67412. (function (BABYLON) {
  67413. var WebVRFreeCamera = (function (_super) {
  67414. __extends(WebVRFreeCamera, _super);
  67415. function WebVRFreeCamera(name, position, scene, webVROptions) {
  67416. if (webVROptions === void 0) { webVROptions = {}; }
  67417. var _this = _super.call(this, name, position, scene) || this;
  67418. _this.webVROptions = webVROptions;
  67419. _this._vrDevice = null;
  67420. _this.rawPose = null;
  67421. _this._specsVersion = "1.1";
  67422. _this._attached = false;
  67423. _this._positionOffset = BABYLON.Vector3.Zero();
  67424. _this._descendants = [];
  67425. _this.devicePosition = BABYLON.Vector3.Zero();
  67426. _this.deviceScaleFactor = 1;
  67427. _this.controllers = [];
  67428. _this.onControllersAttachedObservable = new BABYLON.Observable();
  67429. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  67430. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  67431. _this.minZ = 0.1;
  67432. //legacy support - the compensation boolean was removed.
  67433. if (arguments.length === 5) {
  67434. _this.webVROptions = arguments[4];
  67435. }
  67436. // default webVR options
  67437. if (_this.webVROptions.trackPosition == undefined) {
  67438. _this.webVROptions.trackPosition = true;
  67439. }
  67440. if (_this.webVROptions.controllerMeshes == undefined) {
  67441. _this.webVROptions.controllerMeshes = true;
  67442. }
  67443. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  67444. _this.webVROptions.defaultLightingOnControllers = true;
  67445. }
  67446. _this.rotationQuaternion = new BABYLON.Quaternion();
  67447. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  67448. if (_this.webVROptions && _this.webVROptions.positionScale) {
  67449. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  67450. }
  67451. //enable VR
  67452. var engine = _this.getEngine();
  67453. _this._onVREnabled = function (success) { if (success) {
  67454. _this.initControllers();
  67455. } };
  67456. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  67457. engine.initWebVR().add(function (event) {
  67458. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  67459. return;
  67460. }
  67461. _this._vrDevice = event.vrDisplay;
  67462. //reset the rig parameters.
  67463. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  67464. if (_this._attached) {
  67465. _this.getEngine().enableVR();
  67466. }
  67467. });
  67468. if (typeof (VRFrameData) !== "undefined")
  67469. _this._frameData = new VRFrameData();
  67470. /**
  67471. * The idea behind the following lines:
  67472. * objects that have the camera as parent should actually have the rig cameras as a parent.
  67473. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  67474. * the second will not show it correctly.
  67475. *
  67476. * To solve this - each object that has the camera as parent will be added to a protected array.
  67477. * When the rig camera renders, it will take this array and set all of those to be its children.
  67478. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  67479. * Amazing!
  67480. */
  67481. scene.onBeforeCameraRenderObservable.add(function (camera) {
  67482. if (camera.parent === _this && _this.rigParenting) {
  67483. _this._descendants = _this.getDescendants(true, function (n) {
  67484. // don't take the cameras or the controllers!
  67485. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  67486. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  67487. return !isController && !isRigCamera;
  67488. });
  67489. _this._descendants.forEach(function (node) {
  67490. node.parent = camera;
  67491. });
  67492. }
  67493. });
  67494. scene.onAfterCameraRenderObservable.add(function (camera) {
  67495. if (camera.parent === _this && _this.rigParenting) {
  67496. _this._descendants.forEach(function (node) {
  67497. node.parent = _this;
  67498. });
  67499. }
  67500. });
  67501. return _this;
  67502. }
  67503. WebVRFreeCamera.prototype.dispose = function () {
  67504. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  67505. _super.prototype.dispose.call(this);
  67506. };
  67507. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  67508. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  67509. var gp = _a[_i];
  67510. if (gp.hand === name) {
  67511. return gp;
  67512. }
  67513. }
  67514. return undefined;
  67515. };
  67516. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  67517. get: function () {
  67518. if (!this._leftController) {
  67519. this._leftController = this.getControllerByName("left");
  67520. }
  67521. return this._leftController;
  67522. },
  67523. enumerable: true,
  67524. configurable: true
  67525. });
  67526. ;
  67527. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  67528. get: function () {
  67529. if (!this._rightController) {
  67530. this._rightController = this.getControllerByName("right");
  67531. }
  67532. return this._rightController;
  67533. },
  67534. enumerable: true,
  67535. configurable: true
  67536. });
  67537. ;
  67538. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  67539. if (length === void 0) { length = 100; }
  67540. if (this.leftCamera) {
  67541. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  67542. }
  67543. else {
  67544. return _super.prototype.getForwardRay.call(this, length);
  67545. }
  67546. };
  67547. WebVRFreeCamera.prototype._checkInputs = function () {
  67548. if (this._vrDevice && this._vrDevice.isPresenting) {
  67549. this._vrDevice.getFrameData(this._frameData);
  67550. this.updateFromDevice(this._frameData.pose);
  67551. }
  67552. _super.prototype._checkInputs.call(this);
  67553. };
  67554. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  67555. if (poseData && poseData.orientation) {
  67556. this.rawPose = poseData;
  67557. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  67558. if (this.getScene().useRightHandedSystem) {
  67559. this.deviceRotationQuaternion.z *= -1;
  67560. this.deviceRotationQuaternion.w *= -1;
  67561. }
  67562. if (this.webVROptions.trackPosition && this.rawPose.position) {
  67563. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  67564. if (this.getScene().useRightHandedSystem) {
  67565. this.devicePosition.z *= -1;
  67566. }
  67567. }
  67568. }
  67569. };
  67570. /**
  67571. * WebVR's attach control will start broadcasting frames to the device.
  67572. * Note that in certain browsers (chrome for example) this function must be called
  67573. * within a user-interaction callback. Example:
  67574. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  67575. *
  67576. * @param {HTMLElement} element
  67577. * @param {boolean} [noPreventDefault]
  67578. *
  67579. * @memberOf WebVRFreeCamera
  67580. */
  67581. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  67582. _super.prototype.attachControl.call(this, element, noPreventDefault);
  67583. this._attached = true;
  67584. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  67585. if (this._vrDevice) {
  67586. this.getEngine().enableVR();
  67587. }
  67588. };
  67589. WebVRFreeCamera.prototype.detachControl = function (element) {
  67590. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  67591. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  67592. _super.prototype.detachControl.call(this, element);
  67593. this._attached = false;
  67594. this.getEngine().disableVR();
  67595. };
  67596. WebVRFreeCamera.prototype.getClassName = function () {
  67597. return "WebVRFreeCamera";
  67598. };
  67599. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  67600. //uses the vrDisplay's "resetPose()".
  67601. //pitch and roll won't be affected.
  67602. this._vrDevice.resetPose();
  67603. };
  67604. WebVRFreeCamera.prototype._updateRigCameras = function () {
  67605. var camLeft = this._rigCameras[0];
  67606. var camRight = this._rigCameras[1];
  67607. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  67608. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  67609. camLeft.position.copyFrom(this.devicePosition);
  67610. camRight.position.copyFrom(this.devicePosition);
  67611. };
  67612. /**
  67613. * This function is called by the two RIG cameras.
  67614. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  67615. */
  67616. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  67617. var _this = this;
  67618. //WebVR 1.1
  67619. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  67620. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  67621. if (!this.getScene().useRightHandedSystem) {
  67622. [2, 6, 8, 9, 14].forEach(function (num) {
  67623. _this._webvrViewMatrix.m[num] *= -1;
  67624. });
  67625. }
  67626. // update the camera rotation matrix
  67627. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  67628. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  67629. // Computing target and final matrix
  67630. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  67631. var parentCamera = this._cameraRigParams["parentCamera"];
  67632. // should the view matrix be updated with scale and position offset?
  67633. if (parentCamera.deviceScaleFactor !== 1) {
  67634. this._webvrViewMatrix.invert();
  67635. // scale the position, if set
  67636. if (parentCamera.deviceScaleFactor) {
  67637. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  67638. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  67639. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  67640. }
  67641. this._webvrViewMatrix.invert();
  67642. }
  67643. return this._webvrViewMatrix;
  67644. };
  67645. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  67646. var _this = this;
  67647. var parentCamera = this.parent;
  67648. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  67649. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  67650. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  67651. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  67652. //babylon compatible matrix
  67653. if (!this.getScene().useRightHandedSystem) {
  67654. [8, 9, 10, 11].forEach(function (num) {
  67655. _this._projectionMatrix.m[num] *= -1;
  67656. });
  67657. }
  67658. return this._projectionMatrix;
  67659. };
  67660. WebVRFreeCamera.prototype.initControllers = function () {
  67661. var _this = this;
  67662. this.controllers = [];
  67663. var manager = this.getScene().gamepadManager;
  67664. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  67665. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  67666. var webVrController = gamepad;
  67667. if (webVrController.defaultModel) {
  67668. webVrController.defaultModel.setEnabled(false);
  67669. }
  67670. }
  67671. });
  67672. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  67673. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  67674. var webVrController_1 = gamepad;
  67675. if (_this.webVROptions.controllerMeshes) {
  67676. if (webVrController_1.defaultModel) {
  67677. webVrController_1.defaultModel.setEnabled(true);
  67678. }
  67679. else {
  67680. // Load the meshes
  67681. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  67682. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  67683. if (_this.webVROptions.defaultLightingOnControllers) {
  67684. if (!_this._lightOnControllers) {
  67685. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  67686. }
  67687. var activateLightOnSubMeshes_1 = function (mesh, light) {
  67688. var children = mesh.getChildren();
  67689. if (children.length !== 0) {
  67690. children.forEach(function (mesh) {
  67691. light.includedOnlyMeshes.push(mesh);
  67692. activateLightOnSubMeshes_1(mesh, light);
  67693. });
  67694. }
  67695. };
  67696. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  67697. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  67698. }
  67699. });
  67700. }
  67701. }
  67702. webVrController_1.attachToPoseControlledCamera(_this);
  67703. // since this is async - sanity check. Is the controller already stored?
  67704. if (_this.controllers.indexOf(webVrController_1) === -1) {
  67705. //add to the controllers array
  67706. _this.controllers.push(webVrController_1);
  67707. //did we find enough controllers? Great! let the developer know.
  67708. if (_this.controllers.length >= 2) {
  67709. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  67710. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  67711. // So we're overriding setting left & right manually to be sure
  67712. var firstViveWandDetected = false;
  67713. for (var i = 0; i < _this.controllers.length; i++) {
  67714. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  67715. if (!firstViveWandDetected) {
  67716. firstViveWandDetected = true;
  67717. _this.controllers[i].hand = "left";
  67718. }
  67719. else {
  67720. _this.controllers[i].hand = "right";
  67721. }
  67722. }
  67723. }
  67724. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  67725. }
  67726. }
  67727. }
  67728. });
  67729. };
  67730. return WebVRFreeCamera;
  67731. }(BABYLON.FreeCamera));
  67732. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  67733. })(BABYLON || (BABYLON = {}));
  67734. //# sourceMappingURL=babylon.webVRCamera.js.map
  67735. /// <reference path="babylon.freeCamera.ts" />
  67736. var BABYLON;
  67737. (function (BABYLON) {
  67738. // We're mainly based on the logic defined into the FreeCamera code
  67739. var DeviceOrientationCamera = (function (_super) {
  67740. __extends(DeviceOrientationCamera, _super);
  67741. function DeviceOrientationCamera(name, position, scene) {
  67742. var _this = _super.call(this, name, position, scene) || this;
  67743. _this._quaternionCache = new BABYLON.Quaternion();
  67744. _this.inputs.addDeviceOrientation();
  67745. return _this;
  67746. }
  67747. DeviceOrientationCamera.prototype.getClassName = function () {
  67748. return "DeviceOrientationCamera";
  67749. };
  67750. DeviceOrientationCamera.prototype._checkInputs = function () {
  67751. _super.prototype._checkInputs.call(this);
  67752. this._quaternionCache.copyFrom(this.rotationQuaternion);
  67753. if (this._initialQuaternion) {
  67754. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  67755. }
  67756. };
  67757. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  67758. var _this = this;
  67759. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  67760. //can only work if this camera has a rotation quaternion already.
  67761. if (!this.rotationQuaternion)
  67762. return;
  67763. if (!this._initialQuaternion) {
  67764. this._initialQuaternion = new BABYLON.Quaternion();
  67765. }
  67766. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  67767. ['x', 'y', 'z'].forEach(function (axisName) {
  67768. if (!axis[axisName]) {
  67769. _this._initialQuaternion[axisName] = 0;
  67770. }
  67771. else {
  67772. _this._initialQuaternion[axisName] *= -1;
  67773. }
  67774. });
  67775. this._initialQuaternion.normalize();
  67776. //force rotation update
  67777. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  67778. };
  67779. return DeviceOrientationCamera;
  67780. }(BABYLON.FreeCamera));
  67781. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  67782. })(BABYLON || (BABYLON = {}));
  67783. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  67784. var BABYLON;
  67785. (function (BABYLON) {
  67786. var VRDeviceOrientationFreeCamera = (function (_super) {
  67787. __extends(VRDeviceOrientationFreeCamera, _super);
  67788. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  67789. if (compensateDistortion === void 0) { compensateDistortion = true; }
  67790. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  67791. var _this = _super.call(this, name, position, scene) || this;
  67792. vrCameraMetrics.compensateDistortion = compensateDistortion;
  67793. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  67794. return _this;
  67795. }
  67796. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  67797. return "VRDeviceOrientationFreeCamera";
  67798. };
  67799. return VRDeviceOrientationFreeCamera;
  67800. }(BABYLON.DeviceOrientationCamera));
  67801. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  67802. var VRDeviceOrientationGamepadCamera = (function (_super) {
  67803. __extends(VRDeviceOrientationGamepadCamera, _super);
  67804. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  67805. if (compensateDistortion === void 0) { compensateDistortion = true; }
  67806. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  67807. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  67808. _this.inputs.addGamepad();
  67809. return _this;
  67810. }
  67811. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  67812. return "VRDeviceOrientationGamepadCamera";
  67813. };
  67814. return VRDeviceOrientationGamepadCamera;
  67815. }(VRDeviceOrientationFreeCamera));
  67816. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  67817. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  67818. __extends(VRDeviceOrientationArcRotateCamera, _super);
  67819. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  67820. if (compensateDistortion === void 0) { compensateDistortion = true; }
  67821. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  67822. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  67823. vrCameraMetrics.compensateDistortion = compensateDistortion;
  67824. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  67825. _this.inputs.addVRDeviceOrientation();
  67826. return _this;
  67827. }
  67828. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  67829. return "VRDeviceOrientationArcRotateCamera";
  67830. };
  67831. return VRDeviceOrientationArcRotateCamera;
  67832. }(BABYLON.ArcRotateCamera));
  67833. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  67834. })(BABYLON || (BABYLON = {}));
  67835. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  67836. /// <reference path="babylon.freeCamera.ts" />
  67837. /// <reference path="babylon.arcRotateCamera.ts" />
  67838. /// <reference path="babylon.gamepadCamera.ts" />
  67839. /// <reference path="babylon.universalCamera.ts" />
  67840. var BABYLON;
  67841. (function (BABYLON) {
  67842. var AnaglyphFreeCamera = (function (_super) {
  67843. __extends(AnaglyphFreeCamera, _super);
  67844. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  67845. var _this = _super.call(this, name, position, scene) || this;
  67846. _this.interaxialDistance = interaxialDistance;
  67847. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  67848. return _this;
  67849. }
  67850. AnaglyphFreeCamera.prototype.getClassName = function () {
  67851. return "AnaglyphFreeCamera";
  67852. };
  67853. return AnaglyphFreeCamera;
  67854. }(BABYLON.FreeCamera));
  67855. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  67856. var AnaglyphArcRotateCamera = (function (_super) {
  67857. __extends(AnaglyphArcRotateCamera, _super);
  67858. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  67859. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  67860. _this.interaxialDistance = interaxialDistance;
  67861. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  67862. return _this;
  67863. }
  67864. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  67865. return "AnaglyphArcRotateCamera";
  67866. };
  67867. return AnaglyphArcRotateCamera;
  67868. }(BABYLON.ArcRotateCamera));
  67869. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  67870. var AnaglyphGamepadCamera = (function (_super) {
  67871. __extends(AnaglyphGamepadCamera, _super);
  67872. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  67873. var _this = _super.call(this, name, position, scene) || this;
  67874. _this.interaxialDistance = interaxialDistance;
  67875. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  67876. return _this;
  67877. }
  67878. AnaglyphGamepadCamera.prototype.getClassName = function () {
  67879. return "AnaglyphGamepadCamera";
  67880. };
  67881. return AnaglyphGamepadCamera;
  67882. }(BABYLON.GamepadCamera));
  67883. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  67884. var AnaglyphUniversalCamera = (function (_super) {
  67885. __extends(AnaglyphUniversalCamera, _super);
  67886. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  67887. var _this = _super.call(this, name, position, scene) || this;
  67888. _this.interaxialDistance = interaxialDistance;
  67889. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  67890. return _this;
  67891. }
  67892. AnaglyphUniversalCamera.prototype.getClassName = function () {
  67893. return "AnaglyphUniversalCamera";
  67894. };
  67895. return AnaglyphUniversalCamera;
  67896. }(BABYLON.UniversalCamera));
  67897. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  67898. var StereoscopicFreeCamera = (function (_super) {
  67899. __extends(StereoscopicFreeCamera, _super);
  67900. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  67901. var _this = _super.call(this, name, position, scene) || this;
  67902. _this.interaxialDistance = interaxialDistance;
  67903. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  67904. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  67905. return _this;
  67906. }
  67907. StereoscopicFreeCamera.prototype.getClassName = function () {
  67908. return "StereoscopicFreeCamera";
  67909. };
  67910. return StereoscopicFreeCamera;
  67911. }(BABYLON.FreeCamera));
  67912. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  67913. var StereoscopicArcRotateCamera = (function (_super) {
  67914. __extends(StereoscopicArcRotateCamera, _super);
  67915. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  67916. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  67917. _this.interaxialDistance = interaxialDistance;
  67918. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  67919. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  67920. return _this;
  67921. }
  67922. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  67923. return "StereoscopicArcRotateCamera";
  67924. };
  67925. return StereoscopicArcRotateCamera;
  67926. }(BABYLON.ArcRotateCamera));
  67927. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  67928. var StereoscopicGamepadCamera = (function (_super) {
  67929. __extends(StereoscopicGamepadCamera, _super);
  67930. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  67931. var _this = _super.call(this, name, position, scene) || this;
  67932. _this.interaxialDistance = interaxialDistance;
  67933. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  67934. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  67935. return _this;
  67936. }
  67937. StereoscopicGamepadCamera.prototype.getClassName = function () {
  67938. return "StereoscopicGamepadCamera";
  67939. };
  67940. return StereoscopicGamepadCamera;
  67941. }(BABYLON.GamepadCamera));
  67942. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  67943. var StereoscopicUniversalCamera = (function (_super) {
  67944. __extends(StereoscopicUniversalCamera, _super);
  67945. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  67946. var _this = _super.call(this, name, position, scene) || this;
  67947. _this.interaxialDistance = interaxialDistance;
  67948. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  67949. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  67950. return _this;
  67951. }
  67952. StereoscopicUniversalCamera.prototype.getClassName = function () {
  67953. return "StereoscopicUniversalCamera";
  67954. };
  67955. return StereoscopicUniversalCamera;
  67956. }(BABYLON.UniversalCamera));
  67957. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  67958. })(BABYLON || (BABYLON = {}));
  67959. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  67960. var BABYLON;
  67961. (function (BABYLON) {
  67962. var VRExperienceHelper = (function () {
  67963. function VRExperienceHelper(scene, webVROptions) {
  67964. if (webVROptions === void 0) { webVROptions = {}; }
  67965. var _this = this;
  67966. this.webVROptions = webVROptions;
  67967. // Can the system support WebVR, even if a headset isn't plugged in?
  67968. this._webVRsupported = false;
  67969. // If WebVR is supported, is a headset plugged in and are we ready to present?
  67970. this._webVRready = false;
  67971. // Are we waiting for the requestPresent callback to complete?
  67972. this._webVRrequesting = false;
  67973. // Are we presenting to the headset right now?
  67974. this._webVRpresenting = false;
  67975. // Are we presenting in the fullscreen fallback?
  67976. this._fullscreenVRpresenting = false;
  67977. this._scene = scene;
  67978. if (!this._scene.activeCamera) {
  67979. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  67980. }
  67981. else {
  67982. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  67983. if (scene.activeCamera.rotation) {
  67984. this._deviceOrientationCamera.rotation = scene.activeCamera.rotation.clone();
  67985. }
  67986. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  67987. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  67988. }
  67989. this._scene.activeCamera = this._deviceOrientationCamera;
  67990. this._position = this._scene.activeCamera.position;
  67991. this._canvas = scene.getEngine().getRenderingCanvas();
  67992. this._scene.activeCamera.attachControl(this._canvas);
  67993. this._btnVR = document.createElement("BUTTON");
  67994. this._btnVR.className = "babylonVRicon";
  67995. this._btnVR.id = "babylonVRiconbtn";
  67996. this._btnVR.title = "Click to switch to VR";
  67997. 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) }";
  67998. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  67999. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  68000. // css += ".babylonVRicon.vrdisplaysupported { }";
  68001. // css += ".babylonVRicon.vrdisplayready { }";
  68002. // css += ".babylonVRicon.vrdisplayrequesting { }";
  68003. var style = document.createElement('style');
  68004. style.appendChild(document.createTextNode(css));
  68005. document.getElementsByTagName('head')[0].appendChild(style);
  68006. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  68007. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  68008. this._btnVR.addEventListener("click", function () {
  68009. _this.enterVR();
  68010. });
  68011. window.addEventListener("resize", function () {
  68012. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  68013. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  68014. if (_this._fullscreenVRpresenting && _this._webVRready) {
  68015. _this.exitVR();
  68016. }
  68017. });
  68018. document.addEventListener("fullscreenchange", function () { _this._onFullscreenChange(); }, false);
  68019. document.addEventListener("mozfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  68020. document.addEventListener("webkitfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  68021. document.addEventListener("msfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  68022. document.body.appendChild(this._btnVR);
  68023. // Exiting VR mode using 'ESC' key on desktop
  68024. this._onKeyDown = function (event) {
  68025. if (event.keyCode === 27 && _this.isInVRMode()) {
  68026. _this.exitVR();
  68027. }
  68028. };
  68029. document.addEventListener("keydown", this._onKeyDown);
  68030. // Exiting VR mode double tapping the touch screen
  68031. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  68032. if (_this.isInVRMode()) {
  68033. _this.exitVR();
  68034. if (_this._fullscreenVRpresenting) {
  68035. _this._scene.getEngine().switchFullscreen(true);
  68036. }
  68037. }
  68038. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  68039. // Listen for WebVR display changes
  68040. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  68041. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  68042. this._onVRRequestPresentStart = function () {
  68043. _this._webVRrequesting = true;
  68044. _this.updateButtonVisibility();
  68045. };
  68046. this._onVRRequestPresentComplete = function (success) {
  68047. _this._webVRrequesting = false;
  68048. _this.updateButtonVisibility();
  68049. };
  68050. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  68051. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  68052. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  68053. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  68054. // Create the cameras
  68055. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  68056. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  68057. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  68058. this.updateButtonVisibility();
  68059. }
  68060. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  68061. if (this.onControllerMeshLoaded) {
  68062. this.onControllerMeshLoaded(webVRController);
  68063. }
  68064. };
  68065. VRExperienceHelper.prototype._onFullscreenChange = function () {
  68066. if (document.fullscreen !== undefined) {
  68067. this._fullscreenVRpresenting = document.fullscreen;
  68068. }
  68069. else if (document.mozFullScreen !== undefined) {
  68070. this._fullscreenVRpresenting = document.mozFullScreen;
  68071. }
  68072. else if (document.webkitIsFullScreen !== undefined) {
  68073. this._fullscreenVRpresenting = document.webkitIsFullScreen;
  68074. }
  68075. else if (document.msIsFullScreen !== undefined) {
  68076. this._fullscreenVRpresenting = document.msIsFullScreen;
  68077. }
  68078. if (!this._fullscreenVRpresenting) {
  68079. this.exitVR();
  68080. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  68081. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  68082. }
  68083. };
  68084. VRExperienceHelper.prototype.isInVRMode = function () {
  68085. return this._webVRpresenting || this._fullscreenVRpresenting;
  68086. };
  68087. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  68088. var vrDisplay = this._scene.getEngine().getVRDevice();
  68089. if (vrDisplay) {
  68090. var wasPresenting = this._webVRpresenting;
  68091. // A VR display is connected
  68092. this._webVRpresenting = vrDisplay.isPresenting;
  68093. if (wasPresenting && !this._webVRpresenting)
  68094. this.exitVR();
  68095. }
  68096. else {
  68097. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  68098. }
  68099. this.updateButtonVisibility();
  68100. };
  68101. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  68102. this._webVRsupported = eventArgs.vrSupported;
  68103. this._webVRready = !!eventArgs.vrDisplay;
  68104. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  68105. this.updateButtonVisibility();
  68106. };
  68107. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  68108. if (!this._btnVR) {
  68109. return;
  68110. }
  68111. this._btnVR.className = "babylonVRicon";
  68112. if (this.isInVRMode()) {
  68113. this._btnVR.className += " vrdisplaypresenting";
  68114. }
  68115. else {
  68116. if (this._webVRready)
  68117. this._btnVR.className += " vrdisplayready";
  68118. if (this._webVRsupported)
  68119. this._btnVR.className += " vrdisplaysupported";
  68120. if (this._webVRrequesting)
  68121. this._btnVR.className += " vrdisplayrequesting";
  68122. }
  68123. };
  68124. /**
  68125. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  68126. * Otherwise, will use the fullscreen API.
  68127. */
  68128. VRExperienceHelper.prototype.enterVR = function () {
  68129. if (this.onEnteringVR) {
  68130. this.onEnteringVR();
  68131. }
  68132. if (this._webVRrequesting)
  68133. return;
  68134. // If WebVR is supported and a headset is connected
  68135. if (this._webVRready) {
  68136. if (!this._webVRpresenting) {
  68137. this._webVRCamera.position = this._position;
  68138. this._scene.activeCamera = this._webVRCamera;
  68139. }
  68140. }
  68141. else {
  68142. this._vrDeviceOrientationCamera.position = this._position;
  68143. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  68144. this._scene.getEngine().switchFullscreen(true);
  68145. this.updateButtonVisibility();
  68146. }
  68147. this._scene.activeCamera.attachControl(this._canvas);
  68148. };
  68149. /**
  68150. * Attempt to exit VR, or fullscreen.
  68151. */
  68152. VRExperienceHelper.prototype.exitVR = function () {
  68153. if (this.onExitingVR) {
  68154. this.onExitingVR();
  68155. }
  68156. if (this._webVRpresenting) {
  68157. this._scene.getEngine().disableVR();
  68158. }
  68159. if (this._scene.activeCamera) {
  68160. this._position = this._scene.activeCamera.position;
  68161. }
  68162. this._deviceOrientationCamera.position = this._position;
  68163. this._scene.activeCamera = this._deviceOrientationCamera;
  68164. this._scene.activeCamera.attachControl(this._canvas);
  68165. this.updateButtonVisibility();
  68166. };
  68167. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  68168. get: function () {
  68169. return this._position;
  68170. },
  68171. set: function (value) {
  68172. this._position = value;
  68173. this._scene.activeCamera.position = value;
  68174. },
  68175. enumerable: true,
  68176. configurable: true
  68177. });
  68178. VRExperienceHelper.prototype.dispose = function () {
  68179. if (this.isInVRMode()) {
  68180. this.exitVR();
  68181. }
  68182. this._deviceOrientationCamera.dispose();
  68183. if (this._webVRCamera) {
  68184. this._webVRCamera.dispose();
  68185. }
  68186. if (this._vrDeviceOrientationCamera) {
  68187. this._vrDeviceOrientationCamera.dispose();
  68188. }
  68189. document.body.removeChild(this._btnVR);
  68190. document.removeEventListener("keydown", this._onKeyDown);
  68191. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  68192. };
  68193. VRExperienceHelper.prototype.getClassName = function () {
  68194. return "VRExperienceHelper";
  68195. };
  68196. return VRExperienceHelper;
  68197. }());
  68198. BABYLON.VRExperienceHelper = VRExperienceHelper;
  68199. })(BABYLON || (BABYLON = {}));
  68200. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  68201. // Mainly based on these 2 articles :
  68202. // 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
  68203. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  68204. var BABYLON;
  68205. (function (BABYLON) {
  68206. var JoystickAxis;
  68207. (function (JoystickAxis) {
  68208. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  68209. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  68210. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  68211. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  68212. var VirtualJoystick = (function () {
  68213. function VirtualJoystick(leftJoystick) {
  68214. var _this = this;
  68215. if (leftJoystick) {
  68216. this._leftJoystick = true;
  68217. }
  68218. else {
  68219. this._leftJoystick = false;
  68220. }
  68221. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  68222. VirtualJoystick._globalJoystickIndex++;
  68223. // By default left & right arrow keys are moving the X
  68224. // and up & down keys are moving the Y
  68225. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  68226. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  68227. this.reverseLeftRight = false;
  68228. this.reverseUpDown = false;
  68229. // collections of pointers
  68230. this._touches = new BABYLON.StringDictionary();
  68231. this.deltaPosition = BABYLON.Vector3.Zero();
  68232. this._joystickSensibility = 25;
  68233. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  68234. this._rotationSpeed = 25;
  68235. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  68236. this._rotateOnAxisRelativeToMesh = false;
  68237. this._onResize = function (evt) {
  68238. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  68239. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  68240. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  68241. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  68242. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  68243. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  68244. };
  68245. // injecting a canvas element on top of the canvas 3D game
  68246. if (!VirtualJoystick.vjCanvas) {
  68247. window.addEventListener("resize", this._onResize, false);
  68248. VirtualJoystick.vjCanvas = document.createElement("canvas");
  68249. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  68250. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  68251. VirtualJoystick.vjCanvas.width = window.innerWidth;
  68252. VirtualJoystick.vjCanvas.height = window.innerHeight;
  68253. VirtualJoystick.vjCanvas.style.width = "100%";
  68254. VirtualJoystick.vjCanvas.style.height = "100%";
  68255. VirtualJoystick.vjCanvas.style.position = "absolute";
  68256. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  68257. VirtualJoystick.vjCanvas.style.top = "0px";
  68258. VirtualJoystick.vjCanvas.style.left = "0px";
  68259. VirtualJoystick.vjCanvas.style.zIndex = "5";
  68260. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  68261. // Support for jQuery PEP polyfill
  68262. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  68263. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  68264. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  68265. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  68266. document.body.appendChild(VirtualJoystick.vjCanvas);
  68267. }
  68268. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  68269. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  68270. this.pressed = false;
  68271. // default joystick color
  68272. this._joystickColor = "cyan";
  68273. this._joystickPointerID = -1;
  68274. // current joystick position
  68275. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  68276. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  68277. // origin joystick position
  68278. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  68279. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  68280. this._onPointerDownHandlerRef = function (evt) {
  68281. _this._onPointerDown(evt);
  68282. };
  68283. this._onPointerMoveHandlerRef = function (evt) {
  68284. _this._onPointerMove(evt);
  68285. };
  68286. this._onPointerOutHandlerRef = function (evt) {
  68287. _this._onPointerUp(evt);
  68288. };
  68289. this._onPointerUpHandlerRef = function (evt) {
  68290. _this._onPointerUp(evt);
  68291. };
  68292. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  68293. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  68294. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  68295. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  68296. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  68297. evt.preventDefault(); // Disables system menu
  68298. }, false);
  68299. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  68300. }
  68301. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  68302. this._joystickSensibility = newJoystickSensibility;
  68303. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  68304. };
  68305. VirtualJoystick.prototype._onPointerDown = function (e) {
  68306. var positionOnScreenCondition;
  68307. e.preventDefault();
  68308. if (this._leftJoystick === true) {
  68309. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  68310. }
  68311. else {
  68312. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  68313. }
  68314. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  68315. // First contact will be dedicated to the virtual joystick
  68316. this._joystickPointerID = e.pointerId;
  68317. this._joystickPointerStartPos.x = e.clientX;
  68318. this._joystickPointerStartPos.y = e.clientY;
  68319. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  68320. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  68321. this._deltaJoystickVector.x = 0;
  68322. this._deltaJoystickVector.y = 0;
  68323. this.pressed = true;
  68324. this._touches.add(e.pointerId.toString(), e);
  68325. }
  68326. else {
  68327. // You can only trigger the action buttons with a joystick declared
  68328. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  68329. this._action();
  68330. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  68331. }
  68332. }
  68333. };
  68334. VirtualJoystick.prototype._onPointerMove = function (e) {
  68335. // If the current pointer is the one associated to the joystick (first touch contact)
  68336. if (this._joystickPointerID == e.pointerId) {
  68337. this._joystickPointerPos.x = e.clientX;
  68338. this._joystickPointerPos.y = e.clientY;
  68339. this._deltaJoystickVector = this._joystickPointerPos.clone();
  68340. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  68341. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  68342. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  68343. switch (this._axisTargetedByLeftAndRight) {
  68344. case JoystickAxis.X:
  68345. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  68346. break;
  68347. case JoystickAxis.Y:
  68348. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  68349. break;
  68350. case JoystickAxis.Z:
  68351. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  68352. break;
  68353. }
  68354. var directionUpDown = this.reverseUpDown ? 1 : -1;
  68355. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  68356. switch (this._axisTargetedByUpAndDown) {
  68357. case JoystickAxis.X:
  68358. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  68359. break;
  68360. case JoystickAxis.Y:
  68361. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  68362. break;
  68363. case JoystickAxis.Z:
  68364. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  68365. break;
  68366. }
  68367. }
  68368. else {
  68369. var data = this._touches.get(e.pointerId.toString());
  68370. if (data) {
  68371. data.x = e.clientX;
  68372. data.y = e.clientY;
  68373. }
  68374. }
  68375. };
  68376. VirtualJoystick.prototype._onPointerUp = function (e) {
  68377. if (this._joystickPointerID == e.pointerId) {
  68378. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  68379. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  68380. this._joystickPointerID = -1;
  68381. this.pressed = false;
  68382. }
  68383. else {
  68384. var touch = this._touches.get(e.pointerId.toString());
  68385. if (touch) {
  68386. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  68387. }
  68388. }
  68389. this._deltaJoystickVector.x = 0;
  68390. this._deltaJoystickVector.y = 0;
  68391. this._touches.remove(e.pointerId.toString());
  68392. };
  68393. /**
  68394. * Change the color of the virtual joystick
  68395. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  68396. */
  68397. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  68398. this._joystickColor = newColor;
  68399. };
  68400. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  68401. this._action = action;
  68402. };
  68403. // Define which axis you'd like to control for left & right
  68404. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  68405. switch (axis) {
  68406. case JoystickAxis.X:
  68407. case JoystickAxis.Y:
  68408. case JoystickAxis.Z:
  68409. this._axisTargetedByLeftAndRight = axis;
  68410. break;
  68411. default:
  68412. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  68413. break;
  68414. }
  68415. };
  68416. // Define which axis you'd like to control for up & down
  68417. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  68418. switch (axis) {
  68419. case JoystickAxis.X:
  68420. case JoystickAxis.Y:
  68421. case JoystickAxis.Z:
  68422. this._axisTargetedByUpAndDown = axis;
  68423. break;
  68424. default:
  68425. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  68426. break;
  68427. }
  68428. };
  68429. VirtualJoystick.prototype._clearCanvas = function () {
  68430. if (this._leftJoystick) {
  68431. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  68432. }
  68433. else {
  68434. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  68435. }
  68436. };
  68437. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  68438. var _this = this;
  68439. if (this.pressed) {
  68440. this._touches.forEach(function (key, touch) {
  68441. if (touch.pointerId === _this._joystickPointerID) {
  68442. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  68443. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  68444. VirtualJoystick.vjCanvasContext.beginPath();
  68445. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  68446. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  68447. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  68448. VirtualJoystick.vjCanvasContext.stroke();
  68449. VirtualJoystick.vjCanvasContext.closePath();
  68450. VirtualJoystick.vjCanvasContext.beginPath();
  68451. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  68452. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  68453. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  68454. VirtualJoystick.vjCanvasContext.stroke();
  68455. VirtualJoystick.vjCanvasContext.closePath();
  68456. VirtualJoystick.vjCanvasContext.beginPath();
  68457. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  68458. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  68459. VirtualJoystick.vjCanvasContext.stroke();
  68460. VirtualJoystick.vjCanvasContext.closePath();
  68461. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  68462. }
  68463. else {
  68464. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  68465. VirtualJoystick.vjCanvasContext.beginPath();
  68466. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  68467. VirtualJoystick.vjCanvasContext.beginPath();
  68468. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  68469. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  68470. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  68471. VirtualJoystick.vjCanvasContext.stroke();
  68472. VirtualJoystick.vjCanvasContext.closePath();
  68473. touch.prevX = touch.x;
  68474. touch.prevY = touch.y;
  68475. }
  68476. ;
  68477. });
  68478. }
  68479. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  68480. };
  68481. VirtualJoystick.prototype.releaseCanvas = function () {
  68482. if (VirtualJoystick.vjCanvas) {
  68483. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  68484. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  68485. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  68486. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  68487. window.removeEventListener("resize", this._onResize);
  68488. document.body.removeChild(VirtualJoystick.vjCanvas);
  68489. VirtualJoystick.vjCanvas = null;
  68490. }
  68491. };
  68492. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  68493. VirtualJoystick._globalJoystickIndex = 0;
  68494. return VirtualJoystick;
  68495. }());
  68496. BABYLON.VirtualJoystick = VirtualJoystick;
  68497. })(BABYLON || (BABYLON = {}));
  68498. //# sourceMappingURL=babylon.virtualJoystick.js.map
  68499. var BABYLON;
  68500. (function (BABYLON) {
  68501. // We're mainly based on the logic defined into the FreeCamera code
  68502. var VirtualJoysticksCamera = (function (_super) {
  68503. __extends(VirtualJoysticksCamera, _super);
  68504. function VirtualJoysticksCamera(name, position, scene) {
  68505. var _this = _super.call(this, name, position, scene) || this;
  68506. _this.inputs.addVirtualJoystick();
  68507. return _this;
  68508. }
  68509. VirtualJoysticksCamera.prototype.getClassName = function () {
  68510. return "VirtualJoysticksCamera";
  68511. };
  68512. return VirtualJoysticksCamera;
  68513. }(BABYLON.FreeCamera));
  68514. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  68515. })(BABYLON || (BABYLON = {}));
  68516. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  68517. var BABYLON;
  68518. (function (BABYLON) {
  68519. var FreeCameraVirtualJoystickInput = (function () {
  68520. function FreeCameraVirtualJoystickInput() {
  68521. }
  68522. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  68523. return this._leftjoystick;
  68524. };
  68525. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  68526. return this._rightjoystick;
  68527. };
  68528. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  68529. if (this._leftjoystick) {
  68530. var camera = this.camera;
  68531. var speed = camera._computeLocalCameraSpeed() * 50;
  68532. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  68533. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  68534. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  68535. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  68536. if (!this._leftjoystick.pressed) {
  68537. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  68538. }
  68539. if (!this._rightjoystick.pressed) {
  68540. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  68541. }
  68542. }
  68543. };
  68544. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  68545. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  68546. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  68547. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  68548. this._leftjoystick.setJoystickSensibility(0.15);
  68549. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  68550. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  68551. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  68552. this._rightjoystick.reverseUpDown = true;
  68553. this._rightjoystick.setJoystickSensibility(0.05);
  68554. this._rightjoystick.setJoystickColor("yellow");
  68555. };
  68556. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  68557. this._leftjoystick.releaseCanvas();
  68558. this._rightjoystick.releaseCanvas();
  68559. };
  68560. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  68561. return "FreeCameraVirtualJoystickInput";
  68562. };
  68563. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  68564. return "virtualJoystick";
  68565. };
  68566. return FreeCameraVirtualJoystickInput;
  68567. }());
  68568. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  68569. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  68570. })(BABYLON || (BABYLON = {}));
  68571. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  68572. var BABYLON;
  68573. (function (BABYLON) {
  68574. var SimplificationSettings = (function () {
  68575. function SimplificationSettings(quality, distance, optimizeMesh) {
  68576. this.quality = quality;
  68577. this.distance = distance;
  68578. this.optimizeMesh = optimizeMesh;
  68579. }
  68580. return SimplificationSettings;
  68581. }());
  68582. BABYLON.SimplificationSettings = SimplificationSettings;
  68583. var SimplificationQueue = (function () {
  68584. function SimplificationQueue() {
  68585. this.running = false;
  68586. this._simplificationArray = [];
  68587. }
  68588. SimplificationQueue.prototype.addTask = function (task) {
  68589. this._simplificationArray.push(task);
  68590. };
  68591. SimplificationQueue.prototype.executeNext = function () {
  68592. var task = this._simplificationArray.pop();
  68593. if (task) {
  68594. this.running = true;
  68595. this.runSimplification(task);
  68596. }
  68597. else {
  68598. this.running = false;
  68599. }
  68600. };
  68601. SimplificationQueue.prototype.runSimplification = function (task) {
  68602. var _this = this;
  68603. if (task.parallelProcessing) {
  68604. //parallel simplifier
  68605. task.settings.forEach(function (setting) {
  68606. var simplifier = _this.getSimplifier(task);
  68607. simplifier.simplify(setting, function (newMesh) {
  68608. task.mesh.addLODLevel(setting.distance, newMesh);
  68609. newMesh.isVisible = true;
  68610. //check if it is the last
  68611. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  68612. //all done, run the success callback.
  68613. task.successCallback();
  68614. }
  68615. _this.executeNext();
  68616. });
  68617. });
  68618. }
  68619. else {
  68620. //single simplifier.
  68621. var simplifier = this.getSimplifier(task);
  68622. var runDecimation = function (setting, callback) {
  68623. simplifier.simplify(setting, function (newMesh) {
  68624. task.mesh.addLODLevel(setting.distance, newMesh);
  68625. newMesh.isVisible = true;
  68626. //run the next quality level
  68627. callback();
  68628. });
  68629. };
  68630. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  68631. runDecimation(task.settings[loop.index], function () {
  68632. loop.executeNext();
  68633. });
  68634. }, function () {
  68635. //execution ended, run the success callback.
  68636. if (task.successCallback) {
  68637. task.successCallback();
  68638. }
  68639. _this.executeNext();
  68640. });
  68641. }
  68642. };
  68643. SimplificationQueue.prototype.getSimplifier = function (task) {
  68644. switch (task.simplificationType) {
  68645. case SimplificationType.QUADRATIC:
  68646. default:
  68647. return new QuadraticErrorSimplification(task.mesh);
  68648. }
  68649. };
  68650. return SimplificationQueue;
  68651. }());
  68652. BABYLON.SimplificationQueue = SimplificationQueue;
  68653. /**
  68654. * The implemented types of simplification.
  68655. * At the moment only Quadratic Error Decimation is implemented.
  68656. */
  68657. var SimplificationType;
  68658. (function (SimplificationType) {
  68659. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  68660. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  68661. var DecimationTriangle = (function () {
  68662. function DecimationTriangle(vertices) {
  68663. this.vertices = vertices;
  68664. this.error = new Array(4);
  68665. this.deleted = false;
  68666. this.isDirty = false;
  68667. this.deletePending = false;
  68668. this.borderFactor = 0;
  68669. }
  68670. return DecimationTriangle;
  68671. }());
  68672. BABYLON.DecimationTriangle = DecimationTriangle;
  68673. var DecimationVertex = (function () {
  68674. function DecimationVertex(position, id) {
  68675. this.position = position;
  68676. this.id = id;
  68677. this.isBorder = true;
  68678. this.q = new QuadraticMatrix();
  68679. this.triangleCount = 0;
  68680. this.triangleStart = 0;
  68681. this.originalOffsets = [];
  68682. }
  68683. DecimationVertex.prototype.updatePosition = function (newPosition) {
  68684. this.position.copyFrom(newPosition);
  68685. };
  68686. return DecimationVertex;
  68687. }());
  68688. BABYLON.DecimationVertex = DecimationVertex;
  68689. var QuadraticMatrix = (function () {
  68690. function QuadraticMatrix(data) {
  68691. this.data = new Array(10);
  68692. for (var i = 0; i < 10; ++i) {
  68693. if (data && data[i]) {
  68694. this.data[i] = data[i];
  68695. }
  68696. else {
  68697. this.data[i] = 0;
  68698. }
  68699. }
  68700. }
  68701. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  68702. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  68703. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  68704. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  68705. return det;
  68706. };
  68707. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  68708. for (var i = 0; i < 10; ++i) {
  68709. this.data[i] += matrix.data[i];
  68710. }
  68711. };
  68712. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  68713. for (var i = 0; i < 10; ++i) {
  68714. this.data[i] += data[i];
  68715. }
  68716. };
  68717. QuadraticMatrix.prototype.add = function (matrix) {
  68718. var m = new QuadraticMatrix();
  68719. for (var i = 0; i < 10; ++i) {
  68720. m.data[i] = this.data[i] + matrix.data[i];
  68721. }
  68722. return m;
  68723. };
  68724. QuadraticMatrix.FromData = function (a, b, c, d) {
  68725. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  68726. };
  68727. //returning an array to avoid garbage collection
  68728. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  68729. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  68730. };
  68731. return QuadraticMatrix;
  68732. }());
  68733. BABYLON.QuadraticMatrix = QuadraticMatrix;
  68734. var Reference = (function () {
  68735. function Reference(vertexId, triangleId) {
  68736. this.vertexId = vertexId;
  68737. this.triangleId = triangleId;
  68738. }
  68739. return Reference;
  68740. }());
  68741. BABYLON.Reference = Reference;
  68742. /**
  68743. * An implementation of the Quadratic Error simplification algorithm.
  68744. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  68745. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  68746. * @author RaananW
  68747. */
  68748. var QuadraticErrorSimplification = (function () {
  68749. function QuadraticErrorSimplification(_mesh) {
  68750. this._mesh = _mesh;
  68751. this.initialized = false;
  68752. this.syncIterations = 5000;
  68753. this.aggressiveness = 7;
  68754. this.decimationIterations = 100;
  68755. this.boundingBoxEpsilon = BABYLON.Epsilon;
  68756. }
  68757. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  68758. var _this = this;
  68759. this.initDecimatedMesh();
  68760. //iterating through the submeshes array, one after the other.
  68761. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  68762. _this.initWithMesh(loop.index, function () {
  68763. _this.runDecimation(settings, loop.index, function () {
  68764. loop.executeNext();
  68765. });
  68766. }, settings.optimizeMesh);
  68767. }, function () {
  68768. setTimeout(function () {
  68769. successCallback(_this._reconstructedMesh);
  68770. }, 0);
  68771. });
  68772. };
  68773. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  68774. var _this = this;
  68775. var gCount = 0;
  68776. triangle.vertices.forEach(function (vertex) {
  68777. var count = 0;
  68778. var vPos = vertex.position;
  68779. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  68780. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  68781. ++count;
  68782. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  68783. ++count;
  68784. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  68785. ++count;
  68786. if (count > 1) {
  68787. ++gCount;
  68788. }
  68789. ;
  68790. });
  68791. if (gCount > 1) {
  68792. console.log(triangle, gCount);
  68793. }
  68794. return gCount > 1;
  68795. };
  68796. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  68797. var _this = this;
  68798. var targetCount = ~~(this.triangles.length * settings.quality);
  68799. var deletedTriangles = 0;
  68800. var triangleCount = this.triangles.length;
  68801. var iterationFunction = function (iteration, callback) {
  68802. setTimeout(function () {
  68803. if (iteration % 5 === 0) {
  68804. _this.updateMesh(iteration === 0);
  68805. }
  68806. for (var i = 0; i < _this.triangles.length; ++i) {
  68807. _this.triangles[i].isDirty = false;
  68808. }
  68809. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  68810. var trianglesIterator = function (i) {
  68811. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  68812. var t = _this.triangles[tIdx];
  68813. if (!t)
  68814. return;
  68815. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  68816. return;
  68817. }
  68818. for (var j = 0; j < 3; ++j) {
  68819. if (t.error[j] < threshold) {
  68820. var deleted0 = [];
  68821. var deleted1 = [];
  68822. var v0 = t.vertices[j];
  68823. var v1 = t.vertices[(j + 1) % 3];
  68824. if (v0.isBorder || v1.isBorder)
  68825. continue;
  68826. var p = BABYLON.Vector3.Zero();
  68827. var n = BABYLON.Vector3.Zero();
  68828. var uv = BABYLON.Vector2.Zero();
  68829. var color = new BABYLON.Color4(0, 0, 0, 1);
  68830. _this.calculateError(v0, v1, p, n, uv, color);
  68831. var delTr = new Array();
  68832. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  68833. continue;
  68834. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  68835. continue;
  68836. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  68837. continue;
  68838. var uniqueArray = new Array();
  68839. delTr.forEach(function (deletedT) {
  68840. if (uniqueArray.indexOf(deletedT) === -1) {
  68841. deletedT.deletePending = true;
  68842. uniqueArray.push(deletedT);
  68843. }
  68844. });
  68845. if (uniqueArray.length % 2 !== 0) {
  68846. continue;
  68847. }
  68848. v0.q = v1.q.add(v0.q);
  68849. v0.updatePosition(p);
  68850. var tStart = _this.references.length;
  68851. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  68852. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  68853. var tCount = _this.references.length - tStart;
  68854. if (tCount <= v0.triangleCount) {
  68855. if (tCount) {
  68856. for (var c = 0; c < tCount; c++) {
  68857. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  68858. }
  68859. }
  68860. }
  68861. else {
  68862. v0.triangleStart = tStart;
  68863. }
  68864. v0.triangleCount = tCount;
  68865. break;
  68866. }
  68867. }
  68868. };
  68869. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  68870. }, 0);
  68871. };
  68872. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  68873. if (triangleCount - deletedTriangles <= targetCount)
  68874. loop.breakLoop();
  68875. else {
  68876. iterationFunction(loop.index, function () {
  68877. loop.executeNext();
  68878. });
  68879. }
  68880. }, function () {
  68881. setTimeout(function () {
  68882. //reconstruct this part of the mesh
  68883. _this.reconstructMesh(submeshIndex);
  68884. successCallback();
  68885. }, 0);
  68886. });
  68887. };
  68888. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  68889. var _this = this;
  68890. this.vertices = [];
  68891. this.triangles = [];
  68892. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68893. var indices = this._mesh.getIndices();
  68894. var submesh = this._mesh.subMeshes[submeshIndex];
  68895. var findInVertices = function (positionToSearch) {
  68896. if (optimizeMesh) {
  68897. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  68898. if (_this.vertices[ii].position.equals(positionToSearch)) {
  68899. return _this.vertices[ii];
  68900. }
  68901. }
  68902. }
  68903. return null;
  68904. };
  68905. var vertexReferences = [];
  68906. var vertexInit = function (i) {
  68907. var offset = i + submesh.verticesStart;
  68908. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  68909. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  68910. vertex.originalOffsets.push(offset);
  68911. if (vertex.id === _this.vertices.length) {
  68912. _this.vertices.push(vertex);
  68913. }
  68914. vertexReferences.push(vertex.id);
  68915. };
  68916. //var totalVertices = mesh.getTotalVertices();
  68917. var totalVertices = submesh.verticesCount;
  68918. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  68919. var indicesInit = function (i) {
  68920. var offset = (submesh.indexStart / 3) + i;
  68921. var pos = (offset * 3);
  68922. var i0 = indices[pos + 0];
  68923. var i1 = indices[pos + 1];
  68924. var i2 = indices[pos + 2];
  68925. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  68926. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  68927. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  68928. var triangle = new DecimationTriangle([v0, v1, v2]);
  68929. triangle.originalOffset = pos;
  68930. _this.triangles.push(triangle);
  68931. };
  68932. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  68933. _this.init(callback);
  68934. });
  68935. });
  68936. };
  68937. QuadraticErrorSimplification.prototype.init = function (callback) {
  68938. var _this = this;
  68939. var triangleInit1 = function (i) {
  68940. var t = _this.triangles[i];
  68941. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  68942. for (var j = 0; j < 3; j++) {
  68943. 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))));
  68944. }
  68945. };
  68946. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  68947. var triangleInit2 = function (i) {
  68948. var t = _this.triangles[i];
  68949. for (var j = 0; j < 3; ++j) {
  68950. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  68951. }
  68952. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  68953. };
  68954. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  68955. _this.initialized = true;
  68956. callback();
  68957. });
  68958. });
  68959. };
  68960. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  68961. var newTriangles = [];
  68962. var i;
  68963. for (i = 0; i < this.vertices.length; ++i) {
  68964. this.vertices[i].triangleCount = 0;
  68965. }
  68966. var t;
  68967. var j;
  68968. for (i = 0; i < this.triangles.length; ++i) {
  68969. if (!this.triangles[i].deleted) {
  68970. t = this.triangles[i];
  68971. for (j = 0; j < 3; ++j) {
  68972. t.vertices[j].triangleCount = 1;
  68973. }
  68974. newTriangles.push(t);
  68975. }
  68976. }
  68977. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  68978. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  68979. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  68980. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  68981. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  68982. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  68983. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  68984. var vertexCount = 0;
  68985. for (i = 0; i < this.vertices.length; ++i) {
  68986. var vertex = this.vertices[i];
  68987. vertex.id = vertexCount;
  68988. if (vertex.triangleCount) {
  68989. vertex.originalOffsets.forEach(function (originalOffset) {
  68990. newPositionData.push(vertex.position.x);
  68991. newPositionData.push(vertex.position.y);
  68992. newPositionData.push(vertex.position.z);
  68993. newNormalData.push(normalData[originalOffset * 3]);
  68994. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  68995. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  68996. if (uvs && uvs.length) {
  68997. newUVsData.push(uvs[(originalOffset * 2)]);
  68998. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  68999. }
  69000. else if (colorsData && colorsData.length) {
  69001. newColorsData.push(colorsData[(originalOffset * 4)]);
  69002. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  69003. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  69004. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  69005. }
  69006. ++vertexCount;
  69007. });
  69008. }
  69009. }
  69010. var startingIndex = this._reconstructedMesh.getTotalIndices();
  69011. var startingVertex = this._reconstructedMesh.getTotalVertices();
  69012. var submeshesArray = this._reconstructedMesh.subMeshes;
  69013. this._reconstructedMesh.subMeshes = [];
  69014. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  69015. var originalIndices = this._mesh.getIndices();
  69016. for (i = 0; i < newTriangles.length; ++i) {
  69017. t = newTriangles[i]; //now get the new referencing point for each vertex
  69018. [0, 1, 2].forEach(function (idx) {
  69019. var id = originalIndices[t.originalOffset + idx];
  69020. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  69021. if (offset < 0)
  69022. offset = 0;
  69023. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  69024. });
  69025. }
  69026. //overwriting the old vertex buffers and indices.
  69027. this._reconstructedMesh.setIndices(newIndicesArray);
  69028. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  69029. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  69030. if (newUVsData.length > 0)
  69031. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  69032. if (newColorsData.length > 0)
  69033. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  69034. //create submesh
  69035. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  69036. if (submeshIndex > 0) {
  69037. this._reconstructedMesh.subMeshes = [];
  69038. submeshesArray.forEach(function (submesh) {
  69039. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  69040. });
  69041. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  69042. }
  69043. };
  69044. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  69045. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  69046. this._reconstructedMesh.material = this._mesh.material;
  69047. this._reconstructedMesh.parent = this._mesh.parent;
  69048. this._reconstructedMesh.isVisible = false;
  69049. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  69050. };
  69051. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  69052. for (var i = 0; i < vertex1.triangleCount; ++i) {
  69053. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  69054. if (t.deleted)
  69055. continue;
  69056. var s = this.references[vertex1.triangleStart + i].vertexId;
  69057. var v1 = t.vertices[(s + 1) % 3];
  69058. var v2 = t.vertices[(s + 2) % 3];
  69059. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  69060. deletedArray[i] = true;
  69061. delTr.push(t);
  69062. continue;
  69063. }
  69064. var d1 = v1.position.subtract(point);
  69065. d1 = d1.normalize();
  69066. var d2 = v2.position.subtract(point);
  69067. d2 = d2.normalize();
  69068. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  69069. return true;
  69070. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  69071. deletedArray[i] = false;
  69072. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  69073. return true;
  69074. }
  69075. return false;
  69076. };
  69077. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  69078. var newDeleted = deletedTriangles;
  69079. for (var i = 0; i < vertex.triangleCount; ++i) {
  69080. var ref = this.references[vertex.triangleStart + i];
  69081. var t = this.triangles[ref.triangleId];
  69082. if (t.deleted)
  69083. continue;
  69084. if (deletedArray[i] && t.deletePending) {
  69085. t.deleted = true;
  69086. newDeleted++;
  69087. continue;
  69088. }
  69089. t.vertices[ref.vertexId] = origVertex;
  69090. t.isDirty = true;
  69091. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  69092. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  69093. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  69094. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  69095. this.references.push(ref);
  69096. }
  69097. return newDeleted;
  69098. };
  69099. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  69100. for (var i = 0; i < this.vertices.length; ++i) {
  69101. var vCount = [];
  69102. var vId = [];
  69103. var v = this.vertices[i];
  69104. var j;
  69105. for (j = 0; j < v.triangleCount; ++j) {
  69106. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  69107. for (var ii = 0; ii < 3; ii++) {
  69108. var ofs = 0;
  69109. var vv = triangle.vertices[ii];
  69110. while (ofs < vCount.length) {
  69111. if (vId[ofs] === vv.id)
  69112. break;
  69113. ++ofs;
  69114. }
  69115. if (ofs === vCount.length) {
  69116. vCount.push(1);
  69117. vId.push(vv.id);
  69118. }
  69119. else {
  69120. vCount[ofs]++;
  69121. }
  69122. }
  69123. }
  69124. for (j = 0; j < vCount.length; ++j) {
  69125. if (vCount[j] === 1) {
  69126. this.vertices[vId[j]].isBorder = true;
  69127. }
  69128. else {
  69129. this.vertices[vId[j]].isBorder = false;
  69130. }
  69131. }
  69132. }
  69133. };
  69134. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  69135. if (identifyBorders === void 0) { identifyBorders = false; }
  69136. var i;
  69137. if (!identifyBorders) {
  69138. var newTrianglesVector = [];
  69139. for (i = 0; i < this.triangles.length; ++i) {
  69140. if (!this.triangles[i].deleted) {
  69141. newTrianglesVector.push(this.triangles[i]);
  69142. }
  69143. }
  69144. this.triangles = newTrianglesVector;
  69145. }
  69146. for (i = 0; i < this.vertices.length; ++i) {
  69147. this.vertices[i].triangleCount = 0;
  69148. this.vertices[i].triangleStart = 0;
  69149. }
  69150. var t;
  69151. var j;
  69152. var v;
  69153. for (i = 0; i < this.triangles.length; ++i) {
  69154. t = this.triangles[i];
  69155. for (j = 0; j < 3; ++j) {
  69156. v = t.vertices[j];
  69157. v.triangleCount++;
  69158. }
  69159. }
  69160. var tStart = 0;
  69161. for (i = 0; i < this.vertices.length; ++i) {
  69162. this.vertices[i].triangleStart = tStart;
  69163. tStart += this.vertices[i].triangleCount;
  69164. this.vertices[i].triangleCount = 0;
  69165. }
  69166. var newReferences = new Array(this.triangles.length * 3);
  69167. for (i = 0; i < this.triangles.length; ++i) {
  69168. t = this.triangles[i];
  69169. for (j = 0; j < 3; ++j) {
  69170. v = t.vertices[j];
  69171. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  69172. v.triangleCount++;
  69173. }
  69174. }
  69175. this.references = newReferences;
  69176. if (identifyBorders) {
  69177. this.identifyBorder();
  69178. }
  69179. };
  69180. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  69181. var x = point.x;
  69182. var y = point.y;
  69183. var z = point.z;
  69184. 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
  69185. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  69186. };
  69187. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  69188. var q = vertex1.q.add(vertex2.q);
  69189. var border = vertex1.isBorder && vertex2.isBorder;
  69190. var error = 0;
  69191. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  69192. if (qDet !== 0 && !border) {
  69193. if (!pointResult) {
  69194. pointResult = BABYLON.Vector3.Zero();
  69195. }
  69196. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  69197. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  69198. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  69199. error = this.vertexError(q, pointResult);
  69200. }
  69201. else {
  69202. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  69203. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  69204. var error1 = this.vertexError(q, vertex1.position);
  69205. var error2 = this.vertexError(q, vertex2.position);
  69206. var error3 = this.vertexError(q, p3);
  69207. error = Math.min(error1, error2, error3);
  69208. if (error === error1) {
  69209. if (pointResult) {
  69210. pointResult.copyFrom(vertex1.position);
  69211. }
  69212. }
  69213. else if (error === error2) {
  69214. if (pointResult) {
  69215. pointResult.copyFrom(vertex2.position);
  69216. }
  69217. }
  69218. else {
  69219. if (pointResult) {
  69220. pointResult.copyFrom(p3);
  69221. }
  69222. }
  69223. }
  69224. return error;
  69225. };
  69226. return QuadraticErrorSimplification;
  69227. }());
  69228. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  69229. })(BABYLON || (BABYLON = {}));
  69230. //# sourceMappingURL=babylon.meshSimplification.js.map
  69231. var BABYLON;
  69232. (function (BABYLON) {
  69233. var Internals;
  69234. (function (Internals) {
  69235. var MeshLODLevel = (function () {
  69236. function MeshLODLevel(distance, mesh) {
  69237. this.distance = distance;
  69238. this.mesh = mesh;
  69239. }
  69240. return MeshLODLevel;
  69241. }());
  69242. Internals.MeshLODLevel = MeshLODLevel;
  69243. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  69244. })(BABYLON || (BABYLON = {}));
  69245. //# sourceMappingURL=babylon.meshLODLevel.js.map
  69246. var BABYLON;
  69247. (function (BABYLON) {
  69248. // Standard optimizations
  69249. var SceneOptimization = (function () {
  69250. function SceneOptimization(priority) {
  69251. if (priority === void 0) { priority = 0; }
  69252. this.priority = priority;
  69253. this.apply = function (scene) {
  69254. return true; // Return true if everything that can be done was applied
  69255. };
  69256. }
  69257. return SceneOptimization;
  69258. }());
  69259. BABYLON.SceneOptimization = SceneOptimization;
  69260. var TextureOptimization = (function (_super) {
  69261. __extends(TextureOptimization, _super);
  69262. function TextureOptimization(priority, maximumSize) {
  69263. if (priority === void 0) { priority = 0; }
  69264. if (maximumSize === void 0) { maximumSize = 1024; }
  69265. var _this = _super.call(this, priority) || this;
  69266. _this.priority = priority;
  69267. _this.maximumSize = maximumSize;
  69268. _this.apply = function (scene) {
  69269. var allDone = true;
  69270. for (var index = 0; index < scene.textures.length; index++) {
  69271. var texture = scene.textures[index];
  69272. if (!texture.canRescale || texture.getContext) {
  69273. continue;
  69274. }
  69275. var currentSize = texture.getSize();
  69276. var maxDimension = Math.max(currentSize.width, currentSize.height);
  69277. if (maxDimension > _this.maximumSize) {
  69278. texture.scale(0.5);
  69279. allDone = false;
  69280. }
  69281. }
  69282. return allDone;
  69283. };
  69284. return _this;
  69285. }
  69286. return TextureOptimization;
  69287. }(SceneOptimization));
  69288. BABYLON.TextureOptimization = TextureOptimization;
  69289. var HardwareScalingOptimization = (function (_super) {
  69290. __extends(HardwareScalingOptimization, _super);
  69291. function HardwareScalingOptimization(priority, maximumScale) {
  69292. if (priority === void 0) { priority = 0; }
  69293. if (maximumScale === void 0) { maximumScale = 2; }
  69294. var _this = _super.call(this, priority) || this;
  69295. _this.priority = priority;
  69296. _this.maximumScale = maximumScale;
  69297. _this._currentScale = 1;
  69298. _this.apply = function (scene) {
  69299. _this._currentScale++;
  69300. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  69301. return _this._currentScale >= _this.maximumScale;
  69302. };
  69303. return _this;
  69304. }
  69305. return HardwareScalingOptimization;
  69306. }(SceneOptimization));
  69307. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  69308. var ShadowsOptimization = (function (_super) {
  69309. __extends(ShadowsOptimization, _super);
  69310. function ShadowsOptimization() {
  69311. var _this = _super !== null && _super.apply(this, arguments) || this;
  69312. _this.apply = function (scene) {
  69313. scene.shadowsEnabled = false;
  69314. return true;
  69315. };
  69316. return _this;
  69317. }
  69318. return ShadowsOptimization;
  69319. }(SceneOptimization));
  69320. BABYLON.ShadowsOptimization = ShadowsOptimization;
  69321. var PostProcessesOptimization = (function (_super) {
  69322. __extends(PostProcessesOptimization, _super);
  69323. function PostProcessesOptimization() {
  69324. var _this = _super !== null && _super.apply(this, arguments) || this;
  69325. _this.apply = function (scene) {
  69326. scene.postProcessesEnabled = false;
  69327. return true;
  69328. };
  69329. return _this;
  69330. }
  69331. return PostProcessesOptimization;
  69332. }(SceneOptimization));
  69333. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  69334. var LensFlaresOptimization = (function (_super) {
  69335. __extends(LensFlaresOptimization, _super);
  69336. function LensFlaresOptimization() {
  69337. var _this = _super !== null && _super.apply(this, arguments) || this;
  69338. _this.apply = function (scene) {
  69339. scene.lensFlaresEnabled = false;
  69340. return true;
  69341. };
  69342. return _this;
  69343. }
  69344. return LensFlaresOptimization;
  69345. }(SceneOptimization));
  69346. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  69347. var ParticlesOptimization = (function (_super) {
  69348. __extends(ParticlesOptimization, _super);
  69349. function ParticlesOptimization() {
  69350. var _this = _super !== null && _super.apply(this, arguments) || this;
  69351. _this.apply = function (scene) {
  69352. scene.particlesEnabled = false;
  69353. return true;
  69354. };
  69355. return _this;
  69356. }
  69357. return ParticlesOptimization;
  69358. }(SceneOptimization));
  69359. BABYLON.ParticlesOptimization = ParticlesOptimization;
  69360. var RenderTargetsOptimization = (function (_super) {
  69361. __extends(RenderTargetsOptimization, _super);
  69362. function RenderTargetsOptimization() {
  69363. var _this = _super !== null && _super.apply(this, arguments) || this;
  69364. _this.apply = function (scene) {
  69365. scene.renderTargetsEnabled = false;
  69366. return true;
  69367. };
  69368. return _this;
  69369. }
  69370. return RenderTargetsOptimization;
  69371. }(SceneOptimization));
  69372. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  69373. var MergeMeshesOptimization = (function (_super) {
  69374. __extends(MergeMeshesOptimization, _super);
  69375. function MergeMeshesOptimization() {
  69376. var _this = _super !== null && _super.apply(this, arguments) || this;
  69377. _this._canBeMerged = function (abstractMesh) {
  69378. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  69379. return false;
  69380. }
  69381. var mesh = abstractMesh;
  69382. if (!mesh.isVisible || !mesh.isEnabled()) {
  69383. return false;
  69384. }
  69385. if (mesh.instances.length > 0) {
  69386. return false;
  69387. }
  69388. if (mesh.skeleton || mesh.hasLODLevels) {
  69389. return false;
  69390. }
  69391. if (mesh.parent) {
  69392. return false;
  69393. }
  69394. return true;
  69395. };
  69396. _this.apply = function (scene, updateSelectionTree) {
  69397. var globalPool = scene.meshes.slice(0);
  69398. var globalLength = globalPool.length;
  69399. for (var index = 0; index < globalLength; index++) {
  69400. var currentPool = new Array();
  69401. var current = globalPool[index];
  69402. // Checks
  69403. if (!_this._canBeMerged(current)) {
  69404. continue;
  69405. }
  69406. currentPool.push(current);
  69407. // Find compatible meshes
  69408. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  69409. var otherMesh = globalPool[subIndex];
  69410. if (!_this._canBeMerged(otherMesh)) {
  69411. continue;
  69412. }
  69413. if (otherMesh.material !== current.material) {
  69414. continue;
  69415. }
  69416. if (otherMesh.checkCollisions !== current.checkCollisions) {
  69417. continue;
  69418. }
  69419. currentPool.push(otherMesh);
  69420. globalLength--;
  69421. globalPool.splice(subIndex, 1);
  69422. subIndex--;
  69423. }
  69424. if (currentPool.length < 2) {
  69425. continue;
  69426. }
  69427. // Merge meshes
  69428. BABYLON.Mesh.MergeMeshes(currentPool);
  69429. }
  69430. if (updateSelectionTree != undefined) {
  69431. if (updateSelectionTree) {
  69432. scene.createOrUpdateSelectionOctree();
  69433. }
  69434. }
  69435. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  69436. scene.createOrUpdateSelectionOctree();
  69437. }
  69438. return true;
  69439. };
  69440. return _this;
  69441. }
  69442. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  69443. get: function () {
  69444. return MergeMeshesOptimization._UpdateSelectionTree;
  69445. },
  69446. set: function (value) {
  69447. MergeMeshesOptimization._UpdateSelectionTree = value;
  69448. },
  69449. enumerable: true,
  69450. configurable: true
  69451. });
  69452. MergeMeshesOptimization._UpdateSelectionTree = false;
  69453. return MergeMeshesOptimization;
  69454. }(SceneOptimization));
  69455. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  69456. // Options
  69457. var SceneOptimizerOptions = (function () {
  69458. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  69459. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  69460. if (trackerDuration === void 0) { trackerDuration = 2000; }
  69461. this.targetFrameRate = targetFrameRate;
  69462. this.trackerDuration = trackerDuration;
  69463. this.optimizations = new Array();
  69464. }
  69465. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  69466. var result = new SceneOptimizerOptions(targetFrameRate);
  69467. var priority = 0;
  69468. result.optimizations.push(new MergeMeshesOptimization(priority));
  69469. result.optimizations.push(new ShadowsOptimization(priority));
  69470. result.optimizations.push(new LensFlaresOptimization(priority));
  69471. // Next priority
  69472. priority++;
  69473. result.optimizations.push(new PostProcessesOptimization(priority));
  69474. result.optimizations.push(new ParticlesOptimization(priority));
  69475. // Next priority
  69476. priority++;
  69477. result.optimizations.push(new TextureOptimization(priority, 1024));
  69478. return result;
  69479. };
  69480. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  69481. var result = new SceneOptimizerOptions(targetFrameRate);
  69482. var priority = 0;
  69483. result.optimizations.push(new MergeMeshesOptimization(priority));
  69484. result.optimizations.push(new ShadowsOptimization(priority));
  69485. result.optimizations.push(new LensFlaresOptimization(priority));
  69486. // Next priority
  69487. priority++;
  69488. result.optimizations.push(new PostProcessesOptimization(priority));
  69489. result.optimizations.push(new ParticlesOptimization(priority));
  69490. // Next priority
  69491. priority++;
  69492. result.optimizations.push(new TextureOptimization(priority, 512));
  69493. // Next priority
  69494. priority++;
  69495. result.optimizations.push(new RenderTargetsOptimization(priority));
  69496. // Next priority
  69497. priority++;
  69498. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  69499. return result;
  69500. };
  69501. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  69502. var result = new SceneOptimizerOptions(targetFrameRate);
  69503. var priority = 0;
  69504. result.optimizations.push(new MergeMeshesOptimization(priority));
  69505. result.optimizations.push(new ShadowsOptimization(priority));
  69506. result.optimizations.push(new LensFlaresOptimization(priority));
  69507. // Next priority
  69508. priority++;
  69509. result.optimizations.push(new PostProcessesOptimization(priority));
  69510. result.optimizations.push(new ParticlesOptimization(priority));
  69511. // Next priority
  69512. priority++;
  69513. result.optimizations.push(new TextureOptimization(priority, 256));
  69514. // Next priority
  69515. priority++;
  69516. result.optimizations.push(new RenderTargetsOptimization(priority));
  69517. // Next priority
  69518. priority++;
  69519. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  69520. return result;
  69521. };
  69522. return SceneOptimizerOptions;
  69523. }());
  69524. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  69525. // Scene optimizer tool
  69526. var SceneOptimizer = (function () {
  69527. function SceneOptimizer() {
  69528. }
  69529. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  69530. // TODO: add an epsilon
  69531. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  69532. if (onSuccess) {
  69533. onSuccess();
  69534. }
  69535. return;
  69536. }
  69537. // Apply current level of optimizations
  69538. var allDone = true;
  69539. var noOptimizationApplied = true;
  69540. for (var index = 0; index < options.optimizations.length; index++) {
  69541. var optimization = options.optimizations[index];
  69542. if (optimization.priority === currentPriorityLevel) {
  69543. noOptimizationApplied = false;
  69544. allDone = allDone && optimization.apply(scene);
  69545. }
  69546. }
  69547. // If no optimization was applied, this is a failure :(
  69548. if (noOptimizationApplied) {
  69549. if (onFailure) {
  69550. onFailure();
  69551. }
  69552. return;
  69553. }
  69554. // If all optimizations were done, move to next level
  69555. if (allDone) {
  69556. currentPriorityLevel++;
  69557. }
  69558. // Let's the system running for a specific amount of time before checking FPS
  69559. scene.executeWhenReady(function () {
  69560. setTimeout(function () {
  69561. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  69562. }, options.trackerDuration);
  69563. });
  69564. };
  69565. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  69566. if (!options) {
  69567. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  69568. }
  69569. // Let's the system running for a specific amount of time before checking FPS
  69570. scene.executeWhenReady(function () {
  69571. setTimeout(function () {
  69572. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  69573. }, options.trackerDuration);
  69574. });
  69575. };
  69576. return SceneOptimizer;
  69577. }());
  69578. BABYLON.SceneOptimizer = SceneOptimizer;
  69579. })(BABYLON || (BABYLON = {}));
  69580. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  69581. var BABYLON;
  69582. (function (BABYLON) {
  69583. var OutlineRenderer = (function () {
  69584. function OutlineRenderer(scene) {
  69585. this.zOffset = 1;
  69586. this._scene = scene;
  69587. }
  69588. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  69589. var _this = this;
  69590. if (useOverlay === void 0) { useOverlay = false; }
  69591. var scene = this._scene;
  69592. var engine = this._scene.getEngine();
  69593. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  69594. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  69595. return;
  69596. }
  69597. var mesh = subMesh.getRenderingMesh();
  69598. var material = subMesh.getMaterial();
  69599. engine.enableEffect(this._effect);
  69600. // Logarithmic depth
  69601. if (material.useLogarithmicDepth) {
  69602. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  69603. }
  69604. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  69605. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  69606. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  69607. // Bones
  69608. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69609. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  69610. }
  69611. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  69612. // Alpha test
  69613. if (material && material.needAlphaTesting()) {
  69614. var alphaTexture = material.getAlphaTestTexture();
  69615. if (alphaTexture) {
  69616. this._effect.setTexture("diffuseSampler", alphaTexture);
  69617. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  69618. }
  69619. }
  69620. engine.setZOffset(-this.zOffset);
  69621. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  69622. engine.setZOffset(0);
  69623. };
  69624. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  69625. var defines = [];
  69626. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  69627. var mesh = subMesh.getMesh();
  69628. var material = subMesh.getMaterial();
  69629. if (material) {
  69630. // Alpha test
  69631. if (material.needAlphaTesting()) {
  69632. defines.push("#define ALPHATEST");
  69633. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69634. attribs.push(BABYLON.VertexBuffer.UVKind);
  69635. defines.push("#define UV1");
  69636. }
  69637. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69638. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69639. defines.push("#define UV2");
  69640. }
  69641. }
  69642. //Logarithmic depth
  69643. if (material.useLogarithmicDepth) {
  69644. defines.push("#define LOGARITHMICDEPTH");
  69645. }
  69646. }
  69647. // Bones
  69648. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69649. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69650. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69651. if (mesh.numBoneInfluencers > 4) {
  69652. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  69653. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  69654. }
  69655. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69656. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  69657. }
  69658. else {
  69659. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69660. }
  69661. // Instances
  69662. if (useInstances) {
  69663. defines.push("#define INSTANCES");
  69664. attribs.push("world0");
  69665. attribs.push("world1");
  69666. attribs.push("world2");
  69667. attribs.push("world3");
  69668. }
  69669. // Get correct effect
  69670. var join = defines.join("\n");
  69671. if (this._cachedDefines !== join) {
  69672. this._cachedDefines = join;
  69673. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  69674. }
  69675. return this._effect.isReady();
  69676. };
  69677. return OutlineRenderer;
  69678. }());
  69679. BABYLON.OutlineRenderer = OutlineRenderer;
  69680. })(BABYLON || (BABYLON = {}));
  69681. //# sourceMappingURL=babylon.outlineRenderer.js.map
  69682. var BABYLON;
  69683. (function (BABYLON) {
  69684. var FaceAdjacencies = (function () {
  69685. function FaceAdjacencies() {
  69686. this.edges = new Array();
  69687. this.edgesConnectedCount = 0;
  69688. }
  69689. return FaceAdjacencies;
  69690. }());
  69691. var EdgesRenderer = (function () {
  69692. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  69693. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  69694. if (epsilon === void 0) { epsilon = 0.95; }
  69695. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  69696. this.edgesWidthScalerForOrthographic = 1000.0;
  69697. this.edgesWidthScalerForPerspective = 50.0;
  69698. this._linesPositions = new Array();
  69699. this._linesNormals = new Array();
  69700. this._linesIndices = new Array();
  69701. this._buffers = {};
  69702. this._checkVerticesInsteadOfIndices = false;
  69703. this._source = source;
  69704. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  69705. this._epsilon = epsilon;
  69706. this._prepareRessources();
  69707. this._generateEdgesLines();
  69708. }
  69709. EdgesRenderer.prototype._prepareRessources = function () {
  69710. if (this._lineShader) {
  69711. return;
  69712. }
  69713. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  69714. attributes: ["position", "normal"],
  69715. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  69716. });
  69717. this._lineShader.disableDepthWrite = true;
  69718. this._lineShader.backFaceCulling = false;
  69719. };
  69720. EdgesRenderer.prototype._rebuild = function () {
  69721. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  69722. if (buffer) {
  69723. buffer._rebuild();
  69724. }
  69725. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  69726. if (buffer) {
  69727. buffer._rebuild();
  69728. }
  69729. var scene = this._source.getScene();
  69730. var engine = scene.getEngine();
  69731. this._ib = engine.createIndexBuffer(this._linesIndices);
  69732. };
  69733. EdgesRenderer.prototype.dispose = function () {
  69734. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  69735. if (buffer) {
  69736. buffer.dispose();
  69737. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  69738. }
  69739. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  69740. if (buffer) {
  69741. buffer.dispose();
  69742. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  69743. }
  69744. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  69745. this._lineShader.dispose();
  69746. };
  69747. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  69748. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  69749. return 0;
  69750. }
  69751. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  69752. return 1;
  69753. }
  69754. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  69755. return 2;
  69756. }
  69757. return -1;
  69758. };
  69759. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  69760. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  69761. return 0;
  69762. }
  69763. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  69764. return 1;
  69765. }
  69766. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  69767. return 2;
  69768. }
  69769. return -1;
  69770. };
  69771. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  69772. var needToCreateLine;
  69773. if (edge === undefined) {
  69774. needToCreateLine = true;
  69775. }
  69776. else {
  69777. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  69778. needToCreateLine = dotProduct < this._epsilon;
  69779. }
  69780. if (needToCreateLine) {
  69781. var offset = this._linesPositions.length / 3;
  69782. var normal = p0.subtract(p1);
  69783. normal.normalize();
  69784. // Positions
  69785. this._linesPositions.push(p0.x);
  69786. this._linesPositions.push(p0.y);
  69787. this._linesPositions.push(p0.z);
  69788. this._linesPositions.push(p0.x);
  69789. this._linesPositions.push(p0.y);
  69790. this._linesPositions.push(p0.z);
  69791. this._linesPositions.push(p1.x);
  69792. this._linesPositions.push(p1.y);
  69793. this._linesPositions.push(p1.z);
  69794. this._linesPositions.push(p1.x);
  69795. this._linesPositions.push(p1.y);
  69796. this._linesPositions.push(p1.z);
  69797. // Normals
  69798. this._linesNormals.push(p1.x);
  69799. this._linesNormals.push(p1.y);
  69800. this._linesNormals.push(p1.z);
  69801. this._linesNormals.push(-1);
  69802. this._linesNormals.push(p1.x);
  69803. this._linesNormals.push(p1.y);
  69804. this._linesNormals.push(p1.z);
  69805. this._linesNormals.push(1);
  69806. this._linesNormals.push(p0.x);
  69807. this._linesNormals.push(p0.y);
  69808. this._linesNormals.push(p0.z);
  69809. this._linesNormals.push(-1);
  69810. this._linesNormals.push(p0.x);
  69811. this._linesNormals.push(p0.y);
  69812. this._linesNormals.push(p0.z);
  69813. this._linesNormals.push(1);
  69814. // Indices
  69815. this._linesIndices.push(offset);
  69816. this._linesIndices.push(offset + 1);
  69817. this._linesIndices.push(offset + 2);
  69818. this._linesIndices.push(offset);
  69819. this._linesIndices.push(offset + 2);
  69820. this._linesIndices.push(offset + 3);
  69821. }
  69822. };
  69823. EdgesRenderer.prototype._generateEdgesLines = function () {
  69824. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  69825. var indices = this._source.getIndices();
  69826. // First let's find adjacencies
  69827. var adjacencies = new Array();
  69828. var faceNormals = new Array();
  69829. var index;
  69830. var faceAdjacencies;
  69831. // Prepare faces
  69832. for (index = 0; index < indices.length; index += 3) {
  69833. faceAdjacencies = new FaceAdjacencies();
  69834. var p0Index = indices[index];
  69835. var p1Index = indices[index + 1];
  69836. var p2Index = indices[index + 2];
  69837. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  69838. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  69839. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  69840. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  69841. faceNormal.normalize();
  69842. faceNormals.push(faceNormal);
  69843. adjacencies.push(faceAdjacencies);
  69844. }
  69845. // Scan
  69846. for (index = 0; index < adjacencies.length; index++) {
  69847. faceAdjacencies = adjacencies[index];
  69848. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  69849. var otherFaceAdjacencies = adjacencies[otherIndex];
  69850. if (faceAdjacencies.edgesConnectedCount === 3) {
  69851. break;
  69852. }
  69853. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  69854. continue;
  69855. }
  69856. var otherP0 = indices[otherIndex * 3];
  69857. var otherP1 = indices[otherIndex * 3 + 1];
  69858. var otherP2 = indices[otherIndex * 3 + 2];
  69859. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  69860. var otherEdgeIndex;
  69861. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  69862. continue;
  69863. }
  69864. switch (edgeIndex) {
  69865. case 0:
  69866. if (this._checkVerticesInsteadOfIndices) {
  69867. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  69868. }
  69869. else {
  69870. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  69871. }
  69872. break;
  69873. case 1:
  69874. if (this._checkVerticesInsteadOfIndices) {
  69875. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  69876. }
  69877. else {
  69878. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  69879. }
  69880. break;
  69881. case 2:
  69882. if (this._checkVerticesInsteadOfIndices) {
  69883. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  69884. }
  69885. else {
  69886. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  69887. }
  69888. break;
  69889. }
  69890. if (otherEdgeIndex === -1) {
  69891. continue;
  69892. }
  69893. faceAdjacencies.edges[edgeIndex] = otherIndex;
  69894. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  69895. faceAdjacencies.edgesConnectedCount++;
  69896. otherFaceAdjacencies.edgesConnectedCount++;
  69897. if (faceAdjacencies.edgesConnectedCount === 3) {
  69898. break;
  69899. }
  69900. }
  69901. }
  69902. }
  69903. // Create lines
  69904. for (index = 0; index < adjacencies.length; index++) {
  69905. // 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
  69906. var current = adjacencies[index];
  69907. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  69908. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  69909. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  69910. }
  69911. // Merge into a single mesh
  69912. var engine = this._source.getScene().getEngine();
  69913. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  69914. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  69915. this._ib = engine.createIndexBuffer(this._linesIndices);
  69916. this._indicesCount = this._linesIndices.length;
  69917. };
  69918. EdgesRenderer.prototype.render = function () {
  69919. if (!this._lineShader.isReady()) {
  69920. return;
  69921. }
  69922. var scene = this._source.getScene();
  69923. var engine = scene.getEngine();
  69924. this._lineShader._preBind();
  69925. // VBOs
  69926. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  69927. scene.resetCachedMaterial();
  69928. this._lineShader.setColor4("color", this._source.edgesColor);
  69929. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  69930. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  69931. }
  69932. else {
  69933. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  69934. }
  69935. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  69936. this._lineShader.bind(this._source.getWorldMatrix());
  69937. // Draw order
  69938. engine.draw(true, 0, this._indicesCount);
  69939. this._lineShader.unbind();
  69940. engine.setDepthWrite(true);
  69941. };
  69942. return EdgesRenderer;
  69943. }());
  69944. BABYLON.EdgesRenderer = EdgesRenderer;
  69945. })(BABYLON || (BABYLON = {}));
  69946. //# sourceMappingURL=babylon.edgesRenderer.js.map
  69947. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  69948. /// <reference path="..\Math\babylon.math.ts" />
  69949. var BABYLON;
  69950. (function (BABYLON) {
  69951. /**
  69952. * Special Glow Blur post process only blurring the alpha channel
  69953. * It enforces keeping the most luminous color in the color channel.
  69954. */
  69955. var GlowBlurPostProcess = (function (_super) {
  69956. __extends(GlowBlurPostProcess, _super);
  69957. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  69958. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69959. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  69960. _this.direction = direction;
  69961. _this.kernel = kernel;
  69962. _this.onApplyObservable.add(function (effect) {
  69963. effect.setFloat2("screenSize", _this.width, _this.height);
  69964. effect.setVector2("direction", _this.direction);
  69965. effect.setFloat("blurWidth", _this.kernel);
  69966. });
  69967. return _this;
  69968. }
  69969. return GlowBlurPostProcess;
  69970. }(BABYLON.PostProcess));
  69971. /**
  69972. * The highlight layer Helps adding a glow effect around a mesh.
  69973. *
  69974. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  69975. * glowy meshes to your scene.
  69976. *
  69977. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  69978. */
  69979. var HighlightLayer = (function () {
  69980. /**
  69981. * Instantiates a new highlight Layer and references it to the scene..
  69982. * @param name The name of the layer
  69983. * @param scene The scene to use the layer in
  69984. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  69985. */
  69986. function HighlightLayer(name, scene, options) {
  69987. this.name = name;
  69988. this._vertexBuffers = {};
  69989. this._mainTextureDesiredSize = { width: 0, height: 0 };
  69990. this._meshes = {};
  69991. this._maxSize = 0;
  69992. this._shouldRender = false;
  69993. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  69994. this._excludedMeshes = {};
  69995. /**
  69996. * Specifies whether or not the inner glow is ACTIVE in the layer.
  69997. */
  69998. this.innerGlow = true;
  69999. /**
  70000. * Specifies whether or not the outer glow is ACTIVE in the layer.
  70001. */
  70002. this.outerGlow = true;
  70003. /**
  70004. * Specifies wether the highlight layer is enabled or not.
  70005. */
  70006. this.isEnabled = true;
  70007. /**
  70008. * An event triggered when the highlight layer has been disposed.
  70009. * @type {BABYLON.Observable}
  70010. */
  70011. this.onDisposeObservable = new BABYLON.Observable();
  70012. /**
  70013. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  70014. * @type {BABYLON.Observable}
  70015. */
  70016. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  70017. /**
  70018. * An event triggered when the highlight layer is being blurred.
  70019. * @type {BABYLON.Observable}
  70020. */
  70021. this.onBeforeBlurObservable = new BABYLON.Observable();
  70022. /**
  70023. * An event triggered when the highlight layer has been blurred.
  70024. * @type {BABYLON.Observable}
  70025. */
  70026. this.onAfterBlurObservable = new BABYLON.Observable();
  70027. /**
  70028. * An event triggered when the glowing blurred texture is being merged in the scene.
  70029. * @type {BABYLON.Observable}
  70030. */
  70031. this.onBeforeComposeObservable = new BABYLON.Observable();
  70032. /**
  70033. * An event triggered when the glowing blurred texture has been merged in the scene.
  70034. * @type {BABYLON.Observable}
  70035. */
  70036. this.onAfterComposeObservable = new BABYLON.Observable();
  70037. /**
  70038. * An event triggered when the highlight layer changes its size.
  70039. * @type {BABYLON.Observable}
  70040. */
  70041. this.onSizeChangedObservable = new BABYLON.Observable();
  70042. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  70043. var engine = scene.getEngine();
  70044. this._engine = engine;
  70045. this._maxSize = this._engine.getCaps().maxTextureSize;
  70046. this._scene.highlightLayers.push(this);
  70047. // Warn on stencil.
  70048. if (!this._engine.isStencilEnable) {
  70049. 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 }");
  70050. }
  70051. // Adapt options
  70052. this._options = options || {
  70053. mainTextureRatio: 0.5,
  70054. blurTextureSizeRatio: 0.5,
  70055. blurHorizontalSize: 1.0,
  70056. blurVerticalSize: 1.0,
  70057. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  70058. };
  70059. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  70060. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  70061. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  70062. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  70063. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  70064. // VBO
  70065. var vertices = [];
  70066. vertices.push(1, 1);
  70067. vertices.push(-1, 1);
  70068. vertices.push(-1, -1);
  70069. vertices.push(1, -1);
  70070. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70071. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  70072. this._createIndexBuffer();
  70073. // Effect
  70074. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  70075. // Render target
  70076. this.setMainTextureSize();
  70077. // Create Textures and post processes
  70078. this.createTextureAndPostProcesses();
  70079. }
  70080. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  70081. /**
  70082. * Gets the horizontal size of the blur.
  70083. */
  70084. get: function () {
  70085. return this._horizontalBlurPostprocess.kernel;
  70086. },
  70087. /**
  70088. * Specifies the horizontal size of the blur.
  70089. */
  70090. set: function (value) {
  70091. this._horizontalBlurPostprocess.kernel = value;
  70092. },
  70093. enumerable: true,
  70094. configurable: true
  70095. });
  70096. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  70097. /**
  70098. * Gets the vertical size of the blur.
  70099. */
  70100. get: function () {
  70101. return this._verticalBlurPostprocess.kernel;
  70102. },
  70103. /**
  70104. * Specifies the vertical size of the blur.
  70105. */
  70106. set: function (value) {
  70107. this._verticalBlurPostprocess.kernel = value;
  70108. },
  70109. enumerable: true,
  70110. configurable: true
  70111. });
  70112. Object.defineProperty(HighlightLayer.prototype, "camera", {
  70113. /**
  70114. * Gets the camera attached to the layer.
  70115. */
  70116. get: function () {
  70117. return this._options.camera;
  70118. },
  70119. enumerable: true,
  70120. configurable: true
  70121. });
  70122. HighlightLayer.prototype._createIndexBuffer = function () {
  70123. var engine = this._scene.getEngine();
  70124. // Indices
  70125. var indices = [];
  70126. indices.push(0);
  70127. indices.push(1);
  70128. indices.push(2);
  70129. indices.push(0);
  70130. indices.push(2);
  70131. indices.push(3);
  70132. this._indexBuffer = engine.createIndexBuffer(indices);
  70133. };
  70134. HighlightLayer.prototype._rebuild = function () {
  70135. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  70136. this._createIndexBuffer();
  70137. };
  70138. /**
  70139. * Creates the render target textures and post processes used in the highlight layer.
  70140. */
  70141. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  70142. var _this = this;
  70143. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  70144. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  70145. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  70146. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  70147. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  70148. width: this._mainTextureDesiredSize.width,
  70149. height: this._mainTextureDesiredSize.height
  70150. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70151. this._mainTexture.activeCamera = this._options.camera;
  70152. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70153. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70154. this._mainTexture.anisotropicFilteringLevel = 1;
  70155. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  70156. this._mainTexture.renderParticles = false;
  70157. this._mainTexture.renderList = null;
  70158. this._mainTexture.ignoreCameraViewport = true;
  70159. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  70160. width: blurTextureWidth,
  70161. height: blurTextureHeight
  70162. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70163. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70164. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70165. this._blurTexture.anisotropicFilteringLevel = 16;
  70166. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  70167. this._blurTexture.renderParticles = false;
  70168. this._blurTexture.ignoreCameraViewport = true;
  70169. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  70170. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  70171. effect.setTexture("textureSampler", _this._mainTexture);
  70172. });
  70173. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  70174. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  70175. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  70176. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  70177. });
  70178. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  70179. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  70180. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  70181. });
  70182. }
  70183. else {
  70184. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  70185. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  70186. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  70187. });
  70188. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  70189. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  70190. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  70191. });
  70192. }
  70193. this._mainTexture.onAfterUnbindObservable.add(function () {
  70194. _this.onBeforeBlurObservable.notifyObservers(_this);
  70195. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture(), true);
  70196. _this.onAfterBlurObservable.notifyObservers(_this);
  70197. });
  70198. // Custom render function
  70199. var renderSubMesh = function (subMesh) {
  70200. var mesh = subMesh.getRenderingMesh();
  70201. var scene = _this._scene;
  70202. var engine = scene.getEngine();
  70203. // Culling
  70204. engine.setState(subMesh.getMaterial().backFaceCulling);
  70205. // Managing instances
  70206. var batch = mesh._getInstancesRenderList(subMesh._id);
  70207. if (batch.mustReturn) {
  70208. return;
  70209. }
  70210. // Excluded Mesh
  70211. if (_this._excludedMeshes[mesh.uniqueId]) {
  70212. return;
  70213. }
  70214. ;
  70215. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  70216. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  70217. var material = subMesh.getMaterial();
  70218. var emissiveTexture = null;
  70219. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  70220. emissiveTexture = material.emissiveTexture;
  70221. }
  70222. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  70223. engine.enableEffect(_this._glowMapGenerationEffect);
  70224. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  70225. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  70226. if (highlightLayerMesh) {
  70227. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  70228. }
  70229. else {
  70230. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  70231. }
  70232. // Alpha test
  70233. if (material && material.needAlphaTesting()) {
  70234. var alphaTexture = material.getAlphaTestTexture();
  70235. if (alphaTexture) {
  70236. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  70237. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70238. }
  70239. }
  70240. // Glow emissive only
  70241. if (emissiveTexture) {
  70242. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  70243. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  70244. }
  70245. // Bones
  70246. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70247. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70248. }
  70249. // Draw
  70250. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  70251. }
  70252. else {
  70253. // Need to reset refresh rate of the shadowMap
  70254. _this._mainTexture.resetRefreshCounter();
  70255. }
  70256. };
  70257. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70258. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  70259. var index;
  70260. var engine = _this._scene.getEngine();
  70261. if (depthOnlySubMeshes.length) {
  70262. engine.setColorWrite(false);
  70263. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70264. renderSubMesh(depthOnlySubMeshes.data[index]);
  70265. }
  70266. engine.setColorWrite(true);
  70267. }
  70268. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70269. renderSubMesh(opaqueSubMeshes.data[index]);
  70270. }
  70271. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70272. renderSubMesh(alphaTestSubMeshes.data[index]);
  70273. }
  70274. for (index = 0; index < transparentSubMeshes.length; index++) {
  70275. renderSubMesh(transparentSubMeshes.data[index]);
  70276. }
  70277. };
  70278. this._mainTexture.onClearObservable.add(function (engine) {
  70279. engine.clear(HighlightLayer.neutralColor, true, true, true);
  70280. });
  70281. };
  70282. /**
  70283. * Checks for the readiness of the element composing the layer.
  70284. * @param subMesh the mesh to check for
  70285. * @param useInstances specify wether or not to use instances to render the mesh
  70286. * @param emissiveTexture the associated emissive texture used to generate the glow
  70287. * @return true if ready otherwise, false
  70288. */
  70289. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  70290. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  70291. return false;
  70292. }
  70293. var defines = [];
  70294. var attribs = [BABYLON.VertexBuffer.PositionKind];
  70295. var mesh = subMesh.getMesh();
  70296. var material = subMesh.getMaterial();
  70297. var uv1 = false;
  70298. var uv2 = false;
  70299. // Alpha test
  70300. if (material && material.needAlphaTesting()) {
  70301. var alphaTexture = material.getAlphaTestTexture();
  70302. if (alphaTexture) {
  70303. defines.push("#define ALPHATEST");
  70304. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  70305. alphaTexture.coordinatesIndex === 1) {
  70306. defines.push("#define DIFFUSEUV2");
  70307. uv2 = true;
  70308. }
  70309. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70310. defines.push("#define DIFFUSEUV1");
  70311. uv1 = true;
  70312. }
  70313. }
  70314. }
  70315. // Emissive
  70316. if (emissiveTexture) {
  70317. defines.push("#define EMISSIVE");
  70318. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  70319. emissiveTexture.coordinatesIndex === 1) {
  70320. defines.push("#define EMISSIVEUV2");
  70321. uv2 = true;
  70322. }
  70323. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70324. defines.push("#define EMISSIVEUV1");
  70325. uv1 = true;
  70326. }
  70327. }
  70328. if (uv1) {
  70329. attribs.push(BABYLON.VertexBuffer.UVKind);
  70330. defines.push("#define UV1");
  70331. }
  70332. if (uv2) {
  70333. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70334. defines.push("#define UV2");
  70335. }
  70336. // Bones
  70337. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70338. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70339. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70340. if (mesh.numBoneInfluencers > 4) {
  70341. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70342. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70343. }
  70344. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70345. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  70346. }
  70347. else {
  70348. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70349. }
  70350. // Instances
  70351. if (useInstances) {
  70352. defines.push("#define INSTANCES");
  70353. attribs.push("world0");
  70354. attribs.push("world1");
  70355. attribs.push("world2");
  70356. attribs.push("world3");
  70357. }
  70358. // Get correct effect
  70359. var join = defines.join("\n");
  70360. if (this._cachedDefines !== join) {
  70361. this._cachedDefines = join;
  70362. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  70363. }
  70364. return this._glowMapGenerationEffect.isReady();
  70365. };
  70366. /**
  70367. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  70368. */
  70369. HighlightLayer.prototype.render = function () {
  70370. var currentEffect = this._glowMapMergeEffect;
  70371. // Check
  70372. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  70373. return;
  70374. var engine = this._scene.getEngine();
  70375. this.onBeforeComposeObservable.notifyObservers(this);
  70376. // Render
  70377. engine.enableEffect(currentEffect);
  70378. engine.setState(false);
  70379. // Cache
  70380. var previousStencilBuffer = engine.getStencilBuffer();
  70381. var previousStencilFunction = engine.getStencilFunction();
  70382. var previousStencilMask = engine.getStencilMask();
  70383. var previousStencilOperationPass = engine.getStencilOperationPass();
  70384. var previousStencilOperationFail = engine.getStencilOperationFail();
  70385. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  70386. var previousAlphaMode = engine.getAlphaMode();
  70387. // Texture
  70388. currentEffect.setTexture("textureSampler", this._blurTexture);
  70389. // VBOs
  70390. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  70391. // Stencil operations
  70392. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  70393. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  70394. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  70395. // Draw order
  70396. engine.setAlphaMode(this._options.alphaBlendingMode);
  70397. engine.setStencilMask(0x00);
  70398. engine.setStencilBuffer(true);
  70399. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  70400. if (this.outerGlow) {
  70401. currentEffect.setFloat("offset", 0);
  70402. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  70403. engine.draw(true, 0, 6);
  70404. }
  70405. if (this.innerGlow) {
  70406. currentEffect.setFloat("offset", 1);
  70407. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  70408. engine.draw(true, 0, 6);
  70409. }
  70410. // Restore Cache
  70411. engine.setStencilFunction(previousStencilFunction);
  70412. engine.setStencilMask(previousStencilMask);
  70413. engine.setAlphaMode(previousAlphaMode);
  70414. engine.setStencilBuffer(previousStencilBuffer);
  70415. engine.setStencilOperationPass(previousStencilOperationPass);
  70416. engine.setStencilOperationFail(previousStencilOperationFail);
  70417. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  70418. engine._stencilState.reset();
  70419. this.onAfterComposeObservable.notifyObservers(this);
  70420. // Handle size changes.
  70421. var size = this._mainTexture.getSize();
  70422. this.setMainTextureSize();
  70423. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  70424. // Recreate RTT and post processes on size change.
  70425. this.onSizeChangedObservable.notifyObservers(this);
  70426. this.disposeTextureAndPostProcesses();
  70427. this.createTextureAndPostProcesses();
  70428. }
  70429. };
  70430. /**
  70431. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  70432. * @param mesh The mesh to exclude from the highlight layer
  70433. */
  70434. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  70435. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  70436. if (!meshExcluded) {
  70437. this._excludedMeshes[mesh.uniqueId] = {
  70438. mesh: mesh,
  70439. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  70440. mesh.getEngine().setStencilBuffer(false);
  70441. }),
  70442. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  70443. mesh.getEngine().setStencilBuffer(true);
  70444. }),
  70445. };
  70446. }
  70447. };
  70448. /**
  70449. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  70450. * @param mesh The mesh to highlight
  70451. */
  70452. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  70453. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  70454. if (meshExcluded) {
  70455. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  70456. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  70457. }
  70458. this._excludedMeshes[mesh.uniqueId] = undefined;
  70459. };
  70460. /**
  70461. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  70462. * @param mesh The mesh to highlight
  70463. * @param color The color of the highlight
  70464. * @param glowEmissiveOnly Extract the glow from the emissive texture
  70465. */
  70466. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  70467. var _this = this;
  70468. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  70469. var meshHighlight = this._meshes[mesh.uniqueId];
  70470. if (meshHighlight) {
  70471. meshHighlight.color = color;
  70472. }
  70473. else {
  70474. this._meshes[mesh.uniqueId] = {
  70475. mesh: mesh,
  70476. color: color,
  70477. // Lambda required for capture due to Observable this context
  70478. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  70479. if (_this._excludedMeshes[mesh.uniqueId]) {
  70480. _this.defaultStencilReference(mesh);
  70481. }
  70482. else {
  70483. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  70484. }
  70485. }),
  70486. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  70487. glowEmissiveOnly: glowEmissiveOnly
  70488. };
  70489. }
  70490. this._shouldRender = true;
  70491. };
  70492. /**
  70493. * Remove a mesh from the highlight layer in order to make it stop glowing.
  70494. * @param mesh The mesh to highlight
  70495. */
  70496. HighlightLayer.prototype.removeMesh = function (mesh) {
  70497. var meshHighlight = this._meshes[mesh.uniqueId];
  70498. if (meshHighlight) {
  70499. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  70500. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  70501. }
  70502. this._meshes[mesh.uniqueId] = undefined;
  70503. this._shouldRender = false;
  70504. for (var meshHighlightToCheck in this._meshes) {
  70505. if (meshHighlightToCheck) {
  70506. this._shouldRender = true;
  70507. break;
  70508. }
  70509. }
  70510. };
  70511. /**
  70512. * Returns true if the layer contains information to display, otherwise false.
  70513. */
  70514. HighlightLayer.prototype.shouldRender = function () {
  70515. return this.isEnabled && this._shouldRender;
  70516. };
  70517. /**
  70518. * Sets the main texture desired size which is the closest power of two
  70519. * of the engine canvas size.
  70520. */
  70521. HighlightLayer.prototype.setMainTextureSize = function () {
  70522. if (this._options.mainTextureFixedSize) {
  70523. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  70524. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  70525. }
  70526. else {
  70527. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  70528. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  70529. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  70530. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  70531. }
  70532. };
  70533. /**
  70534. * Force the stencil to the normal expected value for none glowing parts
  70535. */
  70536. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  70537. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  70538. };
  70539. /**
  70540. * Dispose only the render target textures and post process.
  70541. */
  70542. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  70543. this._blurTexture.dispose();
  70544. this._mainTexture.dispose();
  70545. this._downSamplePostprocess.dispose();
  70546. this._horizontalBlurPostprocess.dispose();
  70547. this._verticalBlurPostprocess.dispose();
  70548. };
  70549. /**
  70550. * Dispose the highlight layer and free resources.
  70551. */
  70552. HighlightLayer.prototype.dispose = function () {
  70553. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70554. if (vertexBuffer) {
  70555. vertexBuffer.dispose();
  70556. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70557. }
  70558. if (this._indexBuffer) {
  70559. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  70560. this._indexBuffer = null;
  70561. }
  70562. // Clean textures and post processes
  70563. this.disposeTextureAndPostProcesses();
  70564. // Clean mesh references
  70565. for (var id in this._meshes) {
  70566. var meshHighlight = this._meshes[id];
  70567. if (meshHighlight && meshHighlight.mesh) {
  70568. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  70569. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  70570. }
  70571. }
  70572. this._meshes = null;
  70573. for (var id in this._excludedMeshes) {
  70574. var meshHighlight = this._excludedMeshes[id];
  70575. if (meshHighlight) {
  70576. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  70577. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  70578. }
  70579. }
  70580. this._excludedMeshes = null;
  70581. // Remove from scene
  70582. var index = this._scene.highlightLayers.indexOf(this, 0);
  70583. if (index > -1) {
  70584. this._scene.highlightLayers.splice(index, 1);
  70585. }
  70586. // Callback
  70587. this.onDisposeObservable.notifyObservers(this);
  70588. this.onDisposeObservable.clear();
  70589. this.onBeforeRenderMainTextureObservable.clear();
  70590. this.onBeforeBlurObservable.clear();
  70591. this.onBeforeComposeObservable.clear();
  70592. this.onAfterComposeObservable.clear();
  70593. this.onSizeChangedObservable.clear();
  70594. };
  70595. /**
  70596. * The neutral color used during the preparation of the glow effect.
  70597. * This is black by default as the blend operation is a blend operation.
  70598. */
  70599. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  70600. /**
  70601. * Stencil value used for glowing meshes.
  70602. */
  70603. HighlightLayer.glowingMeshStencilReference = 0x02;
  70604. /**
  70605. * Stencil value used for the other meshes in the scene.
  70606. */
  70607. HighlightLayer.normalMeshStencilReference = 0x01;
  70608. return HighlightLayer;
  70609. }());
  70610. BABYLON.HighlightLayer = HighlightLayer;
  70611. })(BABYLON || (BABYLON = {}));
  70612. //# sourceMappingURL=babylon.highlightlayer.js.map
  70613. var BABYLON;
  70614. (function (BABYLON) {
  70615. var AssetTaskState;
  70616. (function (AssetTaskState) {
  70617. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  70618. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  70619. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  70620. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  70621. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  70622. var AbstractAssetTask = (function () {
  70623. function AbstractAssetTask() {
  70624. this.isCompleted = false;
  70625. this.taskState = AssetTaskState.INIT;
  70626. }
  70627. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  70628. var _this = this;
  70629. this.taskState = AssetTaskState.RUNNING;
  70630. this.runTask(scene, function () {
  70631. _this.onDoneCallback(onSuccess, onError);
  70632. }, function (msg, exception) {
  70633. _this.onErrorCallback(onError, msg, exception);
  70634. });
  70635. };
  70636. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  70637. throw new Error("runTask is not implemented");
  70638. };
  70639. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  70640. this.taskState = AssetTaskState.ERROR;
  70641. this.errorObject = {
  70642. message: message,
  70643. exception: exception
  70644. };
  70645. if (this.onError) {
  70646. this.onError(this, message, exception);
  70647. }
  70648. onError();
  70649. };
  70650. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  70651. try {
  70652. this.taskState = AssetTaskState.DONE;
  70653. this.isCompleted = true;
  70654. if (this.onSuccess) {
  70655. this.onSuccess(this);
  70656. }
  70657. onSuccess();
  70658. }
  70659. catch (e) {
  70660. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  70661. }
  70662. };
  70663. return AbstractAssetTask;
  70664. }());
  70665. BABYLON.AbstractAssetTask = AbstractAssetTask;
  70666. var MeshAssetTask = (function (_super) {
  70667. __extends(MeshAssetTask, _super);
  70668. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  70669. var _this = _super.call(this) || this;
  70670. _this.name = name;
  70671. _this.meshesNames = meshesNames;
  70672. _this.rootUrl = rootUrl;
  70673. _this.sceneFilename = sceneFilename;
  70674. return _this;
  70675. }
  70676. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  70677. var _this = this;
  70678. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  70679. _this.loadedMeshes = meshes;
  70680. _this.loadedParticleSystems = particleSystems;
  70681. _this.loadedSkeletons = skeletons;
  70682. onSuccess();
  70683. }, null, function (scene, message, exception) {
  70684. onError(message, exception);
  70685. });
  70686. };
  70687. return MeshAssetTask;
  70688. }(AbstractAssetTask));
  70689. BABYLON.MeshAssetTask = MeshAssetTask;
  70690. var TextFileAssetTask = (function (_super) {
  70691. __extends(TextFileAssetTask, _super);
  70692. function TextFileAssetTask(name, url) {
  70693. var _this = _super.call(this) || this;
  70694. _this.name = name;
  70695. _this.url = url;
  70696. return _this;
  70697. }
  70698. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  70699. var _this = this;
  70700. BABYLON.Tools.LoadFile(this.url, function (data) {
  70701. _this.text = data;
  70702. onSuccess();
  70703. }, null, scene.database, false, function (request, exception) {
  70704. onError(request.status + " " + request.statusText, exception);
  70705. });
  70706. };
  70707. return TextFileAssetTask;
  70708. }(AbstractAssetTask));
  70709. BABYLON.TextFileAssetTask = TextFileAssetTask;
  70710. var BinaryFileAssetTask = (function (_super) {
  70711. __extends(BinaryFileAssetTask, _super);
  70712. function BinaryFileAssetTask(name, url) {
  70713. var _this = _super.call(this) || this;
  70714. _this.name = name;
  70715. _this.url = url;
  70716. return _this;
  70717. }
  70718. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  70719. var _this = this;
  70720. BABYLON.Tools.LoadFile(this.url, function (data) {
  70721. _this.data = data;
  70722. onSuccess();
  70723. }, null, scene.database, true, function (request, exception) {
  70724. onError(request.status + " " + request.statusText, exception);
  70725. });
  70726. };
  70727. return BinaryFileAssetTask;
  70728. }(AbstractAssetTask));
  70729. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  70730. var ImageAssetTask = (function (_super) {
  70731. __extends(ImageAssetTask, _super);
  70732. function ImageAssetTask(name, url) {
  70733. var _this = _super.call(this) || this;
  70734. _this.name = name;
  70735. _this.url = url;
  70736. return _this;
  70737. }
  70738. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  70739. var _this = this;
  70740. var img = new Image();
  70741. BABYLON.Tools.SetCorsBehavior(this.url, img);
  70742. img.onload = function () {
  70743. _this.image = img;
  70744. onSuccess();
  70745. };
  70746. img.onerror = function (err) {
  70747. onError("Error loading image", err);
  70748. };
  70749. img.src = this.url;
  70750. };
  70751. return ImageAssetTask;
  70752. }(AbstractAssetTask));
  70753. BABYLON.ImageAssetTask = ImageAssetTask;
  70754. var TextureAssetTask = (function (_super) {
  70755. __extends(TextureAssetTask, _super);
  70756. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  70757. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70758. var _this = _super.call(this) || this;
  70759. _this.name = name;
  70760. _this.url = url;
  70761. _this.noMipmap = noMipmap;
  70762. _this.invertY = invertY;
  70763. _this.samplingMode = samplingMode;
  70764. return _this;
  70765. }
  70766. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  70767. var onload = function () {
  70768. onSuccess();
  70769. };
  70770. var onerror = function (msg, exception) {
  70771. onError(msg, exception);
  70772. };
  70773. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  70774. };
  70775. return TextureAssetTask;
  70776. }(AbstractAssetTask));
  70777. BABYLON.TextureAssetTask = TextureAssetTask;
  70778. var CubeTextureAssetTask = (function (_super) {
  70779. __extends(CubeTextureAssetTask, _super);
  70780. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  70781. var _this = _super.call(this) || this;
  70782. _this.name = name;
  70783. _this.url = url;
  70784. _this.extensions = extensions;
  70785. _this.noMipmap = noMipmap;
  70786. _this.files = files;
  70787. return _this;
  70788. }
  70789. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  70790. var onload = function () {
  70791. onSuccess();
  70792. };
  70793. var onerror = function (msg, exception) {
  70794. onError(msg, exception);
  70795. };
  70796. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  70797. };
  70798. return CubeTextureAssetTask;
  70799. }(AbstractAssetTask));
  70800. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  70801. var HDRCubeTextureAssetTask = (function (_super) {
  70802. __extends(HDRCubeTextureAssetTask, _super);
  70803. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  70804. if (noMipmap === void 0) { noMipmap = false; }
  70805. if (generateHarmonics === void 0) { generateHarmonics = true; }
  70806. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  70807. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  70808. var _this = _super.call(this) || this;
  70809. _this.name = name;
  70810. _this.url = url;
  70811. _this.size = size;
  70812. _this.noMipmap = noMipmap;
  70813. _this.generateHarmonics = generateHarmonics;
  70814. _this.useInGammaSpace = useInGammaSpace;
  70815. _this.usePMREMGenerator = usePMREMGenerator;
  70816. return _this;
  70817. }
  70818. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  70819. var onload = function () {
  70820. onSuccess();
  70821. };
  70822. var onerror = function (message, exception) {
  70823. onError(message, exception);
  70824. };
  70825. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  70826. };
  70827. return HDRCubeTextureAssetTask;
  70828. }(AbstractAssetTask));
  70829. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  70830. var AssetsManager = (function () {
  70831. function AssetsManager(scene) {
  70832. this.tasks = new Array();
  70833. this.waitingTasksCount = 0;
  70834. //Observables
  70835. this.onTaskSuccessObservable = new BABYLON.Observable();
  70836. this.onTaskErrorObservable = new BABYLON.Observable();
  70837. this.onTasksDoneObservable = new BABYLON.Observable();
  70838. this.useDefaultLoadingScreen = true;
  70839. this._scene = scene;
  70840. }
  70841. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  70842. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  70843. this.tasks.push(task);
  70844. return task;
  70845. };
  70846. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  70847. var task = new TextFileAssetTask(taskName, url);
  70848. this.tasks.push(task);
  70849. return task;
  70850. };
  70851. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  70852. var task = new BinaryFileAssetTask(taskName, url);
  70853. this.tasks.push(task);
  70854. return task;
  70855. };
  70856. AssetsManager.prototype.addImageTask = function (taskName, url) {
  70857. var task = new ImageAssetTask(taskName, url);
  70858. this.tasks.push(task);
  70859. return task;
  70860. };
  70861. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  70862. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70863. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  70864. this.tasks.push(task);
  70865. return task;
  70866. };
  70867. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  70868. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  70869. this.tasks.push(task);
  70870. return task;
  70871. };
  70872. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  70873. if (noMipmap === void 0) { noMipmap = false; }
  70874. if (generateHarmonics === void 0) { generateHarmonics = true; }
  70875. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  70876. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  70877. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  70878. this.tasks.push(task);
  70879. return task;
  70880. };
  70881. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  70882. this.waitingTasksCount--;
  70883. if (this.waitingTasksCount === 0) {
  70884. try {
  70885. if (this.onFinish) {
  70886. this.onFinish(this.tasks);
  70887. }
  70888. this.onTasksDoneObservable.notifyObservers(this.tasks);
  70889. }
  70890. catch (e) {
  70891. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  70892. console.log(e);
  70893. }
  70894. this._scene.getEngine().hideLoadingUI();
  70895. }
  70896. };
  70897. AssetsManager.prototype._runTask = function (task) {
  70898. var _this = this;
  70899. var done = function () {
  70900. try {
  70901. if (_this.onTaskSuccess) {
  70902. _this.onTaskSuccess(task);
  70903. }
  70904. _this.onTaskSuccessObservable.notifyObservers(task);
  70905. _this._decreaseWaitingTasksCount();
  70906. }
  70907. catch (e) {
  70908. error("Error executing task success callbacks", e);
  70909. }
  70910. };
  70911. var error = function (message, exception) {
  70912. task.errorObject = task.errorObject || {
  70913. message: message,
  70914. exception: exception
  70915. };
  70916. if (_this.onTaskError) {
  70917. _this.onTaskError(task);
  70918. }
  70919. _this.onTaskErrorObservable.notifyObservers(task);
  70920. _this._decreaseWaitingTasksCount();
  70921. };
  70922. task.run(this._scene, done, error);
  70923. };
  70924. AssetsManager.prototype.reset = function () {
  70925. this.tasks = new Array();
  70926. return this;
  70927. };
  70928. AssetsManager.prototype.load = function () {
  70929. this.waitingTasksCount = this.tasks.length;
  70930. if (this.waitingTasksCount === 0) {
  70931. if (this.onFinish) {
  70932. this.onFinish(this.tasks);
  70933. }
  70934. this.onTasksDoneObservable.notifyObservers(this.tasks);
  70935. return this;
  70936. }
  70937. if (this.useDefaultLoadingScreen) {
  70938. this._scene.getEngine().displayLoadingUI();
  70939. }
  70940. for (var index = 0; index < this.tasks.length; index++) {
  70941. var task = this.tasks[index];
  70942. this._runTask(task);
  70943. }
  70944. return this;
  70945. };
  70946. return AssetsManager;
  70947. }());
  70948. BABYLON.AssetsManager = AssetsManager;
  70949. })(BABYLON || (BABYLON = {}));
  70950. //# sourceMappingURL=babylon.assetsManager.js.map
  70951. var BABYLON;
  70952. (function (BABYLON) {
  70953. var MapTexture = (function (_super) {
  70954. __extends(MapTexture, _super);
  70955. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  70956. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70957. if (useMipMap === void 0) { useMipMap = false; }
  70958. if (margin === void 0) { margin = 0; }
  70959. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  70960. _this.name = name;
  70961. _this._size = size;
  70962. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70963. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70964. // Create the rectPackMap that will allocate portion of the texture
  70965. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  70966. // Create the texture that will store the content
  70967. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  70968. return _this;
  70969. }
  70970. /**
  70971. * Allocate a rectangle of a given size in the texture map
  70972. * @param size the size of the rectangle to allocation
  70973. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  70974. */
  70975. MapTexture.prototype.allocateRect = function (size) {
  70976. return this._rectPackingMap.addRect(size);
  70977. };
  70978. /**
  70979. * Free a given rectangle from the texture map
  70980. * @param rectInfo the instance corresponding to the rect to free.
  70981. */
  70982. MapTexture.prototype.freeRect = function (rectInfo) {
  70983. if (rectInfo) {
  70984. rectInfo.freeContent();
  70985. }
  70986. };
  70987. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  70988. /**
  70989. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  70990. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  70991. * @returns {}
  70992. */
  70993. get: function () {
  70994. return this._rectPackingMap.freeSpace;
  70995. },
  70996. enumerable: true,
  70997. configurable: true
  70998. });
  70999. /**
  71000. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  71001. * 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.
  71002. * Don't forget to call unbindTexture when you're done rendering
  71003. * @param rect the zone to render to
  71004. * @param clear true to clear the portion's color/depth data
  71005. */
  71006. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  71007. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  71008. };
  71009. /**
  71010. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  71011. * 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.
  71012. * Don't forget to call unbindTexture when you're done rendering
  71013. * @param pos the position into the texture
  71014. * @param size the portion to fit the clip space to
  71015. * @param clear true to clear the portion's color/depth data
  71016. */
  71017. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  71018. var engine = this.getScene().getEngine();
  71019. engine.bindFramebuffer(this._texture);
  71020. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  71021. if (clear) {
  71022. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  71023. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  71024. }
  71025. };
  71026. /**
  71027. * Unbind the texture map from the rendering engine.
  71028. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  71029. * @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.
  71030. */
  71031. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  71032. // Dump ?
  71033. if (dumpForDebug) {
  71034. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  71035. }
  71036. var engine = this.getScene().getEngine();
  71037. if (this._replacedViewport) {
  71038. engine.setViewport(this._replacedViewport);
  71039. this._replacedViewport = null;
  71040. }
  71041. engine.unBindFramebuffer(this._texture);
  71042. };
  71043. Object.defineProperty(MapTexture.prototype, "canRescale", {
  71044. get: function () {
  71045. return false;
  71046. },
  71047. enumerable: true,
  71048. configurable: true
  71049. });
  71050. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  71051. // Anyway, there's not much point to use this method for this kind of texture I guess
  71052. MapTexture.prototype.clone = function () {
  71053. return null;
  71054. };
  71055. return MapTexture;
  71056. }(BABYLON.Texture));
  71057. BABYLON.MapTexture = MapTexture;
  71058. })(BABYLON || (BABYLON = {}));
  71059. //# sourceMappingURL=babylon.mapTexture.js.map
  71060. var BABYLON;
  71061. (function (BABYLON) {
  71062. /**
  71063. * This class describe a rectangle that were added to the map.
  71064. * You have access to its coordinates either in pixel or normalized (UV)
  71065. */
  71066. var PackedRect = (function () {
  71067. function PackedRect(root, parent, pos, size) {
  71068. this._pos = pos;
  71069. this._size = size;
  71070. this._root = root;
  71071. this._parent = parent;
  71072. this._contentSize = null;
  71073. this._bottomNode = null;
  71074. this._leftNode = null;
  71075. this._initialSize = null;
  71076. this._rightNode = null;
  71077. }
  71078. Object.defineProperty(PackedRect.prototype, "pos", {
  71079. /**
  71080. * @returns the position of this node into the map
  71081. */
  71082. get: function () {
  71083. return this._pos;
  71084. },
  71085. enumerable: true,
  71086. configurable: true
  71087. });
  71088. Object.defineProperty(PackedRect.prototype, "contentSize", {
  71089. /**
  71090. * @returns the size of the rectangle this node handles
  71091. */
  71092. get: function () {
  71093. return this._contentSize;
  71094. },
  71095. enumerable: true,
  71096. configurable: true
  71097. });
  71098. /**
  71099. * Retrieve the inner position (considering the margin) and stores it into the res object
  71100. * @param res must be a valid Vector2 that will contain the inner position after this call
  71101. */
  71102. PackedRect.prototype.getInnerPosToRef = function (res) {
  71103. var m = this._root._margin;
  71104. res.x = this._pos.x + m;
  71105. res.y = this._pos.y + m;
  71106. };
  71107. /**
  71108. * Retrieve the inner size (considering the margin) and stores it into the res object
  71109. * @param res must be a valid Size that will contain the inner size after this call
  71110. */
  71111. PackedRect.prototype.getInnerSizeToRef = function (res) {
  71112. var m = this._root._margin;
  71113. res.width = this._contentSize.width - (m * 2);
  71114. res.height = this._contentSize.height - (m * 2);
  71115. };
  71116. Object.defineProperty(PackedRect.prototype, "UVs", {
  71117. /**
  71118. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  71119. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  71120. */
  71121. get: function () {
  71122. if (!this._contentSize) {
  71123. throw new Error("Can't compute UVs for this object because it's nor allocated");
  71124. }
  71125. return this.getUVsForCustomSize(this._contentSize);
  71126. },
  71127. enumerable: true,
  71128. configurable: true
  71129. });
  71130. /**
  71131. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  71132. * and then using only a part of the PackRect.
  71133. * This method will return the UVs for this part by given the custom size of what you really use
  71134. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  71135. */
  71136. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  71137. var mainWidth = this._root._size.width;
  71138. var mainHeight = this._root._size.height;
  71139. var margin = this._root._margin;
  71140. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  71141. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  71142. var uvs = new Array();
  71143. uvs.push(topLeft);
  71144. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  71145. uvs.push(rightBottom);
  71146. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  71147. return uvs;
  71148. };
  71149. /**
  71150. * Free this rectangle from the map.
  71151. * Call this method when you no longer need the rectangle to be in the map.
  71152. */
  71153. PackedRect.prototype.freeContent = function () {
  71154. if (!this.contentSize) {
  71155. return;
  71156. }
  71157. this._contentSize = null;
  71158. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  71159. this.attemptDefrag();
  71160. };
  71161. Object.defineProperty(PackedRect.prototype, "isUsed", {
  71162. get: function () {
  71163. return this._contentSize != null || this._leftNode != null;
  71164. },
  71165. enumerable: true,
  71166. configurable: true
  71167. });
  71168. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  71169. var node = this.findNode(contentSize);
  71170. // Not enough space...
  71171. if (!node) {
  71172. return null;
  71173. }
  71174. node.splitNode(contentSize);
  71175. return node;
  71176. };
  71177. PackedRect.prototype.findNode = function (size) {
  71178. var resNode = null;
  71179. var margin = this._root._margin * 2;
  71180. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  71181. if (this.isUsed) {
  71182. if (this._leftNode) {
  71183. resNode = this._leftNode.findNode(size);
  71184. }
  71185. if (!resNode && this._rightNode) {
  71186. resNode = this._rightNode.findNode(size);
  71187. }
  71188. if (!resNode && this._bottomNode) {
  71189. resNode = this._bottomNode.findNode(size);
  71190. }
  71191. }
  71192. else if (this._initialSize) {
  71193. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  71194. resNode = this;
  71195. }
  71196. else {
  71197. return null;
  71198. }
  71199. }
  71200. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  71201. resNode = this;
  71202. }
  71203. return resNode;
  71204. };
  71205. PackedRect.prototype.splitNode = function (contentSize) {
  71206. var cs = PackedRect.TpsSize;
  71207. var margin = this._root._margin * 2;
  71208. cs.copyFrom(contentSize);
  71209. cs.width += margin;
  71210. cs.height += margin;
  71211. // 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)
  71212. if (!this._contentSize && this._initialSize) {
  71213. this._contentSize = cs.clone();
  71214. 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));
  71215. return this._leftNode.splitNode(contentSize);
  71216. }
  71217. else {
  71218. this._contentSize = cs.clone();
  71219. this._initialSize = cs.clone();
  71220. if (cs.width !== this._size.width) {
  71221. 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));
  71222. }
  71223. if (cs.height !== this._size.height) {
  71224. 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));
  71225. }
  71226. return this;
  71227. }
  71228. };
  71229. PackedRect.prototype.attemptDefrag = function () {
  71230. if (!this.isUsed && this.isRecursiveFree) {
  71231. this.clearNode();
  71232. if (this._parent) {
  71233. this._parent.attemptDefrag();
  71234. }
  71235. }
  71236. };
  71237. PackedRect.prototype.clearNode = function () {
  71238. this._initialSize = null;
  71239. this._rightNode = null;
  71240. this._bottomNode = null;
  71241. };
  71242. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  71243. get: function () {
  71244. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  71245. },
  71246. enumerable: true,
  71247. configurable: true
  71248. });
  71249. PackedRect.prototype.evalFreeSize = function (size) {
  71250. var levelSize = 0;
  71251. if (!this.isUsed) {
  71252. var margin = this._root._margin;
  71253. var is = this._initialSize;
  71254. if (is) {
  71255. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  71256. }
  71257. else {
  71258. var size_1 = this._size;
  71259. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  71260. }
  71261. }
  71262. if (this._rightNode) {
  71263. levelSize += this._rightNode.evalFreeSize(0);
  71264. }
  71265. if (this._bottomNode) {
  71266. levelSize += this._bottomNode.evalFreeSize(0);
  71267. }
  71268. return levelSize + size;
  71269. };
  71270. PackedRect.TpsSize = BABYLON.Size.Zero();
  71271. return PackedRect;
  71272. }());
  71273. BABYLON.PackedRect = PackedRect;
  71274. /**
  71275. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  71276. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  71277. * 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.
  71278. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  71279. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  71280. */
  71281. var RectPackingMap = (function (_super) {
  71282. __extends(RectPackingMap, _super);
  71283. /**
  71284. * Create an instance of the object with a dimension using the given size
  71285. * @param size The dimension of the rectangle that will contain all the sub ones.
  71286. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  71287. */
  71288. function RectPackingMap(size, margin) {
  71289. if (margin === void 0) { margin = 0; }
  71290. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  71291. _this._margin = margin;
  71292. _this._root = _this;
  71293. return _this;
  71294. }
  71295. /**
  71296. * Add a rectangle, finding the best location to store it into the map
  71297. * @param size the dimension of the rectangle to store
  71298. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  71299. */
  71300. RectPackingMap.prototype.addRect = function (size) {
  71301. var node = this.findAndSplitNode(size);
  71302. return node;
  71303. };
  71304. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  71305. /**
  71306. * Return the current space free normalized between [0;1]
  71307. * @returns {}
  71308. */
  71309. get: function () {
  71310. var freeSize = 0;
  71311. freeSize = this.evalFreeSize(freeSize);
  71312. return freeSize / (this._size.width * this._size.height);
  71313. },
  71314. enumerable: true,
  71315. configurable: true
  71316. });
  71317. return RectPackingMap;
  71318. }(PackedRect));
  71319. BABYLON.RectPackingMap = RectPackingMap;
  71320. })(BABYLON || (BABYLON = {}));
  71321. //# sourceMappingURL=babylon.rectPackingMap.js.map
  71322. var BABYLON;
  71323. (function (BABYLON) {
  71324. var serializedGeometries = [];
  71325. var serializeGeometry = function (geometry, serializationGeometries) {
  71326. if (serializedGeometries[geometry.id]) {
  71327. return;
  71328. }
  71329. if (geometry.doNotSerialize) {
  71330. return;
  71331. }
  71332. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  71333. serializationGeometries.boxes.push(geometry.serialize());
  71334. }
  71335. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  71336. serializationGeometries.spheres.push(geometry.serialize());
  71337. }
  71338. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  71339. serializationGeometries.cylinders.push(geometry.serialize());
  71340. }
  71341. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  71342. serializationGeometries.toruses.push(geometry.serialize());
  71343. }
  71344. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  71345. serializationGeometries.grounds.push(geometry.serialize());
  71346. }
  71347. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  71348. serializationGeometries.planes.push(geometry.serialize());
  71349. }
  71350. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  71351. serializationGeometries.torusKnots.push(geometry.serialize());
  71352. }
  71353. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  71354. throw new Error("Unknown primitive type");
  71355. }
  71356. else {
  71357. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  71358. }
  71359. serializedGeometries[geometry.id] = true;
  71360. };
  71361. var serializeMesh = function (mesh, serializationScene) {
  71362. var serializationObject = {};
  71363. // Geometry
  71364. var geometry = mesh._geometry;
  71365. if (geometry) {
  71366. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  71367. // 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
  71368. serializeGeometry(geometry, serializationScene.geometries);
  71369. }
  71370. }
  71371. // Custom
  71372. if (mesh.serialize) {
  71373. mesh.serialize(serializationObject);
  71374. }
  71375. return serializationObject;
  71376. };
  71377. var finalizeSingleMesh = function (mesh, serializationObject) {
  71378. //only works if the mesh is already loaded
  71379. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  71380. //serialize material
  71381. if (mesh.material) {
  71382. if (mesh.material instanceof BABYLON.StandardMaterial) {
  71383. serializationObject.materials = serializationObject.materials || [];
  71384. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  71385. serializationObject.materials.push(mesh.material.serialize());
  71386. }
  71387. }
  71388. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  71389. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  71390. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  71391. serializationObject.multiMaterials.push(mesh.material.serialize());
  71392. }
  71393. }
  71394. }
  71395. //serialize geometry
  71396. var geometry = mesh._geometry;
  71397. if (geometry) {
  71398. if (!serializationObject.geometries) {
  71399. serializationObject.geometries = {};
  71400. serializationObject.geometries.boxes = [];
  71401. serializationObject.geometries.spheres = [];
  71402. serializationObject.geometries.cylinders = [];
  71403. serializationObject.geometries.toruses = [];
  71404. serializationObject.geometries.grounds = [];
  71405. serializationObject.geometries.planes = [];
  71406. serializationObject.geometries.torusKnots = [];
  71407. serializationObject.geometries.vertexData = [];
  71408. }
  71409. serializeGeometry(geometry, serializationObject.geometries);
  71410. }
  71411. // Skeletons
  71412. if (mesh.skeleton) {
  71413. serializationObject.skeletons = serializationObject.skeletons || [];
  71414. serializationObject.skeletons.push(mesh.skeleton.serialize());
  71415. }
  71416. //serialize the actual mesh
  71417. serializationObject.meshes = serializationObject.meshes || [];
  71418. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  71419. }
  71420. };
  71421. var SceneSerializer = (function () {
  71422. function SceneSerializer() {
  71423. }
  71424. SceneSerializer.ClearCache = function () {
  71425. serializedGeometries = [];
  71426. };
  71427. SceneSerializer.Serialize = function (scene) {
  71428. var serializationObject = {};
  71429. SceneSerializer.ClearCache();
  71430. // Scene
  71431. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  71432. serializationObject.autoClear = scene.autoClear;
  71433. serializationObject.clearColor = scene.clearColor.asArray();
  71434. serializationObject.ambientColor = scene.ambientColor.asArray();
  71435. serializationObject.gravity = scene.gravity.asArray();
  71436. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  71437. serializationObject.workerCollisions = scene.workerCollisions;
  71438. // Fog
  71439. if (scene.fogMode && scene.fogMode !== 0) {
  71440. serializationObject.fogMode = scene.fogMode;
  71441. serializationObject.fogColor = scene.fogColor.asArray();
  71442. serializationObject.fogStart = scene.fogStart;
  71443. serializationObject.fogEnd = scene.fogEnd;
  71444. serializationObject.fogDensity = scene.fogDensity;
  71445. }
  71446. //Physics
  71447. if (scene.isPhysicsEnabled()) {
  71448. serializationObject.physicsEnabled = true;
  71449. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  71450. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  71451. }
  71452. // Metadata
  71453. if (scene.metadata) {
  71454. serializationObject.metadata = scene.metadata;
  71455. }
  71456. // Morph targets
  71457. serializationObject.morphTargetManagers = [];
  71458. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  71459. var abstractMesh = _a[_i];
  71460. var manager = abstractMesh.morphTargetManager;
  71461. if (manager) {
  71462. serializationObject.morphTargetManagers.push(manager.serialize());
  71463. }
  71464. }
  71465. // Lights
  71466. serializationObject.lights = [];
  71467. var index;
  71468. var light;
  71469. for (index = 0; index < scene.lights.length; index++) {
  71470. light = scene.lights[index];
  71471. if (!light.doNotSerialize) {
  71472. serializationObject.lights.push(light.serialize());
  71473. }
  71474. }
  71475. // Cameras
  71476. serializationObject.cameras = [];
  71477. for (index = 0; index < scene.cameras.length; index++) {
  71478. var camera = scene.cameras[index];
  71479. if (!camera.doNotSerialize) {
  71480. serializationObject.cameras.push(camera.serialize());
  71481. }
  71482. }
  71483. if (scene.activeCamera) {
  71484. serializationObject.activeCameraID = scene.activeCamera.id;
  71485. }
  71486. // Animations
  71487. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  71488. // Materials
  71489. serializationObject.materials = [];
  71490. serializationObject.multiMaterials = [];
  71491. var material;
  71492. for (index = 0; index < scene.materials.length; index++) {
  71493. material = scene.materials[index];
  71494. if (!material.doNotSerialize) {
  71495. serializationObject.materials.push(material.serialize());
  71496. }
  71497. }
  71498. // MultiMaterials
  71499. serializationObject.multiMaterials = [];
  71500. for (index = 0; index < scene.multiMaterials.length; index++) {
  71501. var multiMaterial = scene.multiMaterials[index];
  71502. serializationObject.multiMaterials.push(multiMaterial.serialize());
  71503. }
  71504. // Skeletons
  71505. serializationObject.skeletons = [];
  71506. for (index = 0; index < scene.skeletons.length; index++) {
  71507. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  71508. }
  71509. // Geometries
  71510. serializationObject.geometries = {};
  71511. serializationObject.geometries.boxes = [];
  71512. serializationObject.geometries.spheres = [];
  71513. serializationObject.geometries.cylinders = [];
  71514. serializationObject.geometries.toruses = [];
  71515. serializationObject.geometries.grounds = [];
  71516. serializationObject.geometries.planes = [];
  71517. serializationObject.geometries.torusKnots = [];
  71518. serializationObject.geometries.vertexData = [];
  71519. serializedGeometries = [];
  71520. var geometries = scene.getGeometries();
  71521. for (index = 0; index < geometries.length; index++) {
  71522. var geometry = geometries[index];
  71523. if (geometry.isReady()) {
  71524. serializeGeometry(geometry, serializationObject.geometries);
  71525. }
  71526. }
  71527. // Meshes
  71528. serializationObject.meshes = [];
  71529. for (index = 0; index < scene.meshes.length; index++) {
  71530. var abstractMesh = scene.meshes[index];
  71531. if (abstractMesh instanceof BABYLON.Mesh) {
  71532. var mesh = abstractMesh;
  71533. if (!mesh.doNotSerialize) {
  71534. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  71535. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  71536. }
  71537. }
  71538. }
  71539. }
  71540. // Particles Systems
  71541. serializationObject.particleSystems = [];
  71542. for (index = 0; index < scene.particleSystems.length; index++) {
  71543. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  71544. }
  71545. // Lens flares
  71546. serializationObject.lensFlareSystems = [];
  71547. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  71548. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  71549. }
  71550. // Shadows
  71551. serializationObject.shadowGenerators = [];
  71552. for (index = 0; index < scene.lights.length; index++) {
  71553. light = scene.lights[index];
  71554. var shadowGenerator = light.getShadowGenerator();
  71555. if (shadowGenerator) {
  71556. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  71557. }
  71558. }
  71559. // Action Manager
  71560. if (scene.actionManager) {
  71561. serializationObject.actions = scene.actionManager.serialize("scene");
  71562. }
  71563. // Audio
  71564. serializationObject.sounds = [];
  71565. for (index = 0; index < scene.soundTracks.length; index++) {
  71566. var soundtrack = scene.soundTracks[index];
  71567. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  71568. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  71569. }
  71570. }
  71571. return serializationObject;
  71572. };
  71573. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  71574. if (withParents === void 0) { withParents = false; }
  71575. if (withChildren === void 0) { withChildren = false; }
  71576. var serializationObject = {};
  71577. SceneSerializer.ClearCache();
  71578. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  71579. if (withParents || withChildren) {
  71580. //deliberate for loop! not for each, appended should be processed as well.
  71581. for (var i = 0; i < toSerialize.length; ++i) {
  71582. if (withChildren) {
  71583. toSerialize[i].getDescendants().forEach(function (node) {
  71584. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  71585. toSerialize.push(node);
  71586. }
  71587. });
  71588. }
  71589. //make sure the array doesn't contain the object already
  71590. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  71591. toSerialize.push(toSerialize[i].parent);
  71592. }
  71593. }
  71594. }
  71595. toSerialize.forEach(function (mesh) {
  71596. finalizeSingleMesh(mesh, serializationObject);
  71597. });
  71598. return serializationObject;
  71599. };
  71600. return SceneSerializer;
  71601. }());
  71602. BABYLON.SceneSerializer = SceneSerializer;
  71603. })(BABYLON || (BABYLON = {}));
  71604. //# sourceMappingURL=babylon.sceneSerializer.js.map
  71605. var BABYLON;
  71606. (function (BABYLON) {
  71607. var ReflectionProbe = (function () {
  71608. function ReflectionProbe(name, size, scene, generateMipMaps) {
  71609. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71610. var _this = this;
  71611. this.name = name;
  71612. this._viewMatrix = BABYLON.Matrix.Identity();
  71613. this._target = BABYLON.Vector3.Zero();
  71614. this._add = BABYLON.Vector3.Zero();
  71615. this.invertYAxis = false;
  71616. this.position = BABYLON.Vector3.Zero();
  71617. this._scene = scene;
  71618. this._scene.reflectionProbes.push(this);
  71619. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  71620. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  71621. switch (faceIndex) {
  71622. case 0:
  71623. _this._add.copyFromFloats(1, 0, 0);
  71624. break;
  71625. case 1:
  71626. _this._add.copyFromFloats(-1, 0, 0);
  71627. break;
  71628. case 2:
  71629. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  71630. break;
  71631. case 3:
  71632. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  71633. break;
  71634. case 4:
  71635. _this._add.copyFromFloats(0, 0, 1);
  71636. break;
  71637. case 5:
  71638. _this._add.copyFromFloats(0, 0, -1);
  71639. break;
  71640. }
  71641. if (_this._attachedMesh) {
  71642. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  71643. }
  71644. _this.position.addToRef(_this._add, _this._target);
  71645. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  71646. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  71647. });
  71648. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  71649. scene.updateTransformMatrix(true);
  71650. });
  71651. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  71652. }
  71653. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  71654. get: function () {
  71655. return this._renderTargetTexture.samples;
  71656. },
  71657. set: function (value) {
  71658. this._renderTargetTexture.samples = value;
  71659. },
  71660. enumerable: true,
  71661. configurable: true
  71662. });
  71663. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  71664. get: function () {
  71665. return this._renderTargetTexture.refreshRate;
  71666. },
  71667. set: function (value) {
  71668. this._renderTargetTexture.refreshRate = value;
  71669. },
  71670. enumerable: true,
  71671. configurable: true
  71672. });
  71673. ReflectionProbe.prototype.getScene = function () {
  71674. return this._scene;
  71675. };
  71676. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  71677. get: function () {
  71678. return this._renderTargetTexture;
  71679. },
  71680. enumerable: true,
  71681. configurable: true
  71682. });
  71683. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  71684. get: function () {
  71685. return this._renderTargetTexture.renderList;
  71686. },
  71687. enumerable: true,
  71688. configurable: true
  71689. });
  71690. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  71691. this._attachedMesh = mesh;
  71692. };
  71693. /**
  71694. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  71695. *
  71696. * @param renderingGroupId The rendering group id corresponding to its index
  71697. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  71698. */
  71699. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  71700. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  71701. };
  71702. ReflectionProbe.prototype.dispose = function () {
  71703. var index = this._scene.reflectionProbes.indexOf(this);
  71704. if (index !== -1) {
  71705. // Remove from the scene if found
  71706. this._scene.reflectionProbes.splice(index, 1);
  71707. }
  71708. if (this._renderTargetTexture) {
  71709. this._renderTargetTexture.dispose();
  71710. this._renderTargetTexture = null;
  71711. }
  71712. };
  71713. return ReflectionProbe;
  71714. }());
  71715. BABYLON.ReflectionProbe = ReflectionProbe;
  71716. })(BABYLON || (BABYLON = {}));
  71717. //# sourceMappingURL=babylon.reflectionProbe.js.map
  71718. var BABYLON;
  71719. (function (BABYLON) {
  71720. var Layer = (function () {
  71721. function Layer(name, imgUrl, scene, isBackground, color) {
  71722. this.name = name;
  71723. this.scale = new BABYLON.Vector2(1, 1);
  71724. this.offset = new BABYLON.Vector2(0, 0);
  71725. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  71726. this.layerMask = 0x0FFFFFFF;
  71727. this._vertexBuffers = {};
  71728. // Events
  71729. /**
  71730. * An event triggered when the layer is disposed.
  71731. * @type {BABYLON.Observable}
  71732. */
  71733. this.onDisposeObservable = new BABYLON.Observable();
  71734. /**
  71735. * An event triggered before rendering the scene
  71736. * @type {BABYLON.Observable}
  71737. */
  71738. this.onBeforeRenderObservable = new BABYLON.Observable();
  71739. /**
  71740. * An event triggered after rendering the scene
  71741. * @type {BABYLON.Observable}
  71742. */
  71743. this.onAfterRenderObservable = new BABYLON.Observable();
  71744. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  71745. this.isBackground = isBackground === undefined ? true : isBackground;
  71746. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  71747. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71748. this._scene.layers.push(this);
  71749. var engine = this._scene.getEngine();
  71750. // VBO
  71751. var vertices = [];
  71752. vertices.push(1, 1);
  71753. vertices.push(-1, 1);
  71754. vertices.push(-1, -1);
  71755. vertices.push(1, -1);
  71756. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71757. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  71758. this._createIndexBuffer();
  71759. // Effects
  71760. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  71761. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  71762. }
  71763. Object.defineProperty(Layer.prototype, "onDispose", {
  71764. set: function (callback) {
  71765. if (this._onDisposeObserver) {
  71766. this.onDisposeObservable.remove(this._onDisposeObserver);
  71767. }
  71768. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  71769. },
  71770. enumerable: true,
  71771. configurable: true
  71772. });
  71773. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  71774. set: function (callback) {
  71775. if (this._onBeforeRenderObserver) {
  71776. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  71777. }
  71778. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  71779. },
  71780. enumerable: true,
  71781. configurable: true
  71782. });
  71783. Object.defineProperty(Layer.prototype, "onAfterRender", {
  71784. set: function (callback) {
  71785. if (this._onAfterRenderObserver) {
  71786. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  71787. }
  71788. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  71789. },
  71790. enumerable: true,
  71791. configurable: true
  71792. });
  71793. Layer.prototype._createIndexBuffer = function () {
  71794. var engine = this._scene.getEngine();
  71795. // Indices
  71796. var indices = [];
  71797. indices.push(0);
  71798. indices.push(1);
  71799. indices.push(2);
  71800. indices.push(0);
  71801. indices.push(2);
  71802. indices.push(3);
  71803. this._indexBuffer = engine.createIndexBuffer(indices);
  71804. };
  71805. Layer.prototype._rebuild = function () {
  71806. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]._rebuild();
  71807. this._createIndexBuffer();
  71808. };
  71809. Layer.prototype.render = function () {
  71810. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  71811. // Check
  71812. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  71813. return;
  71814. var engine = this._scene.getEngine();
  71815. this.onBeforeRenderObservable.notifyObservers(this);
  71816. // Render
  71817. engine.enableEffect(currentEffect);
  71818. engine.setState(false);
  71819. // Texture
  71820. currentEffect.setTexture("textureSampler", this.texture);
  71821. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  71822. // Color
  71823. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  71824. // Scale / offset
  71825. currentEffect.setVector2("offset", this.offset);
  71826. currentEffect.setVector2("scale", this.scale);
  71827. // VBOs
  71828. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  71829. // Draw order
  71830. if (!this.alphaTest) {
  71831. engine.setAlphaMode(this.alphaBlendingMode);
  71832. engine.draw(true, 0, 6);
  71833. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71834. }
  71835. else {
  71836. engine.draw(true, 0, 6);
  71837. }
  71838. this.onAfterRenderObservable.notifyObservers(this);
  71839. };
  71840. Layer.prototype.dispose = function () {
  71841. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71842. if (vertexBuffer) {
  71843. vertexBuffer.dispose();
  71844. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71845. }
  71846. if (this._indexBuffer) {
  71847. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71848. this._indexBuffer = null;
  71849. }
  71850. if (this.texture) {
  71851. this.texture.dispose();
  71852. this.texture = null;
  71853. }
  71854. // Remove from scene
  71855. var index = this._scene.layers.indexOf(this);
  71856. this._scene.layers.splice(index, 1);
  71857. // Callback
  71858. this.onDisposeObservable.notifyObservers(this);
  71859. this.onDisposeObservable.clear();
  71860. this.onAfterRenderObservable.clear();
  71861. this.onBeforeRenderObservable.clear();
  71862. };
  71863. return Layer;
  71864. }());
  71865. BABYLON.Layer = Layer;
  71866. })(BABYLON || (BABYLON = {}));
  71867. //# sourceMappingURL=babylon.layer.js.map
  71868. var BABYLON;
  71869. (function (BABYLON) {
  71870. var TextureTools = (function () {
  71871. function TextureTools() {
  71872. }
  71873. /**
  71874. * Uses the GPU to create a copy texture rescaled at a given size
  71875. * @param texture Texture to copy from
  71876. * @param width Desired width
  71877. * @param height Desired height
  71878. * @return Generated texture
  71879. */
  71880. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  71881. if (useBilinearMode === void 0) { useBilinearMode = true; }
  71882. var scene = texture.getScene();
  71883. var engine = scene.getEngine();
  71884. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  71885. rtt.wrapU = texture.wrapU;
  71886. rtt.wrapV = texture.wrapV;
  71887. rtt.uOffset = texture.uOffset;
  71888. rtt.vOffset = texture.vOffset;
  71889. rtt.uScale = texture.uScale;
  71890. rtt.vScale = texture.vScale;
  71891. rtt.uAng = texture.uAng;
  71892. rtt.vAng = texture.vAng;
  71893. rtt.wAng = texture.wAng;
  71894. rtt.coordinatesIndex = texture.coordinatesIndex;
  71895. rtt.level = texture.level;
  71896. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  71897. rtt._texture.isReady = false;
  71898. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71899. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71900. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71901. passPostProcess.getEffect().executeWhenCompiled(function () {
  71902. passPostProcess.onApply = function (effect) {
  71903. effect.setTexture("textureSampler", texture);
  71904. };
  71905. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  71906. engine.unBindFramebuffer(rtt.getInternalTexture());
  71907. rtt.disposeFramebufferObjects();
  71908. passPostProcess.dispose();
  71909. rtt._texture.isReady = true;
  71910. });
  71911. return rtt;
  71912. };
  71913. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  71914. if (!scene._environmentBRDFTexture) {
  71915. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  71916. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71917. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71918. scene._environmentBRDFTexture = texture;
  71919. }
  71920. return scene._environmentBRDFTexture;
  71921. };
  71922. 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=";
  71923. return TextureTools;
  71924. }());
  71925. BABYLON.TextureTools = TextureTools;
  71926. })(BABYLON || (BABYLON = {}));
  71927. //# sourceMappingURL=babylon.textureTools.js.map
  71928. var BABYLON;
  71929. (function (BABYLON) {
  71930. var FramingBehavior = (function () {
  71931. function FramingBehavior() {
  71932. this._mode = FramingBehavior.FitFrustumSidesMode;
  71933. this._radiusScale = 1.0;
  71934. this._positionScale = 0.5;
  71935. this._defaultElevation = 0.3;
  71936. this._elevationReturnTime = 1500;
  71937. this._elevationReturnWaitTime = 1000;
  71938. this._zoomStopsAnimation = false;
  71939. this._framingTime = 1500;
  71940. this._isPointerDown = false;
  71941. this._lastFrameTime = null;
  71942. this._lastInteractionTime = -Infinity;
  71943. // Framing control
  71944. this._animatables = new Array();
  71945. this._betaIsAnimating = false;
  71946. this._lastFrameRadius = 0;
  71947. }
  71948. Object.defineProperty(FramingBehavior.prototype, "name", {
  71949. get: function () {
  71950. return "Framing";
  71951. },
  71952. enumerable: true,
  71953. configurable: true
  71954. });
  71955. Object.defineProperty(FramingBehavior.prototype, "mode", {
  71956. /**
  71957. * Gets current mode used by the behavior.
  71958. */
  71959. get: function () {
  71960. return this._mode;
  71961. },
  71962. /**
  71963. * Sets the current mode used by the behavior
  71964. */
  71965. set: function (mode) {
  71966. this._mode = mode;
  71967. },
  71968. enumerable: true,
  71969. configurable: true
  71970. });
  71971. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  71972. /**
  71973. * Gets the scale applied to the radius
  71974. */
  71975. get: function () {
  71976. return this._radiusScale;
  71977. },
  71978. /**
  71979. * Sets the scale applied to the radius (1 by default)
  71980. */
  71981. set: function (radius) {
  71982. this._radiusScale = radius;
  71983. },
  71984. enumerable: true,
  71985. configurable: true
  71986. });
  71987. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  71988. /**
  71989. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  71990. */
  71991. get: function () {
  71992. return this._positionScale;
  71993. },
  71994. /**
  71995. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  71996. */
  71997. set: function (scale) {
  71998. this._positionScale = scale;
  71999. },
  72000. enumerable: true,
  72001. configurable: true
  72002. });
  72003. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  72004. /**
  72005. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  72006. * behaviour is triggered, in radians.
  72007. */
  72008. get: function () {
  72009. return this._defaultElevation;
  72010. },
  72011. /**
  72012. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  72013. * behaviour is triggered, in radians.
  72014. */
  72015. set: function (elevation) {
  72016. this._defaultElevation = elevation;
  72017. },
  72018. enumerable: true,
  72019. configurable: true
  72020. });
  72021. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  72022. /**
  72023. * Gets the time (in milliseconds) taken to return to the default beta position.
  72024. * Negative value indicates camera should not return to default.
  72025. */
  72026. get: function () {
  72027. return this._elevationReturnTime;
  72028. },
  72029. /**
  72030. * Sets the time (in milliseconds) taken to return to the default beta position.
  72031. * Negative value indicates camera should not return to default.
  72032. */
  72033. set: function (speed) {
  72034. this._elevationReturnTime = speed;
  72035. },
  72036. enumerable: true,
  72037. configurable: true
  72038. });
  72039. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  72040. /**
  72041. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  72042. */
  72043. get: function () {
  72044. return this._elevationReturnWaitTime;
  72045. },
  72046. /**
  72047. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  72048. */
  72049. set: function (time) {
  72050. this._elevationReturnWaitTime = time;
  72051. },
  72052. enumerable: true,
  72053. configurable: true
  72054. });
  72055. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  72056. /**
  72057. * Gets the flag that indicates if user zooming should stop animation.
  72058. */
  72059. get: function () {
  72060. return this._zoomStopsAnimation;
  72061. },
  72062. /**
  72063. * Sets the flag that indicates if user zooming should stop animation.
  72064. */
  72065. set: function (flag) {
  72066. this._zoomStopsAnimation = flag;
  72067. },
  72068. enumerable: true,
  72069. configurable: true
  72070. });
  72071. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  72072. /**
  72073. * Gets the transition time when framing the mesh, in milliseconds
  72074. */
  72075. get: function () {
  72076. return this._framingTime;
  72077. },
  72078. /**
  72079. * Sets the transition time when framing the mesh, in milliseconds
  72080. */
  72081. set: function (time) {
  72082. this._framingTime = time;
  72083. },
  72084. enumerable: true,
  72085. configurable: true
  72086. });
  72087. FramingBehavior.prototype.attach = function (camera) {
  72088. var _this = this;
  72089. this._attachedCamera = camera;
  72090. var scene = this._attachedCamera.getScene();
  72091. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  72092. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  72093. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  72094. _this._isPointerDown = true;
  72095. return;
  72096. }
  72097. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  72098. _this._isPointerDown = false;
  72099. }
  72100. });
  72101. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  72102. if (mesh) {
  72103. _this.zoomOnMesh(mesh);
  72104. }
  72105. });
  72106. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  72107. // Stop the animation if there is user interaction and the animation should stop for this interaction
  72108. _this._applyUserInteraction();
  72109. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  72110. // back to the default position after a given timeout
  72111. _this._maintainCameraAboveGround();
  72112. });
  72113. };
  72114. FramingBehavior.prototype.detach = function () {
  72115. var scene = this._attachedCamera.getScene();
  72116. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  72117. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  72118. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  72119. this._attachedCamera = null;
  72120. };
  72121. /**
  72122. * Targets the given mesh and updates zoom level accordingly.
  72123. * @param mesh The mesh to target.
  72124. * @param radius Optional. If a cached radius position already exists, overrides default.
  72125. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  72126. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  72127. * @param onAnimationEnd Callback triggered at the end of the framing animation
  72128. */
  72129. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  72130. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  72131. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  72132. mesh.computeWorldMatrix(true);
  72133. var boundingBox = mesh.getBoundingInfo().boundingBox;
  72134. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  72135. };
  72136. /**
  72137. * Targets the given mesh and updates zoom level accordingly.
  72138. * @param mesh The mesh to target.
  72139. * @param radius Optional. If a cached radius position already exists, overrides default.
  72140. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  72141. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  72142. * @param onAnimationEnd Callback triggered at the end of the framing animation
  72143. */
  72144. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  72145. var _this = this;
  72146. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  72147. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  72148. var zoomTarget;
  72149. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  72150. var bottom = minimumWorld.y;
  72151. var top = maximumWorld.y;
  72152. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  72153. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  72154. if (focusOnOriginXZ) {
  72155. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  72156. }
  72157. else {
  72158. var centerWorld = minimumWorld.add(radiusWorld);
  72159. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  72160. }
  72161. if (!this._vectorTransition) {
  72162. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  72163. }
  72164. this._betaIsAnimating = true;
  72165. this._animatables.push(BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime));
  72166. // sets the radius and lower radius bounds
  72167. // Small delta ensures camera is not always at lower zoom limit.
  72168. var delta = 0.1;
  72169. var radius = 0;
  72170. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  72171. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  72172. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  72173. radius = position;
  72174. }
  72175. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  72176. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  72177. if (this._attachedCamera.lowerRadiusLimit === null) {
  72178. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  72179. }
  72180. }
  72181. // Set sensibilities
  72182. var extend = maximumWorld.subtract(minimumWorld).length();
  72183. this._attachedCamera.panningSensibility = 5000 / extend;
  72184. this._attachedCamera.wheelPrecision = 100 / radius;
  72185. // transition to new radius
  72186. if (!this._radiusTransition) {
  72187. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  72188. }
  72189. this._animatables.push(BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  72190. if (onAnimationEnd) {
  72191. onAnimationEnd();
  72192. }
  72193. _this._attachedCamera.storeState();
  72194. }));
  72195. };
  72196. /**
  72197. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  72198. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  72199. * frustum width.
  72200. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  72201. * to fully enclose the mesh in the viewing frustum.
  72202. */
  72203. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  72204. var size = maximumWorld.subtract(minimumWorld);
  72205. var boxVectorGlobalDiagonal = size.length();
  72206. var frustumSlope = this._getFrustumSlope();
  72207. // Formula for setting distance
  72208. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  72209. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  72210. // Horizon distance
  72211. var radius = radiusWithoutFraming * this._radiusScale;
  72212. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  72213. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  72214. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  72215. var camera = this._attachedCamera;
  72216. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  72217. // Don't exceed the requested limit
  72218. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  72219. }
  72220. // Don't exceed the upper radius limit
  72221. if (camera.upperRadiusLimit) {
  72222. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  72223. }
  72224. return distance;
  72225. };
  72226. /**
  72227. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  72228. * is automatically returned to its default position (expected to be above ground plane).
  72229. */
  72230. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  72231. var _this = this;
  72232. if (this._elevationReturnTime < 0) {
  72233. return;
  72234. }
  72235. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  72236. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  72237. var limitBeta = Math.PI * 0.5;
  72238. // Bring the camera back up if below the ground plane
  72239. if (!this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  72240. this._betaIsAnimating = true;
  72241. //Transition to new position
  72242. this.stopAllAnimations();
  72243. if (!this._betaTransition) {
  72244. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  72245. }
  72246. this._animatables.push(BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  72247. _this._clearAnimationLocks();
  72248. _this.stopAllAnimations();
  72249. }));
  72250. }
  72251. };
  72252. /**
  72253. * Returns the frustum slope based on the canvas ratio and camera FOV
  72254. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  72255. */
  72256. FramingBehavior.prototype._getFrustumSlope = function () {
  72257. // Calculate the viewport ratio
  72258. // Aspect Ratio is Height/Width.
  72259. var camera = this._attachedCamera;
  72260. var engine = camera.getScene().getEngine();
  72261. var aspectRatio = engine.getAspectRatio(camera);
  72262. // Camera FOV is the vertical field of view (top-bottom) in radians.
  72263. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  72264. var frustumSlopeY = Math.tan(camera.fov / 2);
  72265. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  72266. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  72267. // along the forward vector.
  72268. var frustumSlopeX = frustumSlopeY * aspectRatio;
  72269. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  72270. };
  72271. /**
  72272. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  72273. */
  72274. FramingBehavior.prototype._clearAnimationLocks = function () {
  72275. this._betaIsAnimating = false;
  72276. };
  72277. /**
  72278. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  72279. */
  72280. FramingBehavior.prototype._applyUserInteraction = function () {
  72281. if (this.isUserIsMoving) {
  72282. this._lastInteractionTime = BABYLON.Tools.Now;
  72283. this.stopAllAnimations();
  72284. this._clearAnimationLocks();
  72285. }
  72286. };
  72287. /**
  72288. * Stops and removes all animations that have been applied to the camera
  72289. */
  72290. FramingBehavior.prototype.stopAllAnimations = function () {
  72291. this._attachedCamera.animations = [];
  72292. while (this._animatables.length) {
  72293. if (this._animatables[0]) {
  72294. this._animatables[0].onAnimationEnd = null;
  72295. this._animatables[0].stop();
  72296. }
  72297. this._animatables.shift();
  72298. }
  72299. };
  72300. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  72301. /**
  72302. * Gets a value indicating if the user is moving the camera
  72303. */
  72304. get: function () {
  72305. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  72306. this._attachedCamera.inertialBetaOffset !== 0 ||
  72307. this._attachedCamera.inertialRadiusOffset !== 0 ||
  72308. this._attachedCamera.inertialPanningX !== 0 ||
  72309. this._attachedCamera.inertialPanningY !== 0 ||
  72310. this._isPointerDown;
  72311. },
  72312. enumerable: true,
  72313. configurable: true
  72314. });
  72315. /**
  72316. * The easing function used by animations
  72317. */
  72318. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  72319. /**
  72320. * The easing mode used by animations
  72321. */
  72322. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  72323. // Statics
  72324. /**
  72325. * The camera can move all the way towards the mesh.
  72326. */
  72327. FramingBehavior.IgnoreBoundsSizeMode = 0;
  72328. /**
  72329. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  72330. */
  72331. FramingBehavior.FitFrustumSidesMode = 1;
  72332. return FramingBehavior;
  72333. }());
  72334. BABYLON.FramingBehavior = FramingBehavior;
  72335. })(BABYLON || (BABYLON = {}));
  72336. //# sourceMappingURL=babylon.framingBehavior.js.map
  72337. var BABYLON;
  72338. (function (BABYLON) {
  72339. /**
  72340. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  72341. */
  72342. var BouncingBehavior = (function () {
  72343. function BouncingBehavior() {
  72344. /**
  72345. * The duration of the animation, in milliseconds
  72346. */
  72347. this.transitionDuration = 450;
  72348. /**
  72349. * Length of the distance animated by the transition when lower radius is reached
  72350. */
  72351. this.lowerRadiusTransitionRange = 2;
  72352. /**
  72353. * Length of the distance animated by the transition when upper radius is reached
  72354. */
  72355. this.upperRadiusTransitionRange = -2;
  72356. this._autoTransitionRange = false;
  72357. // Animations
  72358. this._radiusIsAnimating = false;
  72359. this._radiusBounceTransition = null;
  72360. this._animatables = new Array();
  72361. }
  72362. Object.defineProperty(BouncingBehavior.prototype, "name", {
  72363. get: function () {
  72364. return "Bouncing";
  72365. },
  72366. enumerable: true,
  72367. configurable: true
  72368. });
  72369. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  72370. /**
  72371. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  72372. */
  72373. get: function () {
  72374. return this._autoTransitionRange;
  72375. },
  72376. /**
  72377. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  72378. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  72379. */
  72380. set: function (value) {
  72381. var _this = this;
  72382. if (this._autoTransitionRange === value) {
  72383. return;
  72384. }
  72385. this._autoTransitionRange = value;
  72386. var camera = this._attachedCamera;
  72387. if (value) {
  72388. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  72389. if (!mesh) {
  72390. return;
  72391. }
  72392. mesh.computeWorldMatrix(true);
  72393. var diagonal = mesh.getBoundingInfo().diagonalLength;
  72394. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  72395. _this.upperRadiusTransitionRange = diagonal * 0.05;
  72396. });
  72397. }
  72398. else if (this._onMeshTargetChangedObserver) {
  72399. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  72400. }
  72401. },
  72402. enumerable: true,
  72403. configurable: true
  72404. });
  72405. BouncingBehavior.prototype.attach = function (camera) {
  72406. var _this = this;
  72407. this._attachedCamera = camera;
  72408. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  72409. // Add the bounce animation to the lower radius limit
  72410. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  72411. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  72412. }
  72413. // Add the bounce animation to the upper radius limit
  72414. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  72415. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  72416. }
  72417. });
  72418. };
  72419. BouncingBehavior.prototype.detach = function () {
  72420. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  72421. if (this._onMeshTargetChangedObserver) {
  72422. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  72423. }
  72424. this._attachedCamera = null;
  72425. };
  72426. /**
  72427. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  72428. * @param radiusLimit The limit to check against.
  72429. * @return Bool to indicate if at limit.
  72430. */
  72431. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  72432. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  72433. return true;
  72434. }
  72435. return false;
  72436. };
  72437. /**
  72438. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  72439. * @param radiusDelta The delta by which to animate to. Can be negative.
  72440. */
  72441. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  72442. var _this = this;
  72443. if (!this._radiusBounceTransition) {
  72444. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  72445. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  72446. }
  72447. // Prevent zoom until bounce has completed
  72448. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  72449. this._attachedCamera.wheelPrecision = Infinity;
  72450. this._attachedCamera.inertialRadiusOffset = 0;
  72451. // Animate to the radius limit
  72452. this.stopAllAnimations();
  72453. this._radiusIsAnimating = true;
  72454. 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(); }));
  72455. };
  72456. /**
  72457. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  72458. */
  72459. BouncingBehavior.prototype._clearAnimationLocks = function () {
  72460. this._radiusIsAnimating = false;
  72461. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  72462. };
  72463. /**
  72464. * Stops and removes all animations that have been applied to the camera
  72465. */
  72466. BouncingBehavior.prototype.stopAllAnimations = function () {
  72467. this._attachedCamera.animations = [];
  72468. while (this._animatables.length) {
  72469. this._animatables[0].onAnimationEnd = null;
  72470. this._animatables[0].stop();
  72471. this._animatables.shift();
  72472. }
  72473. };
  72474. /**
  72475. * The easing function used by animations
  72476. */
  72477. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  72478. /**
  72479. * The easing mode used by animations
  72480. */
  72481. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  72482. return BouncingBehavior;
  72483. }());
  72484. BABYLON.BouncingBehavior = BouncingBehavior;
  72485. })(BABYLON || (BABYLON = {}));
  72486. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  72487. var BABYLON;
  72488. (function (BABYLON) {
  72489. var AutoRotationBehavior = (function () {
  72490. function AutoRotationBehavior() {
  72491. this._zoomStopsAnimation = false;
  72492. this._idleRotationSpeed = 0.05;
  72493. this._idleRotationWaitTime = 2000;
  72494. this._idleRotationSpinupTime = 2000;
  72495. this._isPointerDown = false;
  72496. this._lastFrameTime = null;
  72497. this._lastInteractionTime = -Infinity;
  72498. this._cameraRotationSpeed = 0;
  72499. this._lastFrameRadius = 0;
  72500. }
  72501. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  72502. get: function () {
  72503. return "AutoRotation";
  72504. },
  72505. enumerable: true,
  72506. configurable: true
  72507. });
  72508. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  72509. /**
  72510. * Gets the flag that indicates if user zooming should stop animation.
  72511. */
  72512. get: function () {
  72513. return this._zoomStopsAnimation;
  72514. },
  72515. /**
  72516. * Sets the flag that indicates if user zooming should stop animation.
  72517. */
  72518. set: function (flag) {
  72519. this._zoomStopsAnimation = flag;
  72520. },
  72521. enumerable: true,
  72522. configurable: true
  72523. });
  72524. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  72525. /**
  72526. * Gets the default speed at which the camera rotates around the model.
  72527. */
  72528. get: function () {
  72529. return this._idleRotationSpeed;
  72530. },
  72531. /**
  72532. * Sets the default speed at which the camera rotates around the model.
  72533. */
  72534. set: function (speed) {
  72535. this._idleRotationSpeed = speed;
  72536. },
  72537. enumerable: true,
  72538. configurable: true
  72539. });
  72540. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  72541. /**
  72542. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  72543. */
  72544. get: function () {
  72545. return this._idleRotationWaitTime;
  72546. },
  72547. /**
  72548. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  72549. */
  72550. set: function (time) {
  72551. this._idleRotationWaitTime = time;
  72552. },
  72553. enumerable: true,
  72554. configurable: true
  72555. });
  72556. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  72557. /**
  72558. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  72559. */
  72560. get: function () {
  72561. return this._idleRotationSpinupTime;
  72562. },
  72563. /**
  72564. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  72565. */
  72566. set: function (time) {
  72567. this._idleRotationSpinupTime = time;
  72568. },
  72569. enumerable: true,
  72570. configurable: true
  72571. });
  72572. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  72573. /**
  72574. * Gets a value indicating if the camera is currently rotating because of this behavior
  72575. */
  72576. get: function () {
  72577. return Math.abs(this._cameraRotationSpeed) > 0;
  72578. },
  72579. enumerable: true,
  72580. configurable: true
  72581. });
  72582. AutoRotationBehavior.prototype.attach = function (camera) {
  72583. var _this = this;
  72584. this._attachedCamera = camera;
  72585. var scene = this._attachedCamera.getScene();
  72586. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  72587. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  72588. _this._isPointerDown = true;
  72589. return;
  72590. }
  72591. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  72592. _this._isPointerDown = false;
  72593. }
  72594. });
  72595. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  72596. var now = BABYLON.Tools.Now;
  72597. var dt = 0;
  72598. if (_this._lastFrameTime != null) {
  72599. dt = now - _this._lastFrameTime;
  72600. }
  72601. _this._lastFrameTime = now;
  72602. // Stop the animation if there is user interaction and the animation should stop for this interaction
  72603. _this._applyUserInteraction();
  72604. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  72605. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  72606. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  72607. // Step camera rotation by rotation speed
  72608. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  72609. });
  72610. };
  72611. AutoRotationBehavior.prototype.detach = function () {
  72612. var scene = this._attachedCamera.getScene();
  72613. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  72614. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  72615. this._attachedCamera = null;
  72616. };
  72617. /**
  72618. * Returns true if user is scrolling.
  72619. * @return true if user is scrolling.
  72620. */
  72621. AutoRotationBehavior.prototype._userIsZooming = function () {
  72622. return this._attachedCamera.inertialRadiusOffset !== 0;
  72623. };
  72624. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  72625. var zoomHasHitLimit = false;
  72626. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  72627. zoomHasHitLimit = true;
  72628. }
  72629. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  72630. this._lastFrameRadius = this._attachedCamera.radius;
  72631. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  72632. };
  72633. /**
  72634. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  72635. */
  72636. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  72637. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  72638. this._lastInteractionTime = BABYLON.Tools.Now;
  72639. }
  72640. };
  72641. // Tools
  72642. AutoRotationBehavior.prototype._userIsMoving = function () {
  72643. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  72644. this._attachedCamera.inertialBetaOffset !== 0 ||
  72645. this._attachedCamera.inertialRadiusOffset !== 0 ||
  72646. this._attachedCamera.inertialPanningX !== 0 ||
  72647. this._attachedCamera.inertialPanningY !== 0 ||
  72648. this._isPointerDown;
  72649. };
  72650. return AutoRotationBehavior;
  72651. }());
  72652. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  72653. })(BABYLON || (BABYLON = {}));
  72654. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  72655. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && !defined(USESPHERICALINFRAGMENT)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#if defined(USESPHERICALFROMREFLECTIONMAP) && !defined(USESPHERICALINFRAGMENT)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && !defined(USESPHERICALINFRAGMENT)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\nfloat opacity0=opacityPerceptual*opacityPerceptual;\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && !defined(USESPHERICALINFRAGMENT)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=abs(texture2D(textureSampler,vUV).r);\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,1.0);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}"};
  72656. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\nuniform sampler2D txColorTransform;\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#ifdef COLORGRADING\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};"};
  72657. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  72658. var BABYLON;
  72659. (function (BABYLON) {
  72660. var GridMaterialDefines = (function (_super) {
  72661. __extends(GridMaterialDefines, _super);
  72662. function GridMaterialDefines() {
  72663. var _this = _super.call(this) || this;
  72664. _this.TRANSPARENT = false;
  72665. _this.FOG = false;
  72666. _this.PREMULTIPLYALPHA = false;
  72667. _this.rebuild();
  72668. return _this;
  72669. }
  72670. return GridMaterialDefines;
  72671. }(BABYLON.MaterialDefines));
  72672. /**
  72673. * The grid materials allows you to wrap any shape with a grid.
  72674. * Colors are customizable.
  72675. */
  72676. var GridMaterial = (function (_super) {
  72677. __extends(GridMaterial, _super);
  72678. /**
  72679. * constructor
  72680. * @param name The name given to the material in order to identify it afterwards.
  72681. * @param scene The scene the material is used in.
  72682. */
  72683. function GridMaterial(name, scene) {
  72684. var _this = _super.call(this, name, scene) || this;
  72685. /**
  72686. * Main color of the grid (e.g. between lines)
  72687. */
  72688. _this.mainColor = BABYLON.Color3.Black();
  72689. /**
  72690. * Color of the grid lines.
  72691. */
  72692. _this.lineColor = BABYLON.Color3.Teal();
  72693. /**
  72694. * The scale of the grid compared to unit.
  72695. */
  72696. _this.gridRatio = 1.0;
  72697. /**
  72698. * Allows setting an offset for the grid lines.
  72699. */
  72700. _this.gridOffset = BABYLON.Vector3.Zero();
  72701. /**
  72702. * The frequency of thicker lines.
  72703. */
  72704. _this.majorUnitFrequency = 10;
  72705. /**
  72706. * The visibility of minor units in the grid.
  72707. */
  72708. _this.minorUnitVisibility = 0.33;
  72709. /**
  72710. * The grid opacity outside of the lines.
  72711. */
  72712. _this.opacity = 1.0;
  72713. /**
  72714. * Determine RBG output is premultiplied by alpha value.
  72715. */
  72716. _this.preMultiplyAlpha = false;
  72717. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  72718. return _this;
  72719. }
  72720. /**
  72721. * Returns wehter or not the grid requires alpha blending.
  72722. */
  72723. GridMaterial.prototype.needAlphaBlending = function () {
  72724. return this.opacity < 1.0;
  72725. };
  72726. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  72727. if (this.isFrozen) {
  72728. if (this._wasPreviouslyReady && subMesh.effect) {
  72729. return true;
  72730. }
  72731. }
  72732. if (!subMesh._materialDefines) {
  72733. subMesh._materialDefines = new GridMaterialDefines();
  72734. }
  72735. var defines = subMesh._materialDefines;
  72736. var scene = this.getScene();
  72737. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  72738. if (this._renderId === scene.getRenderId()) {
  72739. return true;
  72740. }
  72741. }
  72742. var engine = scene.getEngine();
  72743. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  72744. defines.TRANSPARENT = !defines.TRANSPARENT;
  72745. defines.markAsUnprocessed();
  72746. }
  72747. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  72748. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  72749. defines.markAsUnprocessed();
  72750. }
  72751. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  72752. // Get correct effect
  72753. if (defines.isDirty) {
  72754. defines.markAsProcessed();
  72755. scene.resetCachedMaterial();
  72756. // Attributes
  72757. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  72758. // Defines
  72759. var join = defines.toString();
  72760. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, null, this.onCompiled, this.onError), defines);
  72761. }
  72762. if (!subMesh.effect.isReady()) {
  72763. return false;
  72764. }
  72765. this._renderId = scene.getRenderId();
  72766. this._wasPreviouslyReady = true;
  72767. return true;
  72768. };
  72769. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  72770. var scene = this.getScene();
  72771. var defines = subMesh._materialDefines;
  72772. if (!defines) {
  72773. return;
  72774. }
  72775. var effect = subMesh.effect;
  72776. this._activeEffect = effect;
  72777. // Matrices
  72778. this.bindOnlyWorldMatrix(world);
  72779. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  72780. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  72781. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  72782. // Uniforms
  72783. if (this._mustRebind(scene, effect)) {
  72784. this._activeEffect.setColor3("mainColor", this.mainColor);
  72785. this._activeEffect.setColor3("lineColor", this.lineColor);
  72786. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  72787. this._gridControl.x = this.gridRatio;
  72788. this._gridControl.y = Math.round(this.majorUnitFrequency);
  72789. this._gridControl.z = this.minorUnitVisibility;
  72790. this._gridControl.w = this.opacity;
  72791. this._activeEffect.setVector4("gridControl", this._gridControl);
  72792. }
  72793. // Fog
  72794. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  72795. this._afterBind(mesh, this._activeEffect);
  72796. };
  72797. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  72798. _super.prototype.dispose.call(this, forceDisposeEffect);
  72799. };
  72800. GridMaterial.prototype.clone = function (name) {
  72801. var _this = this;
  72802. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  72803. };
  72804. GridMaterial.prototype.serialize = function () {
  72805. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  72806. serializationObject.customType = "BABYLON.GridMaterial";
  72807. return serializationObject;
  72808. };
  72809. GridMaterial.prototype.getClassName = function () {
  72810. return "GridMaterial";
  72811. };
  72812. GridMaterial.Parse = function (source, scene, rootUrl) {
  72813. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  72814. };
  72815. __decorate([
  72816. BABYLON.serializeAsColor3()
  72817. ], GridMaterial.prototype, "mainColor", void 0);
  72818. __decorate([
  72819. BABYLON.serializeAsColor3()
  72820. ], GridMaterial.prototype, "lineColor", void 0);
  72821. __decorate([
  72822. BABYLON.serialize()
  72823. ], GridMaterial.prototype, "gridRatio", void 0);
  72824. __decorate([
  72825. BABYLON.serializeAsColor3()
  72826. ], GridMaterial.prototype, "gridOffset", void 0);
  72827. __decorate([
  72828. BABYLON.serialize()
  72829. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  72830. __decorate([
  72831. BABYLON.serialize()
  72832. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  72833. __decorate([
  72834. BABYLON.serialize()
  72835. ], GridMaterial.prototype, "opacity", void 0);
  72836. __decorate([
  72837. BABYLON.serialize()
  72838. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  72839. return GridMaterial;
  72840. }(BABYLON.PushMaterial));
  72841. BABYLON.GridMaterial = GridMaterial;
  72842. })(BABYLON || (BABYLON = {}));
  72843. //# sourceMappingURL=babylon.gridmaterial.js.map
  72844. BABYLON.Effect.ShadersStore['gridVertexShader'] = "precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 projection;\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 worldView;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogVertexDeclaration>\nvoid main(void) {\n#ifdef FOG\nvec4 worldPos=world*vec4(position,1.0);\n#endif\n#include<fogVertex>\nvec4 cameraSpacePosition=worldView*vec4(position,1.0);\ngl_Position=projection*cameraSpacePosition;\n#ifdef TRANSPARENT\nvCameraSpacePosition=cameraSpacePosition;\n#endif\nvPosition=position;\nvNormal=normal;\n}";
  72845. BABYLON.Effect.ShadersStore['gridPixelShader'] = "#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;\nuniform vec3 mainColor;\nuniform vec3 lineColor;\nuniform vec4 gridControl;\nuniform vec3 gridOffset;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogFragmentDeclaration>\nfloat getVisibility(float position) {\n\nfloat majorGridFrequency=gridControl.y;\nif (floor(position+0.5) == floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{\nreturn 1.0;\n} \nreturn gridControl.z;\n}\nfloat getAnisotropicAttenuation(float differentialLength) {\nconst float maxNumberOfLines=10.0;\nreturn clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);\n}\nfloat isPointOnLine(float position,float differentialLength) {\nfloat fractionPartOfPosition=position-floor(position+0.5); \nfractionPartOfPosition/=differentialLength; \nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);\nfloat result=0.5+0.5*cos(fractionPartOfPosition*PI); \nreturn result; \n}\nfloat contributionOnAxis(float position) {\nfloat differentialLength=length(vec2(dFdx(position),dFdy(position)));\ndifferentialLength*=SQRT2; \n\nfloat result=isPointOnLine(position,differentialLength);\n\nfloat visibility=getVisibility(position);\nresult*=visibility;\n\nfloat anisotropicAttenuation=getAnisotropicAttenuation(differentialLength);\nresult*=anisotropicAttenuation;\nreturn result;\n}\nfloat normalImpactOnAxis(float x) {\nfloat normalImpact=clamp(1.0-3.0*abs(x*x*x),0.0,1.0);\nreturn normalImpact;\n}\nvoid main(void) {\n\nfloat gridRatio=gridControl.x;\nvec3 gridPos=(vPosition+gridOffset)/gridRatio;\n\nfloat x=contributionOnAxis(gridPos.x);\nfloat y=contributionOnAxis(gridPos.y);\nfloat z=contributionOnAxis(gridPos.z);\n\nvec3 normal=normalize(vNormal);\nx*=normalImpactOnAxis(normal.x);\ny*=normalImpactOnAxis(normal.y);\nz*=normalImpactOnAxis(normal.z);\n\nfloat grid=clamp(x+y+z,0.,1.);\n\nvec3 color=mix(mainColor,lineColor,grid);\n#ifdef FOG\n#include<fogFragment>\n#endif\n#ifdef TRANSPARENT\nfloat distanceToFragment=length(vCameraSpacePosition.xyz);\nfloat cameraPassThrough=clamp(distanceToFragment-0.25,0.0,1.0);\nfloat opacity=clamp(grid,0.08,cameraPassThrough*gridControl.w*grid);\ngl_FragColor=vec4(color.rgb,opacity);\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else\n\ngl_FragColor=vec4(color.rgb,1.0);\n#endif\n}";
  72846. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  72847. var BABYLON;
  72848. (function (BABYLON) {
  72849. var GLTFLoaderCoordinateSystemMode;
  72850. (function (GLTFLoaderCoordinateSystemMode) {
  72851. // Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene (scene.useRightHandedSystem).
  72852. // NOTE: When scene.useRightHandedSystem is false, an additional transform will be added to the root to transform the data from right-handed to left-handed.
  72853. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  72854. // The glTF right-handed data is not transformed in any form and is loaded directly.
  72855. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["PASS_THROUGH"] = 1] = "PASS_THROUGH";
  72856. // Sets the useRightHandedSystem flag on the scene.
  72857. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 2] = "FORCE_RIGHT_HANDED";
  72858. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  72859. var GLTFFileLoader = (function () {
  72860. function GLTFFileLoader() {
  72861. // V2 options
  72862. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  72863. this.name = "gltf";
  72864. this.extensions = {
  72865. ".gltf": { isBinary: false },
  72866. ".glb": { isBinary: true }
  72867. };
  72868. }
  72869. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  72870. var loaderData = GLTFFileLoader._parse(data, onError);
  72871. if (!loaderData) {
  72872. return;
  72873. }
  72874. if (this.onParsed) {
  72875. this.onParsed(loaderData);
  72876. }
  72877. var loader = this._getLoader(loaderData, onError);
  72878. if (!loader) {
  72879. return;
  72880. }
  72881. loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  72882. };
  72883. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  72884. var loaderData = GLTFFileLoader._parse(data, onError);
  72885. if (!loaderData) {
  72886. return;
  72887. }
  72888. if (this.onParsed) {
  72889. this.onParsed(loaderData);
  72890. }
  72891. var loader = this._getLoader(loaderData, onError);
  72892. if (!loader) {
  72893. return;
  72894. }
  72895. return loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  72896. };
  72897. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  72898. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  72899. };
  72900. GLTFFileLoader._parse = function (data, onError) {
  72901. try {
  72902. if (data instanceof ArrayBuffer) {
  72903. return GLTFFileLoader._parseBinary(data, onError);
  72904. }
  72905. return {
  72906. json: JSON.parse(data),
  72907. bin: null
  72908. };
  72909. }
  72910. catch (e) {
  72911. onError(e.message);
  72912. return null;
  72913. }
  72914. };
  72915. GLTFFileLoader.prototype._getLoader = function (loaderData, onError) {
  72916. var loaderVersion = { major: 2, minor: 0 };
  72917. var asset = loaderData.json.asset || {};
  72918. var version = GLTFFileLoader._parseVersion(asset.version);
  72919. if (!version) {
  72920. onError("Invalid version: " + asset.version);
  72921. return null;
  72922. }
  72923. if (asset.minVersion !== undefined) {
  72924. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  72925. if (!minVersion) {
  72926. onError("Invalid minimum version: " + asset.minVersion);
  72927. return null;
  72928. }
  72929. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  72930. onError("Incompatible minimum version: " + asset.minVersion);
  72931. return null;
  72932. }
  72933. }
  72934. var createLoaders = {
  72935. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  72936. 2: GLTFFileLoader.CreateGLTFLoaderV2
  72937. };
  72938. var createLoader = createLoaders[version.major];
  72939. if (!createLoader) {
  72940. onError("Unsupported version: " + asset.version);
  72941. return null;
  72942. }
  72943. return createLoader(this);
  72944. };
  72945. GLTFFileLoader._parseBinary = function (data, onError) {
  72946. var Binary = {
  72947. Magic: 0x46546C67
  72948. };
  72949. var binaryReader = new BinaryReader(data);
  72950. var magic = binaryReader.readUint32();
  72951. if (magic !== Binary.Magic) {
  72952. onError("Unexpected magic: " + magic);
  72953. return null;
  72954. }
  72955. var version = binaryReader.readUint32();
  72956. switch (version) {
  72957. case 1: return GLTFFileLoader._parseV1(binaryReader, onError);
  72958. case 2: return GLTFFileLoader._parseV2(binaryReader, onError);
  72959. }
  72960. onError("Unsupported version: " + version);
  72961. return null;
  72962. };
  72963. GLTFFileLoader._parseV1 = function (binaryReader, onError) {
  72964. var ContentFormat = {
  72965. JSON: 0
  72966. };
  72967. var length = binaryReader.readUint32();
  72968. if (length != binaryReader.getLength()) {
  72969. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  72970. return null;
  72971. }
  72972. var contentLength = binaryReader.readUint32();
  72973. var contentFormat = binaryReader.readUint32();
  72974. var content;
  72975. switch (contentFormat) {
  72976. case ContentFormat.JSON:
  72977. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  72978. break;
  72979. default:
  72980. onError("Unexpected content format: " + contentFormat);
  72981. return null;
  72982. }
  72983. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  72984. var body = binaryReader.readUint8Array(bytesRemaining);
  72985. return {
  72986. json: content,
  72987. bin: body
  72988. };
  72989. };
  72990. GLTFFileLoader._parseV2 = function (binaryReader, onError) {
  72991. var ChunkFormat = {
  72992. JSON: 0x4E4F534A,
  72993. BIN: 0x004E4942
  72994. };
  72995. var length = binaryReader.readUint32();
  72996. if (length !== binaryReader.getLength()) {
  72997. onError("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  72998. return null;
  72999. }
  73000. // JSON chunk
  73001. var chunkLength = binaryReader.readUint32();
  73002. var chunkFormat = binaryReader.readUint32();
  73003. if (chunkFormat !== ChunkFormat.JSON) {
  73004. onError("First chunk format is not JSON");
  73005. return null;
  73006. }
  73007. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  73008. // Look for BIN chunk
  73009. var bin = null;
  73010. while (binaryReader.getPosition() < binaryReader.getLength()) {
  73011. chunkLength = binaryReader.readUint32();
  73012. chunkFormat = binaryReader.readUint32();
  73013. switch (chunkFormat) {
  73014. case ChunkFormat.JSON:
  73015. onError("Unexpected JSON chunk");
  73016. return null;
  73017. case ChunkFormat.BIN:
  73018. bin = binaryReader.readUint8Array(chunkLength);
  73019. break;
  73020. default:
  73021. // ignore unrecognized chunkFormat
  73022. binaryReader.skipBytes(chunkLength);
  73023. break;
  73024. }
  73025. }
  73026. return {
  73027. json: json,
  73028. bin: bin
  73029. };
  73030. };
  73031. GLTFFileLoader._parseVersion = function (version) {
  73032. if (!version) {
  73033. return null;
  73034. }
  73035. var parts = version.split(".");
  73036. if (parts.length != 2) {
  73037. return null;
  73038. }
  73039. var major = +parts[0];
  73040. if (isNaN(major)) {
  73041. return null;
  73042. }
  73043. var minor = +parts[1];
  73044. if (isNaN(minor)) {
  73045. return null;
  73046. }
  73047. return {
  73048. major: major,
  73049. minor: minor
  73050. };
  73051. };
  73052. GLTFFileLoader._compareVersion = function (a, b) {
  73053. if (a.major > b.major)
  73054. return 1;
  73055. if (a.major < b.major)
  73056. return -1;
  73057. if (a.minor > b.minor)
  73058. return 1;
  73059. if (a.minor < b.minor)
  73060. return -1;
  73061. return 0;
  73062. };
  73063. GLTFFileLoader._decodeBufferToText = function (view) {
  73064. var result = "";
  73065. var length = view.byteLength;
  73066. for (var i = 0; i < length; ++i) {
  73067. result += String.fromCharCode(view[i]);
  73068. }
  73069. return result;
  73070. };
  73071. // V1 options
  73072. GLTFFileLoader.HomogeneousCoordinates = false;
  73073. GLTFFileLoader.IncrementalLoading = true;
  73074. return GLTFFileLoader;
  73075. }());
  73076. BABYLON.GLTFFileLoader = GLTFFileLoader;
  73077. var BinaryReader = (function () {
  73078. function BinaryReader(arrayBuffer) {
  73079. this._arrayBuffer = arrayBuffer;
  73080. this._dataView = new DataView(arrayBuffer);
  73081. this._byteOffset = 0;
  73082. }
  73083. BinaryReader.prototype.getPosition = function () {
  73084. return this._byteOffset;
  73085. };
  73086. BinaryReader.prototype.getLength = function () {
  73087. return this._arrayBuffer.byteLength;
  73088. };
  73089. BinaryReader.prototype.readUint32 = function () {
  73090. var value = this._dataView.getUint32(this._byteOffset, true);
  73091. this._byteOffset += 4;
  73092. return value;
  73093. };
  73094. BinaryReader.prototype.readUint8Array = function (length) {
  73095. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  73096. this._byteOffset += length;
  73097. return value;
  73098. };
  73099. BinaryReader.prototype.skipBytes = function (length) {
  73100. this._byteOffset += length;
  73101. };
  73102. return BinaryReader;
  73103. }());
  73104. if (BABYLON.SceneLoader) {
  73105. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  73106. }
  73107. })(BABYLON || (BABYLON = {}));
  73108. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  73109. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  73110. var BABYLON;
  73111. (function (BABYLON) {
  73112. var GLTF1;
  73113. (function (GLTF1) {
  73114. /**
  73115. * Enums
  73116. */
  73117. var EComponentType;
  73118. (function (EComponentType) {
  73119. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  73120. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  73121. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  73122. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  73123. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  73124. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  73125. var EShaderType;
  73126. (function (EShaderType) {
  73127. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  73128. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  73129. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  73130. var EParameterType;
  73131. (function (EParameterType) {
  73132. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  73133. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  73134. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  73135. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  73136. EParameterType[EParameterType["INT"] = 5124] = "INT";
  73137. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  73138. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  73139. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  73140. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  73141. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  73142. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  73143. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  73144. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  73145. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  73146. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  73147. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  73148. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  73149. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  73150. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  73151. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  73152. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  73153. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  73154. var ETextureWrapMode;
  73155. (function (ETextureWrapMode) {
  73156. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  73157. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  73158. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  73159. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  73160. var ETextureFilterType;
  73161. (function (ETextureFilterType) {
  73162. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  73163. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  73164. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  73165. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  73166. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  73167. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  73168. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  73169. var ETextureFormat;
  73170. (function (ETextureFormat) {
  73171. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  73172. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  73173. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  73174. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  73175. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  73176. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  73177. var ECullingType;
  73178. (function (ECullingType) {
  73179. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  73180. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  73181. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  73182. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  73183. var EBlendingFunction;
  73184. (function (EBlendingFunction) {
  73185. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  73186. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  73187. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  73188. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  73189. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  73190. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  73191. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  73192. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  73193. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  73194. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  73195. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  73196. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  73197. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  73198. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  73199. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  73200. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  73201. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  73202. })(BABYLON || (BABYLON = {}));
  73203. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  73204. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  73205. var BABYLON;
  73206. (function (BABYLON) {
  73207. var GLTF1;
  73208. (function (GLTF1) {
  73209. /**
  73210. * Tokenizer. Used for shaders compatibility
  73211. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  73212. */
  73213. var ETokenType;
  73214. (function (ETokenType) {
  73215. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  73216. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  73217. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  73218. })(ETokenType || (ETokenType = {}));
  73219. var Tokenizer = (function () {
  73220. function Tokenizer(toParse) {
  73221. this._pos = 0;
  73222. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  73223. this._toParse = toParse;
  73224. this._maxPos = toParse.length;
  73225. }
  73226. Tokenizer.prototype.getNextToken = function () {
  73227. if (this.isEnd())
  73228. return ETokenType.END_OF_INPUT;
  73229. this.currentString = this.read();
  73230. this.currentToken = ETokenType.UNKNOWN;
  73231. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  73232. this.currentToken = ETokenType.IDENTIFIER;
  73233. this.currentIdentifier = this.currentString;
  73234. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  73235. this.currentIdentifier += this.currentString;
  73236. this.forward();
  73237. }
  73238. }
  73239. return this.currentToken;
  73240. };
  73241. Tokenizer.prototype.peek = function () {
  73242. return this._toParse[this._pos];
  73243. };
  73244. Tokenizer.prototype.read = function () {
  73245. return this._toParse[this._pos++];
  73246. };
  73247. Tokenizer.prototype.forward = function () {
  73248. this._pos++;
  73249. };
  73250. Tokenizer.prototype.isEnd = function () {
  73251. return this._pos >= this._maxPos;
  73252. };
  73253. return Tokenizer;
  73254. }());
  73255. /**
  73256. * Values
  73257. */
  73258. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  73259. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  73260. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  73261. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  73262. /**
  73263. * Parse
  73264. */
  73265. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  73266. for (var buf in parsedBuffers) {
  73267. var parsedBuffer = parsedBuffers[buf];
  73268. gltfRuntime.buffers[buf] = parsedBuffer;
  73269. gltfRuntime.buffersCount++;
  73270. }
  73271. };
  73272. var parseShaders = function (parsedShaders, gltfRuntime) {
  73273. for (var sha in parsedShaders) {
  73274. var parsedShader = parsedShaders[sha];
  73275. gltfRuntime.shaders[sha] = parsedShader;
  73276. gltfRuntime.shaderscount++;
  73277. }
  73278. };
  73279. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  73280. for (var object in parsedObjects) {
  73281. var parsedObject = parsedObjects[object];
  73282. gltfRuntime[runtimeProperty][object] = parsedObject;
  73283. }
  73284. };
  73285. /**
  73286. * Utils
  73287. */
  73288. var normalizeUVs = function (buffer) {
  73289. if (!buffer) {
  73290. return;
  73291. }
  73292. for (var i = 0; i < buffer.length / 2; i++) {
  73293. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  73294. }
  73295. };
  73296. var replaceInString = function (str, searchValue, replaceValue) {
  73297. while (str.indexOf(searchValue) !== -1) {
  73298. str = str.replace(searchValue, replaceValue);
  73299. }
  73300. return str;
  73301. };
  73302. var getAttribute = function (attributeParameter) {
  73303. if (attributeParameter.semantic === "NORMAL") {
  73304. return "normal";
  73305. }
  73306. else if (attributeParameter.semantic === "POSITION") {
  73307. return "position";
  73308. }
  73309. else if (attributeParameter.semantic === "JOINT") {
  73310. return "matricesIndices";
  73311. }
  73312. else if (attributeParameter.semantic === "WEIGHT") {
  73313. return "matricesWeights";
  73314. }
  73315. else if (attributeParameter.semantic === "COLOR") {
  73316. return "color";
  73317. }
  73318. else if (attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  73319. var channel = Number(attributeParameter.semantic.split("_")[1]);
  73320. return "uv" + (channel === 0 ? "" : channel + 1);
  73321. }
  73322. };
  73323. /**
  73324. * Returns the animation path (glTF -> Babylon)
  73325. */
  73326. var getAnimationPath = function (path) {
  73327. var index = glTFAnimationPaths.indexOf(path);
  73328. if (index !== -1) {
  73329. return babylonAnimationPaths[index];
  73330. }
  73331. return path;
  73332. };
  73333. /**
  73334. * Loads and creates animations
  73335. */
  73336. var loadAnimations = function (gltfRuntime) {
  73337. for (var anim in gltfRuntime.animations) {
  73338. var animation = gltfRuntime.animations[anim];
  73339. var lastAnimation = null;
  73340. for (var i = 0; i < animation.channels.length; i++) {
  73341. // Get parameters and load buffers
  73342. var channel = animation.channels[i];
  73343. var sampler = animation.samplers[channel.sampler];
  73344. if (!sampler) {
  73345. continue;
  73346. }
  73347. var inputData = null;
  73348. var outputData = null;
  73349. if (animation.parameters) {
  73350. inputData = animation.parameters[sampler.input];
  73351. outputData = animation.parameters[sampler.output];
  73352. }
  73353. else {
  73354. inputData = sampler.input;
  73355. outputData = sampler.output;
  73356. }
  73357. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  73358. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  73359. var targetID = channel.target.id;
  73360. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  73361. if (targetNode === null) {
  73362. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  73363. }
  73364. if (targetNode === null) {
  73365. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  73366. continue;
  73367. }
  73368. var isBone = targetNode instanceof BABYLON.Bone;
  73369. // Get target path (position, rotation or scaling)
  73370. var targetPath = channel.target.path;
  73371. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  73372. if (targetPathIndex !== -1) {
  73373. targetPath = babylonAnimationPaths[targetPathIndex];
  73374. }
  73375. // Determine animation type
  73376. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  73377. if (!isBone) {
  73378. if (targetPath === "rotationQuaternion") {
  73379. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  73380. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  73381. }
  73382. else {
  73383. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  73384. }
  73385. }
  73386. // Create animation and key frames
  73387. var babylonAnimation = null;
  73388. var keys = [];
  73389. var arrayOffset = 0;
  73390. var modifyKey = false;
  73391. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  73392. babylonAnimation = lastAnimation;
  73393. modifyKey = true;
  73394. }
  73395. if (!modifyKey) {
  73396. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  73397. }
  73398. // For each frame
  73399. for (var j = 0; j < bufferInput.length; j++) {
  73400. var value = null;
  73401. if (targetPath === "rotationQuaternion") {
  73402. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  73403. arrayOffset += 4;
  73404. }
  73405. else {
  73406. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  73407. arrayOffset += 3;
  73408. }
  73409. if (isBone) {
  73410. var bone = targetNode;
  73411. var translation = BABYLON.Vector3.Zero();
  73412. var rotationQuaternion = new BABYLON.Quaternion();
  73413. var scaling = BABYLON.Vector3.Zero();
  73414. // Warning on decompose
  73415. var mat = bone.getBaseMatrix();
  73416. if (modifyKey) {
  73417. mat = lastAnimation.getKeys()[j].value;
  73418. }
  73419. mat.decompose(scaling, rotationQuaternion, translation);
  73420. if (targetPath === "position") {
  73421. translation = value;
  73422. }
  73423. else if (targetPath === "rotationQuaternion") {
  73424. rotationQuaternion = value;
  73425. }
  73426. else {
  73427. scaling = value;
  73428. }
  73429. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  73430. }
  73431. if (!modifyKey) {
  73432. keys.push({
  73433. frame: bufferInput[j],
  73434. value: value
  73435. });
  73436. }
  73437. else {
  73438. lastAnimation.getKeys()[j].value = value;
  73439. }
  73440. }
  73441. // Finish
  73442. if (!modifyKey) {
  73443. babylonAnimation.setKeys(keys);
  73444. targetNode.animations.push(babylonAnimation);
  73445. }
  73446. lastAnimation = babylonAnimation;
  73447. gltfRuntime.scene.stopAnimation(targetNode);
  73448. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  73449. }
  73450. }
  73451. };
  73452. /**
  73453. * Returns the bones transformation matrix
  73454. */
  73455. var configureBoneTransformation = function (node) {
  73456. var mat = null;
  73457. if (node.translation || node.rotation || node.scale) {
  73458. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  73459. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  73460. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  73461. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  73462. }
  73463. else {
  73464. mat = BABYLON.Matrix.FromArray(node.matrix);
  73465. }
  73466. return mat;
  73467. };
  73468. /**
  73469. * Returns the parent bone
  73470. */
  73471. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  73472. // Try to find
  73473. for (var i = 0; i < newSkeleton.bones.length; i++) {
  73474. if (newSkeleton.bones[i].name === jointName) {
  73475. return newSkeleton.bones[i];
  73476. }
  73477. }
  73478. // Not found, search in gltf nodes
  73479. var nodes = gltfRuntime.nodes;
  73480. for (var nde in nodes) {
  73481. var node = nodes[nde];
  73482. if (!node.jointName) {
  73483. continue;
  73484. }
  73485. var children = node.children;
  73486. for (var i = 0; i < children.length; i++) {
  73487. var child = gltfRuntime.nodes[children[i]];
  73488. if (!child.jointName) {
  73489. continue;
  73490. }
  73491. if (child.jointName === jointName) {
  73492. var mat = configureBoneTransformation(node);
  73493. var bone = new BABYLON.Bone(node.name, newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  73494. bone.id = nde;
  73495. return bone;
  73496. }
  73497. }
  73498. }
  73499. return null;
  73500. };
  73501. /**
  73502. * Returns the appropriate root node
  73503. */
  73504. var getNodeToRoot = function (nodesToRoot, id) {
  73505. for (var i = 0; i < nodesToRoot.length; i++) {
  73506. var nodeToRoot = nodesToRoot[i];
  73507. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  73508. var child = nodeToRoot.node.children[j];
  73509. if (child === id) {
  73510. return nodeToRoot.bone;
  73511. }
  73512. }
  73513. }
  73514. return null;
  73515. };
  73516. /**
  73517. * Returns the node with the joint name
  73518. */
  73519. var getJointNode = function (gltfRuntime, jointName) {
  73520. var nodes = gltfRuntime.nodes;
  73521. var node = nodes[jointName];
  73522. if (node) {
  73523. return {
  73524. node: node,
  73525. id: jointName
  73526. };
  73527. }
  73528. for (var nde in nodes) {
  73529. node = nodes[nde];
  73530. if (node.jointName === jointName) {
  73531. return {
  73532. node: node,
  73533. id: nde
  73534. };
  73535. }
  73536. }
  73537. return null;
  73538. };
  73539. /**
  73540. * Checks if a nodes is in joints
  73541. */
  73542. var nodeIsInJoints = function (skins, id) {
  73543. for (var i = 0; i < skins.jointNames.length; i++) {
  73544. if (skins.jointNames[i] === id) {
  73545. return true;
  73546. }
  73547. }
  73548. return false;
  73549. };
  73550. /**
  73551. * Fills the nodes to root for bones and builds hierarchy
  73552. */
  73553. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  73554. // Creates nodes for root
  73555. for (var nde in gltfRuntime.nodes) {
  73556. var node = gltfRuntime.nodes[nde];
  73557. var id = nde;
  73558. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  73559. continue;
  73560. }
  73561. // Create node to root bone
  73562. var mat = configureBoneTransformation(node);
  73563. var bone = new BABYLON.Bone(node.name, newSkeleton, null, mat);
  73564. bone.id = id;
  73565. nodesToRoot.push({ bone: bone, node: node, id: id });
  73566. }
  73567. // Parenting
  73568. for (var i = 0; i < nodesToRoot.length; i++) {
  73569. var nodeToRoot = nodesToRoot[i];
  73570. var children = nodeToRoot.node.children;
  73571. for (var j = 0; j < children.length; j++) {
  73572. var child = null;
  73573. for (var k = 0; k < nodesToRoot.length; k++) {
  73574. if (nodesToRoot[k].id === children[j]) {
  73575. child = nodesToRoot[k];
  73576. break;
  73577. }
  73578. }
  73579. if (child) {
  73580. child.bone._parent = nodeToRoot.bone;
  73581. nodeToRoot.bone.children.push(child.bone);
  73582. }
  73583. }
  73584. }
  73585. };
  73586. var printMat = function (m) {
  73587. console.log(m[0] + "\t" + m[1] + "\t" + m[2] + "\t" + m[3] + "\n" +
  73588. m[4] + "\t" + m[5] + "\t" + m[6] + "\t" + m[7] + "\n" +
  73589. m[8] + "\t" + m[9] + "\t" + m[10] + "\t" + m[11] + "\n" +
  73590. m[12] + "\t" + m[13] + "\t" + m[14] + "\t" + m[15] + "\n");
  73591. };
  73592. /**
  73593. * Imports a skeleton
  73594. */
  73595. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  73596. if (!newSkeleton) {
  73597. newSkeleton = new BABYLON.Skeleton(skins.name, "", gltfRuntime.scene);
  73598. }
  73599. if (!skins.babylonSkeleton) {
  73600. return newSkeleton;
  73601. }
  73602. // Matrices
  73603. var accessor = gltfRuntime.accessors[skins.inverseBindMatrices];
  73604. var buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  73605. var bindShapeMatrix = BABYLON.Matrix.FromArray(skins.bindShapeMatrix);
  73606. // Find the root bones
  73607. var nodesToRoot = [];
  73608. var nodesToRootToAdd = [];
  73609. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  73610. newSkeleton.bones = [];
  73611. // Joints
  73612. for (var i = 0; i < skins.jointNames.length; i++) {
  73613. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  73614. var node = jointNode.node;
  73615. if (!node) {
  73616. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  73617. continue;
  73618. }
  73619. var id = jointNode.id;
  73620. // Optimize, if the bone already exists...
  73621. var existingBone = gltfRuntime.scene.getBoneByID(id);
  73622. if (existingBone) {
  73623. newSkeleton.bones.push(existingBone);
  73624. continue;
  73625. }
  73626. // Search for parent bone
  73627. var foundBone = false;
  73628. var parentBone = null;
  73629. for (var j = 0; j < i; j++) {
  73630. var joint = getJointNode(gltfRuntime, skins.jointNames[j]).node;
  73631. if (!joint) {
  73632. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  73633. continue;
  73634. }
  73635. var children = joint.children;
  73636. if (!children) {
  73637. continue;
  73638. }
  73639. foundBone = false;
  73640. for (var k = 0; k < children.length; k++) {
  73641. if (children[k] === id) {
  73642. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  73643. foundBone = true;
  73644. break;
  73645. }
  73646. }
  73647. if (foundBone) {
  73648. break;
  73649. }
  73650. }
  73651. // Create bone
  73652. var mat = configureBoneTransformation(node);
  73653. if (!parentBone && nodesToRoot.length > 0) {
  73654. parentBone = getNodeToRoot(nodesToRoot, id);
  73655. if (parentBone) {
  73656. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  73657. nodesToRootToAdd.push(parentBone);
  73658. }
  73659. }
  73660. }
  73661. var bone = new BABYLON.Bone(node.jointName, newSkeleton, parentBone, mat);
  73662. bone.id = id;
  73663. }
  73664. // Polish
  73665. var bones = newSkeleton.bones;
  73666. newSkeleton.bones = [];
  73667. for (var i = 0; i < skins.jointNames.length; i++) {
  73668. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  73669. if (!jointNode) {
  73670. continue;
  73671. }
  73672. for (var j = 0; j < bones.length; j++) {
  73673. if (bones[j].id === jointNode.id) {
  73674. newSkeleton.bones.push(bones[j]);
  73675. break;
  73676. }
  73677. }
  73678. }
  73679. newSkeleton.prepare();
  73680. // Finish
  73681. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  73682. newSkeleton.bones.push(nodesToRootToAdd[i]);
  73683. }
  73684. return newSkeleton;
  73685. };
  73686. /**
  73687. * Imports a mesh and its geometries
  73688. */
  73689. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  73690. if (!newMesh) {
  73691. newMesh = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  73692. newMesh.id = id;
  73693. }
  73694. if (!node.babylonNode) {
  73695. return newMesh;
  73696. }
  73697. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  73698. if (!newMesh.material) {
  73699. newMesh.material = multiMat;
  73700. }
  73701. var vertexData = new BABYLON.VertexData();
  73702. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  73703. var verticesStarts = new Array();
  73704. var verticesCounts = new Array();
  73705. var indexStarts = new Array();
  73706. var indexCounts = new Array();
  73707. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  73708. var meshID = meshes[meshIndex];
  73709. var mesh = gltfRuntime.meshes[meshID];
  73710. if (!mesh) {
  73711. continue;
  73712. }
  73713. // Positions, normals and UVs
  73714. for (var i = 0; i < mesh.primitives.length; i++) {
  73715. // Temporary vertex data
  73716. var tempVertexData = new BABYLON.VertexData();
  73717. var primitive = mesh.primitives[i];
  73718. if (primitive.mode !== 4) {
  73719. // continue;
  73720. }
  73721. var attributes = primitive.attributes;
  73722. var accessor = null;
  73723. var buffer = null;
  73724. // Set positions, normal and uvs
  73725. for (var semantic in attributes) {
  73726. // Link accessor and buffer view
  73727. accessor = gltfRuntime.accessors[attributes[semantic]];
  73728. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  73729. if (semantic === "NORMAL") {
  73730. tempVertexData.normals = new Float32Array(buffer.length);
  73731. tempVertexData.normals.set(buffer);
  73732. }
  73733. else if (semantic === "POSITION") {
  73734. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  73735. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  73736. for (var j = 0; j < buffer.length; j += 4) {
  73737. tempVertexData.positions[j] = buffer[j];
  73738. tempVertexData.positions[j + 1] = buffer[j + 1];
  73739. tempVertexData.positions[j + 2] = buffer[j + 2];
  73740. }
  73741. }
  73742. else {
  73743. tempVertexData.positions = new Float32Array(buffer.length);
  73744. tempVertexData.positions.set(buffer);
  73745. }
  73746. verticesCounts.push(tempVertexData.positions.length);
  73747. }
  73748. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  73749. var channel = Number(semantic.split("_")[1]);
  73750. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  73751. var uvs = new Float32Array(buffer.length);
  73752. uvs.set(buffer);
  73753. normalizeUVs(uvs);
  73754. tempVertexData.set(uvs, uvKind);
  73755. }
  73756. else if (semantic === "JOINT") {
  73757. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  73758. tempVertexData.matricesIndices.set(buffer);
  73759. }
  73760. else if (semantic === "WEIGHT") {
  73761. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  73762. tempVertexData.matricesWeights.set(buffer);
  73763. }
  73764. else if (semantic === "COLOR") {
  73765. tempVertexData.colors = new Float32Array(buffer.length);
  73766. tempVertexData.colors.set(buffer);
  73767. }
  73768. }
  73769. // Indices
  73770. accessor = gltfRuntime.accessors[primitive.indices];
  73771. if (accessor) {
  73772. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  73773. tempVertexData.indices = new Int32Array(buffer.length);
  73774. tempVertexData.indices.set(buffer);
  73775. indexCounts.push(tempVertexData.indices.length);
  73776. }
  73777. else {
  73778. // Set indices on the fly
  73779. var indices = [];
  73780. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  73781. indices.push(j);
  73782. }
  73783. tempVertexData.indices = new Int32Array(indices);
  73784. indexCounts.push(tempVertexData.indices.length);
  73785. }
  73786. vertexData.merge(tempVertexData);
  73787. tempVertexData = undefined;
  73788. // Sub material
  73789. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  73790. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  73791. // Update vertices start and index start
  73792. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  73793. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  73794. }
  73795. }
  73796. // Apply geometry
  73797. geometry.setAllVerticesData(vertexData, false);
  73798. newMesh.computeWorldMatrix(true);
  73799. // Apply submeshes
  73800. newMesh.subMeshes = [];
  73801. var index = 0;
  73802. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  73803. var meshID = meshes[meshIndex];
  73804. var mesh = gltfRuntime.meshes[meshID];
  73805. if (!mesh) {
  73806. continue;
  73807. }
  73808. for (var i = 0; i < mesh.primitives.length; i++) {
  73809. if (mesh.primitives[i].mode !== 4) {
  73810. //continue;
  73811. }
  73812. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  73813. index++;
  73814. }
  73815. }
  73816. // Finish
  73817. return newMesh;
  73818. };
  73819. /**
  73820. * Configure node transformation from position, rotation and scaling
  73821. */
  73822. var configureNode = function (newNode, position, rotation, scaling) {
  73823. if (newNode.position) {
  73824. newNode.position = position;
  73825. }
  73826. if (newNode.rotationQuaternion || newNode.rotation) {
  73827. newNode.rotationQuaternion = rotation;
  73828. }
  73829. if (newNode.scaling) {
  73830. newNode.scaling = scaling;
  73831. }
  73832. };
  73833. /**
  73834. * Configures node from transformation matrix
  73835. */
  73836. var configureNodeFromMatrix = function (newNode, node, parent) {
  73837. if (node.matrix) {
  73838. var position = new BABYLON.Vector3(0, 0, 0);
  73839. var rotation = new BABYLON.Quaternion();
  73840. var scaling = new BABYLON.Vector3(0, 0, 0);
  73841. var mat = BABYLON.Matrix.FromArray(node.matrix);
  73842. mat.decompose(scaling, rotation, position);
  73843. configureNode(newNode, position, rotation, scaling);
  73844. }
  73845. else {
  73846. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  73847. }
  73848. newNode.computeWorldMatrix(true);
  73849. };
  73850. /**
  73851. * Imports a node
  73852. */
  73853. var importNode = function (gltfRuntime, node, id, parent) {
  73854. var lastNode = null;
  73855. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  73856. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  73857. return null;
  73858. }
  73859. }
  73860. // Meshes
  73861. if (node.skin) {
  73862. if (node.meshes) {
  73863. var skin = gltfRuntime.skins[node.skin];
  73864. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  73865. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  73866. if (newMesh.skeleton === null) {
  73867. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  73868. if (!skin.babylonSkeleton) {
  73869. skin.babylonSkeleton = newMesh.skeleton;
  73870. }
  73871. }
  73872. lastNode = newMesh;
  73873. }
  73874. }
  73875. else if (node.meshes) {
  73876. /**
  73877. * Improve meshes property
  73878. */
  73879. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  73880. lastNode = newMesh;
  73881. }
  73882. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  73883. var light = gltfRuntime.lights[node.light];
  73884. if (light) {
  73885. if (light.type === "ambient") {
  73886. var ambienLight = light[light.type];
  73887. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73888. hemiLight.name = node.name;
  73889. if (ambienLight.color) {
  73890. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  73891. }
  73892. lastNode = hemiLight;
  73893. }
  73894. else if (light.type === "directional") {
  73895. var directionalLight = light[light.type];
  73896. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73897. dirLight.name = node.name;
  73898. if (directionalLight.color) {
  73899. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  73900. }
  73901. lastNode = dirLight;
  73902. }
  73903. else if (light.type === "point") {
  73904. var pointLight = light[light.type];
  73905. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73906. ptLight.name = node.name;
  73907. if (pointLight.color) {
  73908. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  73909. }
  73910. lastNode = ptLight;
  73911. }
  73912. else if (light.type === "spot") {
  73913. var spotLight = light[light.type];
  73914. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  73915. spLight.name = node.name;
  73916. if (spotLight.color) {
  73917. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  73918. }
  73919. if (spotLight.fallOfAngle) {
  73920. spLight.angle = spotLight.fallOfAngle;
  73921. }
  73922. if (spotLight.fallOffExponent) {
  73923. spLight.exponent = spotLight.fallOffExponent;
  73924. }
  73925. lastNode = spLight;
  73926. }
  73927. }
  73928. }
  73929. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  73930. var camera = gltfRuntime.cameras[node.camera];
  73931. if (camera) {
  73932. if (camera.type === "orthographic") {
  73933. var orthographicCamera = camera[camera.type];
  73934. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73935. orthoCamera.name = node.name;
  73936. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  73937. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  73938. lastNode = orthoCamera;
  73939. }
  73940. else if (camera.type === "perspective") {
  73941. var perspectiveCamera = camera[camera.type];
  73942. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  73943. persCamera.name = node.name;
  73944. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  73945. if (!perspectiveCamera.aspectRatio) {
  73946. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  73947. }
  73948. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  73949. persCamera.maxZ = perspectiveCamera.zfar;
  73950. persCamera.minZ = perspectiveCamera.znear;
  73951. }
  73952. lastNode = persCamera;
  73953. }
  73954. }
  73955. }
  73956. // Empty node
  73957. if (!node.jointName) {
  73958. if (node.babylonNode) {
  73959. return node.babylonNode;
  73960. }
  73961. else if (lastNode === null) {
  73962. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  73963. node.babylonNode = dummy;
  73964. lastNode = dummy;
  73965. }
  73966. }
  73967. if (lastNode !== null) {
  73968. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  73969. configureNodeFromMatrix(lastNode, node, parent);
  73970. }
  73971. else {
  73972. var translation = node.translation || [0, 0, 0];
  73973. var rotation = node.rotation || [0, 0, 0, 1];
  73974. var scale = node.scale || [1, 1, 1];
  73975. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  73976. }
  73977. lastNode.updateCache(true);
  73978. node.babylonNode = lastNode;
  73979. }
  73980. return lastNode;
  73981. };
  73982. /**
  73983. * Traverses nodes and creates them
  73984. */
  73985. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  73986. var node = gltfRuntime.nodes[id];
  73987. var newNode = null;
  73988. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  73989. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  73990. meshIncluded = true;
  73991. }
  73992. else {
  73993. meshIncluded = false;
  73994. }
  73995. }
  73996. else {
  73997. meshIncluded = true;
  73998. }
  73999. if (!node.jointName && meshIncluded) {
  74000. newNode = importNode(gltfRuntime, node, id, parent);
  74001. if (newNode !== null) {
  74002. newNode.id = id;
  74003. newNode.parent = parent;
  74004. }
  74005. }
  74006. if (node.children) {
  74007. for (var i = 0; i < node.children.length; i++) {
  74008. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  74009. }
  74010. }
  74011. };
  74012. /**
  74013. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  74014. */
  74015. var postLoad = function (gltfRuntime) {
  74016. // Nodes
  74017. var currentScene = gltfRuntime.currentScene;
  74018. if (currentScene) {
  74019. for (var i = 0; i < currentScene.nodes.length; i++) {
  74020. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  74021. }
  74022. }
  74023. else {
  74024. for (var thing in gltfRuntime.scenes) {
  74025. currentScene = gltfRuntime.scenes[thing];
  74026. for (var i = 0; i < currentScene.nodes.length; i++) {
  74027. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  74028. }
  74029. }
  74030. }
  74031. // Set animations
  74032. loadAnimations(gltfRuntime);
  74033. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  74034. var skeleton = gltfRuntime.scene.skeletons[i];
  74035. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  74036. }
  74037. };
  74038. /**
  74039. * onBind shaderrs callback to set uniforms and matrices
  74040. */
  74041. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  74042. var materialValues = material.values || technique.parameters;
  74043. for (var unif in unTreatedUniforms) {
  74044. var uniform = unTreatedUniforms[unif];
  74045. var type = uniform.type;
  74046. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  74047. if (uniform.semantic && !uniform.source && !uniform.node) {
  74048. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  74049. }
  74050. else if (uniform.semantic && (uniform.source || uniform.node)) {
  74051. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  74052. if (source === null) {
  74053. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  74054. }
  74055. if (source === null) {
  74056. continue;
  74057. }
  74058. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  74059. }
  74060. }
  74061. else {
  74062. var value = materialValues[technique.uniforms[unif]];
  74063. if (!value) {
  74064. continue;
  74065. }
  74066. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  74067. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  74068. if (texture === null || texture === undefined) {
  74069. continue;
  74070. }
  74071. shaderMaterial.getEffect().setTexture(unif, texture);
  74072. }
  74073. else {
  74074. GLTF1.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  74075. }
  74076. }
  74077. }
  74078. onSuccess(shaderMaterial);
  74079. };
  74080. /**
  74081. * Prepare uniforms to send the only one time
  74082. * Loads the appropriate textures
  74083. */
  74084. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  74085. var materialValues = material.values || technique.parameters;
  74086. var techniqueUniforms = technique.uniforms;
  74087. /**
  74088. * Prepare values here (not matrices)
  74089. */
  74090. for (var unif in unTreatedUniforms) {
  74091. var uniform = unTreatedUniforms[unif];
  74092. var type = uniform.type;
  74093. var value = materialValues[techniqueUniforms[unif]];
  74094. if (value === undefined) {
  74095. // In case the value is the same for all materials
  74096. value = uniform.value;
  74097. }
  74098. if (!value) {
  74099. continue;
  74100. }
  74101. var onLoadTexture = function (uniformName) {
  74102. return function (texture) {
  74103. if (uniform.value) {
  74104. // Static uniform
  74105. shaderMaterial.setTexture(uniformName, texture);
  74106. delete unTreatedUniforms[uniformName];
  74107. }
  74108. };
  74109. };
  74110. // Texture (sampler2D)
  74111. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  74112. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  74113. }
  74114. else {
  74115. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  74116. // Static uniform
  74117. delete unTreatedUniforms[unif];
  74118. }
  74119. }
  74120. }
  74121. };
  74122. /**
  74123. * Shader compilation failed
  74124. */
  74125. var onShaderCompileError = function (program, shaderMaterial, onError) {
  74126. return function (effect, error) {
  74127. shaderMaterial.dispose(true);
  74128. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  74129. };
  74130. };
  74131. /**
  74132. * Shader compilation success
  74133. */
  74134. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  74135. return function (_) {
  74136. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  74137. shaderMaterial.onBind = function (mesh) {
  74138. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  74139. };
  74140. };
  74141. };
  74142. /**
  74143. * Returns the appropriate uniform if already handled by babylon
  74144. */
  74145. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  74146. for (var unif in technique.uniforms) {
  74147. var uniform = technique.uniforms[unif];
  74148. var uniformParameter = technique.parameters[uniform];
  74149. if (tokenizer.currentIdentifier === unif) {
  74150. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  74151. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  74152. if (transformIndex !== -1) {
  74153. delete unTreatedUniforms[unif];
  74154. return babylonTransforms[transformIndex];
  74155. }
  74156. }
  74157. }
  74158. }
  74159. return tokenizer.currentIdentifier;
  74160. };
  74161. /**
  74162. * All shaders loaded. Create materials one by one
  74163. */
  74164. var importMaterials = function (gltfRuntime) {
  74165. // Create materials
  74166. for (var mat in gltfRuntime.materials) {
  74167. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  74168. }
  74169. };
  74170. /**
  74171. * Implementation of the base glTF spec
  74172. */
  74173. var GLTFLoaderBase = (function () {
  74174. function GLTFLoaderBase() {
  74175. }
  74176. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  74177. var gltfRuntime = {
  74178. extensions: {},
  74179. accessors: {},
  74180. buffers: {},
  74181. bufferViews: {},
  74182. meshes: {},
  74183. lights: {},
  74184. cameras: {},
  74185. nodes: {},
  74186. images: {},
  74187. textures: {},
  74188. shaders: {},
  74189. programs: {},
  74190. samplers: {},
  74191. techniques: {},
  74192. materials: {},
  74193. animations: {},
  74194. skins: {},
  74195. extensionsUsed: [],
  74196. scenes: {},
  74197. buffersCount: 0,
  74198. shaderscount: 0,
  74199. scene: scene,
  74200. rootUrl: rootUrl,
  74201. loadedBufferCount: 0,
  74202. loadedBufferViews: {},
  74203. loadedShaderCount: 0,
  74204. importOnlyMeshes: false,
  74205. dummyNodes: []
  74206. };
  74207. // Parse
  74208. if (parsedData.extensions) {
  74209. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  74210. }
  74211. if (parsedData.extensionsUsed) {
  74212. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  74213. }
  74214. if (parsedData.buffers) {
  74215. parseBuffers(parsedData.buffers, gltfRuntime);
  74216. }
  74217. if (parsedData.bufferViews) {
  74218. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  74219. }
  74220. if (parsedData.accessors) {
  74221. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  74222. }
  74223. if (parsedData.meshes) {
  74224. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  74225. }
  74226. if (parsedData.lights) {
  74227. parseObject(parsedData.lights, "lights", gltfRuntime);
  74228. }
  74229. if (parsedData.cameras) {
  74230. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  74231. }
  74232. if (parsedData.nodes) {
  74233. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  74234. }
  74235. if (parsedData.images) {
  74236. parseObject(parsedData.images, "images", gltfRuntime);
  74237. }
  74238. if (parsedData.textures) {
  74239. parseObject(parsedData.textures, "textures", gltfRuntime);
  74240. }
  74241. if (parsedData.shaders) {
  74242. parseShaders(parsedData.shaders, gltfRuntime);
  74243. }
  74244. if (parsedData.programs) {
  74245. parseObject(parsedData.programs, "programs", gltfRuntime);
  74246. }
  74247. if (parsedData.samplers) {
  74248. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  74249. }
  74250. if (parsedData.techniques) {
  74251. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  74252. }
  74253. if (parsedData.materials) {
  74254. parseObject(parsedData.materials, "materials", gltfRuntime);
  74255. }
  74256. if (parsedData.animations) {
  74257. parseObject(parsedData.animations, "animations", gltfRuntime);
  74258. }
  74259. if (parsedData.skins) {
  74260. parseObject(parsedData.skins, "skins", gltfRuntime);
  74261. }
  74262. if (parsedData.scenes) {
  74263. gltfRuntime.scenes = parsedData.scenes;
  74264. }
  74265. if (parsedData.scene && parsedData.scenes) {
  74266. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  74267. }
  74268. return gltfRuntime;
  74269. };
  74270. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  74271. var buffer = gltfRuntime.buffers[id];
  74272. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  74273. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  74274. }
  74275. else {
  74276. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, null, true, function (request) {
  74277. onError(request.status + " " + request.statusText);
  74278. });
  74279. }
  74280. };
  74281. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  74282. var texture = gltfRuntime.textures[id];
  74283. if (!texture || !texture.source) {
  74284. onError(null);
  74285. return;
  74286. }
  74287. if (texture.babylonTexture) {
  74288. onSuccess(null);
  74289. return;
  74290. }
  74291. var source = gltfRuntime.images[texture.source];
  74292. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  74293. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  74294. }
  74295. else {
  74296. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, function (request) {
  74297. onError(request.status + " " + request.statusText);
  74298. });
  74299. }
  74300. };
  74301. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  74302. var texture = gltfRuntime.textures[id];
  74303. if (texture.babylonTexture) {
  74304. onSuccess(texture.babylonTexture);
  74305. return;
  74306. }
  74307. var sampler = gltfRuntime.samplers[texture.sampler];
  74308. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  74309. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  74310. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  74311. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  74312. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  74313. var blob = new Blob([buffer]);
  74314. var blobURL = URL.createObjectURL(blob);
  74315. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  74316. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  74317. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  74318. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  74319. newTexture.name = id;
  74320. texture.babylonTexture = newTexture;
  74321. onSuccess(newTexture);
  74322. };
  74323. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  74324. var shader = gltfRuntime.shaders[id];
  74325. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  74326. var shaderString = atob(shader.uri.split(",")[1]);
  74327. onSuccess(shaderString);
  74328. }
  74329. else {
  74330. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, function (request) {
  74331. onError(request.status + " " + request.statusText);
  74332. });
  74333. }
  74334. };
  74335. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  74336. var material = gltfRuntime.materials[id];
  74337. var technique = gltfRuntime.techniques[material.technique];
  74338. if (!technique) {
  74339. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  74340. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  74341. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  74342. onSuccess(defaultMaterial);
  74343. return;
  74344. }
  74345. var program = gltfRuntime.programs[technique.program];
  74346. var states = technique.states;
  74347. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  74348. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  74349. var newVertexShader = "";
  74350. var newPixelShader = "";
  74351. var vertexTokenizer = new Tokenizer(vertexShader);
  74352. var pixelTokenizer = new Tokenizer(pixelShader);
  74353. var unTreatedUniforms = {};
  74354. var uniforms = [];
  74355. var attributes = [];
  74356. var samplers = [];
  74357. // Fill uniform, sampler2D and attributes
  74358. for (var unif in technique.uniforms) {
  74359. var uniform = technique.uniforms[unif];
  74360. var uniformParameter = technique.parameters[uniform];
  74361. unTreatedUniforms[unif] = uniformParameter;
  74362. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  74363. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  74364. if (transformIndex !== -1) {
  74365. uniforms.push(babylonTransforms[transformIndex]);
  74366. delete unTreatedUniforms[unif];
  74367. }
  74368. else {
  74369. uniforms.push(unif);
  74370. }
  74371. }
  74372. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  74373. samplers.push(unif);
  74374. }
  74375. else {
  74376. uniforms.push(unif);
  74377. }
  74378. }
  74379. for (var attr in technique.attributes) {
  74380. var attribute = technique.attributes[attr];
  74381. var attributeParameter = technique.parameters[attribute];
  74382. if (attributeParameter.semantic) {
  74383. attributes.push(getAttribute(attributeParameter));
  74384. }
  74385. }
  74386. // Configure vertex shader
  74387. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  74388. var tokenType = vertexTokenizer.currentToken;
  74389. if (tokenType !== ETokenType.IDENTIFIER) {
  74390. newVertexShader += vertexTokenizer.currentString;
  74391. continue;
  74392. }
  74393. var foundAttribute = false;
  74394. for (var attr in technique.attributes) {
  74395. var attribute = technique.attributes[attr];
  74396. var attributeParameter = technique.parameters[attribute];
  74397. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  74398. newVertexShader += getAttribute(attributeParameter);
  74399. foundAttribute = true;
  74400. break;
  74401. }
  74402. }
  74403. if (foundAttribute) {
  74404. continue;
  74405. }
  74406. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  74407. }
  74408. // Configure pixel shader
  74409. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  74410. var tokenType = pixelTokenizer.currentToken;
  74411. if (tokenType !== ETokenType.IDENTIFIER) {
  74412. newPixelShader += pixelTokenizer.currentString;
  74413. continue;
  74414. }
  74415. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  74416. }
  74417. // Create shader material
  74418. var shaderPath = {
  74419. vertex: program.vertexShader + id,
  74420. fragment: program.fragmentShader + id
  74421. };
  74422. var options = {
  74423. attributes: attributes,
  74424. uniforms: uniforms,
  74425. samplers: samplers,
  74426. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  74427. };
  74428. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  74429. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  74430. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  74431. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  74432. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  74433. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  74434. if (states && states.functions) {
  74435. var functions = states.functions;
  74436. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  74437. shaderMaterial.backFaceCulling = false;
  74438. }
  74439. var blendFunc = functions.blendFuncSeparate;
  74440. if (blendFunc) {
  74441. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  74442. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  74443. }
  74444. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  74445. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  74446. }
  74447. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  74448. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  74449. }
  74450. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  74451. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  74452. }
  74453. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  74454. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  74455. }
  74456. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  74457. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  74458. }
  74459. }
  74460. }
  74461. };
  74462. return GLTFLoaderBase;
  74463. }());
  74464. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  74465. /**
  74466. * glTF V1 Loader
  74467. */
  74468. var GLTFLoader = (function () {
  74469. function GLTFLoader() {
  74470. }
  74471. GLTFLoader.RegisterExtension = function (extension) {
  74472. if (GLTFLoader.Extensions[extension.name]) {
  74473. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  74474. return;
  74475. }
  74476. GLTFLoader.Extensions[extension.name] = extension;
  74477. };
  74478. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  74479. var _this = this;
  74480. scene.useRightHandedSystem = true;
  74481. var gltfRuntime = GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  74482. gltfRuntime.importOnlyMeshes = true;
  74483. if (meshesNames === "") {
  74484. gltfRuntime.importMeshesNames = [];
  74485. }
  74486. else if (typeof meshesNames === "string") {
  74487. gltfRuntime.importMeshesNames = [meshesNames];
  74488. }
  74489. else if (meshesNames && !(meshesNames instanceof Array)) {
  74490. gltfRuntime.importMeshesNames = [meshesNames];
  74491. }
  74492. else {
  74493. gltfRuntime.importMeshesNames = [];
  74494. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  74495. }
  74496. // Create nodes
  74497. _this._createNodes(gltfRuntime);
  74498. var meshes = new Array();
  74499. var skeletons = new Array();
  74500. // Fill arrays of meshes and skeletons
  74501. for (var nde in gltfRuntime.nodes) {
  74502. var node = gltfRuntime.nodes[nde];
  74503. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  74504. meshes.push(node.babylonNode);
  74505. }
  74506. }
  74507. for (var skl in gltfRuntime.skins) {
  74508. var skin = gltfRuntime.skins[skl];
  74509. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  74510. skeletons.push(skin.babylonSkeleton);
  74511. }
  74512. }
  74513. // Load buffers, shaders, materials, etc.
  74514. _this._loadBuffersAsync(gltfRuntime, function () {
  74515. _this._loadShadersAsync(gltfRuntime, function () {
  74516. importMaterials(gltfRuntime);
  74517. postLoad(gltfRuntime);
  74518. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  74519. onSuccess(meshes, null, skeletons);
  74520. }
  74521. });
  74522. }, onProgress);
  74523. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  74524. onSuccess(meshes, null, skeletons);
  74525. }
  74526. }, onError);
  74527. return true;
  74528. };
  74529. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  74530. var _this = this;
  74531. scene.useRightHandedSystem = true;
  74532. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  74533. // Load runtime extensios
  74534. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  74535. // Create nodes
  74536. _this._createNodes(gltfRuntime);
  74537. // Load buffers, shaders, materials, etc.
  74538. _this._loadBuffersAsync(gltfRuntime, function () {
  74539. _this._loadShadersAsync(gltfRuntime, function () {
  74540. importMaterials(gltfRuntime);
  74541. postLoad(gltfRuntime);
  74542. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  74543. onSuccess();
  74544. }
  74545. });
  74546. });
  74547. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  74548. onSuccess();
  74549. }
  74550. }, onError);
  74551. }, onError);
  74552. };
  74553. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  74554. var hasShaders = false;
  74555. var processShader = function (sha, shader) {
  74556. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  74557. gltfRuntime.loadedShaderCount++;
  74558. if (shaderString) {
  74559. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  74560. }
  74561. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  74562. onload();
  74563. }
  74564. }, function () {
  74565. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  74566. });
  74567. };
  74568. for (var sha in gltfRuntime.shaders) {
  74569. hasShaders = true;
  74570. var shader = gltfRuntime.shaders[sha];
  74571. if (shader) {
  74572. processShader.bind(this, sha, shader)();
  74573. }
  74574. else {
  74575. BABYLON.Tools.Error("No shader named: " + sha);
  74576. }
  74577. }
  74578. if (!hasShaders) {
  74579. onload();
  74580. }
  74581. };
  74582. ;
  74583. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  74584. var hasBuffers = false;
  74585. var processBuffer = function (buf, buffer) {
  74586. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  74587. gltfRuntime.loadedBufferCount++;
  74588. if (bufferView) {
  74589. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  74590. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  74591. }
  74592. gltfRuntime.loadedBufferViews[buf] = bufferView;
  74593. }
  74594. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  74595. onLoad();
  74596. }
  74597. }, function () {
  74598. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  74599. });
  74600. };
  74601. for (var buf in gltfRuntime.buffers) {
  74602. hasBuffers = true;
  74603. var buffer = gltfRuntime.buffers[buf];
  74604. if (buffer) {
  74605. processBuffer.bind(this, buf, buffer)();
  74606. }
  74607. else {
  74608. BABYLON.Tools.Error("No buffer named: " + buf);
  74609. }
  74610. }
  74611. if (!hasBuffers) {
  74612. onLoad();
  74613. }
  74614. };
  74615. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  74616. var currentScene = gltfRuntime.currentScene;
  74617. if (currentScene) {
  74618. // Only one scene even if multiple scenes are defined
  74619. for (var i = 0; i < currentScene.nodes.length; i++) {
  74620. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  74621. }
  74622. }
  74623. else {
  74624. // Load all scenes
  74625. for (var thing in gltfRuntime.scenes) {
  74626. currentScene = gltfRuntime.scenes[thing];
  74627. for (var i = 0; i < currentScene.nodes.length; i++) {
  74628. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  74629. }
  74630. }
  74631. }
  74632. };
  74633. GLTFLoader.Extensions = {};
  74634. return GLTFLoader;
  74635. }());
  74636. GLTF1.GLTFLoader = GLTFLoader;
  74637. ;
  74638. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  74639. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  74640. })(BABYLON || (BABYLON = {}));
  74641. //# sourceMappingURL=babylon.glTFLoader.js.map
  74642. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74643. var BABYLON;
  74644. (function (BABYLON) {
  74645. var GLTF1;
  74646. (function (GLTF1) {
  74647. /**
  74648. * Utils functions for GLTF
  74649. */
  74650. var GLTFUtils = (function () {
  74651. function GLTFUtils() {
  74652. }
  74653. /**
  74654. * Sets the given "parameter" matrix
  74655. * @param scene: the {BABYLON.Scene} object
  74656. * @param source: the source node where to pick the matrix
  74657. * @param parameter: the GLTF technique parameter
  74658. * @param uniformName: the name of the shader's uniform
  74659. * @param shaderMaterial: the shader material
  74660. */
  74661. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  74662. var mat = null;
  74663. if (parameter.semantic === "MODEL") {
  74664. mat = source.getWorldMatrix();
  74665. }
  74666. else if (parameter.semantic === "PROJECTION") {
  74667. mat = scene.getProjectionMatrix();
  74668. }
  74669. else if (parameter.semantic === "VIEW") {
  74670. mat = scene.getViewMatrix();
  74671. }
  74672. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  74673. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  74674. }
  74675. else if (parameter.semantic === "MODELVIEW") {
  74676. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  74677. }
  74678. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  74679. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  74680. }
  74681. else if (parameter.semantic === "MODELINVERSE") {
  74682. mat = source.getWorldMatrix().invert();
  74683. }
  74684. else if (parameter.semantic === "VIEWINVERSE") {
  74685. mat = scene.getViewMatrix().invert();
  74686. }
  74687. else if (parameter.semantic === "PROJECTIONINVERSE") {
  74688. mat = scene.getProjectionMatrix().invert();
  74689. }
  74690. else if (parameter.semantic === "MODELVIEWINVERSE") {
  74691. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  74692. }
  74693. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  74694. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  74695. }
  74696. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  74697. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  74698. }
  74699. else {
  74700. debugger;
  74701. }
  74702. switch (parameter.type) {
  74703. case GLTF1.EParameterType.FLOAT_MAT2:
  74704. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  74705. break;
  74706. case GLTF1.EParameterType.FLOAT_MAT3:
  74707. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  74708. break;
  74709. case GLTF1.EParameterType.FLOAT_MAT4:
  74710. shaderMaterial.setMatrix(uniformName, mat);
  74711. break;
  74712. default: break;
  74713. }
  74714. };
  74715. /**
  74716. * Sets the given "parameter" matrix
  74717. * @param shaderMaterial: the shader material
  74718. * @param uniform: the name of the shader's uniform
  74719. * @param value: the value of the uniform
  74720. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  74721. */
  74722. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  74723. switch (type) {
  74724. case GLTF1.EParameterType.FLOAT:
  74725. shaderMaterial.setFloat(uniform, value);
  74726. return true;
  74727. case GLTF1.EParameterType.FLOAT_VEC2:
  74728. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  74729. return true;
  74730. case GLTF1.EParameterType.FLOAT_VEC3:
  74731. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  74732. return true;
  74733. case GLTF1.EParameterType.FLOAT_VEC4:
  74734. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  74735. return true;
  74736. default: return false;
  74737. }
  74738. };
  74739. /**
  74740. * If the uri is a base64 string
  74741. * @param uri: the uri to test
  74742. */
  74743. GLTFUtils.IsBase64 = function (uri) {
  74744. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  74745. };
  74746. /**
  74747. * Decode the base64 uri
  74748. * @param uri: the uri to decode
  74749. */
  74750. GLTFUtils.DecodeBase64 = function (uri) {
  74751. var decodedString = atob(uri.split(",")[1]);
  74752. var bufferLength = decodedString.length;
  74753. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  74754. for (var i = 0; i < bufferLength; i++) {
  74755. bufferView[i] = decodedString.charCodeAt(i);
  74756. }
  74757. return bufferView.buffer;
  74758. };
  74759. /**
  74760. * Returns the wrap mode of the texture
  74761. * @param mode: the mode value
  74762. */
  74763. GLTFUtils.GetWrapMode = function (mode) {
  74764. switch (mode) {
  74765. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  74766. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  74767. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  74768. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  74769. }
  74770. };
  74771. /**
  74772. * Returns the byte stride giving an accessor
  74773. * @param accessor: the GLTF accessor objet
  74774. */
  74775. GLTFUtils.GetByteStrideFromType = function (accessor) {
  74776. // Needs this function since "byteStride" isn't requiered in glTF format
  74777. var type = accessor.type;
  74778. switch (type) {
  74779. case "VEC2": return 2;
  74780. case "VEC3": return 3;
  74781. case "VEC4": return 4;
  74782. case "MAT2": return 4;
  74783. case "MAT3": return 9;
  74784. case "MAT4": return 16;
  74785. default: return 1;
  74786. }
  74787. };
  74788. /**
  74789. * Returns the texture filter mode giving a mode value
  74790. * @param mode: the filter mode value
  74791. */
  74792. GLTFUtils.GetTextureFilterMode = function (mode) {
  74793. switch (mode) {
  74794. case GLTF1.ETextureFilterType.LINEAR:
  74795. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  74796. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  74797. case GLTF1.ETextureFilterType.NEAREST:
  74798. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  74799. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  74800. }
  74801. };
  74802. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  74803. var byteOffset = bufferView.byteOffset + byteOffset;
  74804. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  74805. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  74806. throw new Error("Buffer access is out of range");
  74807. }
  74808. var buffer = loadedBufferView.buffer;
  74809. byteOffset += loadedBufferView.byteOffset;
  74810. switch (componentType) {
  74811. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  74812. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  74813. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  74814. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  74815. default: return new Float32Array(buffer, byteOffset, byteLength);
  74816. }
  74817. };
  74818. /**
  74819. * Returns a buffer from its accessor
  74820. * @param gltfRuntime: the GLTF runtime
  74821. * @param accessor: the GLTF accessor
  74822. */
  74823. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  74824. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  74825. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  74826. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  74827. };
  74828. /**
  74829. * Decodes a buffer view into a string
  74830. * @param view: the buffer view
  74831. */
  74832. GLTFUtils.DecodeBufferToText = function (view) {
  74833. var result = "";
  74834. var length = view.byteLength;
  74835. for (var i = 0; i < length; ++i) {
  74836. result += String.fromCharCode(view[i]);
  74837. }
  74838. return result;
  74839. };
  74840. /**
  74841. * Returns the default material of gltf. Related to
  74842. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  74843. * @param scene: the Babylon.js scene
  74844. */
  74845. GLTFUtils.GetDefaultMaterial = function (scene) {
  74846. if (!GLTFUtils._DefaultMaterial) {
  74847. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  74848. "precision highp float;",
  74849. "",
  74850. "uniform mat4 worldView;",
  74851. "uniform mat4 projection;",
  74852. "",
  74853. "attribute vec3 position;",
  74854. "",
  74855. "void main(void)",
  74856. "{",
  74857. " gl_Position = projection * worldView * vec4(position, 1.0);",
  74858. "}"
  74859. ].join("\n");
  74860. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  74861. "precision highp float;",
  74862. "",
  74863. "uniform vec4 u_emission;",
  74864. "",
  74865. "void main(void)",
  74866. "{",
  74867. " gl_FragColor = u_emission;",
  74868. "}"
  74869. ].join("\n");
  74870. var shaderPath = {
  74871. vertex: "GLTFDefaultMaterial",
  74872. fragment: "GLTFDefaultMaterial"
  74873. };
  74874. var options = {
  74875. attributes: ["position"],
  74876. uniforms: ["worldView", "projection", "u_emission"],
  74877. samplers: new Array(),
  74878. needAlphaBlending: false
  74879. };
  74880. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  74881. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  74882. }
  74883. return GLTFUtils._DefaultMaterial;
  74884. };
  74885. // The GLTF default material
  74886. GLTFUtils._DefaultMaterial = null;
  74887. return GLTFUtils;
  74888. }());
  74889. GLTF1.GLTFUtils = GLTFUtils;
  74890. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  74891. })(BABYLON || (BABYLON = {}));
  74892. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  74893. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  74894. var BABYLON;
  74895. (function (BABYLON) {
  74896. var GLTF1;
  74897. (function (GLTF1) {
  74898. var GLTFLoaderExtension = (function () {
  74899. function GLTFLoaderExtension(name) {
  74900. this._name = name;
  74901. }
  74902. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  74903. get: function () {
  74904. return this._name;
  74905. },
  74906. enumerable: true,
  74907. configurable: true
  74908. });
  74909. /**
  74910. * Defines an override for loading the runtime
  74911. * Return true to stop further extensions from loading the runtime
  74912. */
  74913. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  74914. return false;
  74915. };
  74916. /**
  74917. * Defines an onverride for creating gltf runtime
  74918. * Return true to stop further extensions from creating the runtime
  74919. */
  74920. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  74921. return false;
  74922. };
  74923. /**
  74924. * Defines an override for loading buffers
  74925. * Return true to stop further extensions from loading this buffer
  74926. */
  74927. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  74928. return false;
  74929. };
  74930. /**
  74931. * Defines an override for loading texture buffers
  74932. * Return true to stop further extensions from loading this texture data
  74933. */
  74934. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  74935. return false;
  74936. };
  74937. /**
  74938. * Defines an override for creating textures
  74939. * Return true to stop further extensions from loading this texture
  74940. */
  74941. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  74942. return false;
  74943. };
  74944. /**
  74945. * Defines an override for loading shader strings
  74946. * Return true to stop further extensions from loading this shader data
  74947. */
  74948. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  74949. return false;
  74950. };
  74951. /**
  74952. * Defines an override for loading materials
  74953. * Return true to stop further extensions from loading this material
  74954. */
  74955. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  74956. return false;
  74957. };
  74958. // ---------
  74959. // Utilities
  74960. // ---------
  74961. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  74962. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74963. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  74964. }, function () {
  74965. setTimeout(function () {
  74966. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  74967. });
  74968. });
  74969. };
  74970. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  74971. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74972. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  74973. }, function () {
  74974. setTimeout(function () {
  74975. onSuccess();
  74976. });
  74977. });
  74978. };
  74979. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  74980. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74981. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  74982. }, function () {
  74983. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  74984. });
  74985. };
  74986. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  74987. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  74988. };
  74989. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  74990. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74991. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  74992. }, function () {
  74993. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  74994. });
  74995. };
  74996. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  74997. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  74998. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  74999. }, function () {
  75000. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  75001. });
  75002. };
  75003. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  75004. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  75005. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  75006. }, function () {
  75007. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  75008. });
  75009. };
  75010. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  75011. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  75012. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  75013. }, function () {
  75014. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  75015. });
  75016. };
  75017. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  75018. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  75019. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  75020. if (func(loaderExtension)) {
  75021. return;
  75022. }
  75023. }
  75024. defaultFunc();
  75025. };
  75026. return GLTFLoaderExtension;
  75027. }());
  75028. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  75029. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  75030. })(BABYLON || (BABYLON = {}));
  75031. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  75032. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  75033. var BABYLON;
  75034. (function (BABYLON) {
  75035. var GLTF1;
  75036. (function (GLTF1) {
  75037. var BinaryExtensionBufferName = "binary_glTF";
  75038. var EContentFormat;
  75039. (function (EContentFormat) {
  75040. EContentFormat[EContentFormat["JSON"] = 0] = "JSON";
  75041. })(EContentFormat || (EContentFormat = {}));
  75042. ;
  75043. ;
  75044. ;
  75045. var GLTFBinaryExtension = (function (_super) {
  75046. __extends(GLTFBinaryExtension, _super);
  75047. function GLTFBinaryExtension() {
  75048. return _super.call(this, "KHR_binary_glTF") || this;
  75049. }
  75050. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  75051. var extensionsUsed = data.json.extensionsUsed;
  75052. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1) {
  75053. return false;
  75054. }
  75055. this._bin = data.bin;
  75056. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  75057. return true;
  75058. };
  75059. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  75060. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  75061. return false;
  75062. }
  75063. if (id !== BinaryExtensionBufferName) {
  75064. return false;
  75065. }
  75066. onSuccess(this._bin);
  75067. return true;
  75068. };
  75069. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  75070. var texture = gltfRuntime.textures[id];
  75071. var source = gltfRuntime.images[texture.source];
  75072. if (!source.extensions || !(this.name in source.extensions)) {
  75073. return false;
  75074. }
  75075. var sourceExt = source.extensions[this.name];
  75076. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  75077. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  75078. onSuccess(buffer);
  75079. return true;
  75080. };
  75081. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  75082. var shader = gltfRuntime.shaders[id];
  75083. if (!shader.extensions || !(this.name in shader.extensions)) {
  75084. return false;
  75085. }
  75086. var binaryExtensionShader = shader.extensions[this.name];
  75087. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  75088. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  75089. setTimeout(function () {
  75090. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  75091. onSuccess(shaderString);
  75092. });
  75093. return true;
  75094. };
  75095. return GLTFBinaryExtension;
  75096. }(GLTF1.GLTFLoaderExtension));
  75097. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  75098. var BinaryReader = (function () {
  75099. function BinaryReader(arrayBuffer) {
  75100. this._arrayBuffer = arrayBuffer;
  75101. this._dataView = new DataView(arrayBuffer);
  75102. this._byteOffset = 0;
  75103. }
  75104. BinaryReader.prototype.getUint32 = function () {
  75105. var value = this._dataView.getUint32(this._byteOffset, true);
  75106. this._byteOffset += 4;
  75107. return value;
  75108. };
  75109. BinaryReader.prototype.getUint8Array = function (length) {
  75110. if (!length) {
  75111. length = this._arrayBuffer.byteLength - this._byteOffset;
  75112. }
  75113. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  75114. this._byteOffset += length;
  75115. return value;
  75116. };
  75117. return BinaryReader;
  75118. }());
  75119. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  75120. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  75121. })(BABYLON || (BABYLON = {}));
  75122. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  75123. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  75124. var BABYLON;
  75125. (function (BABYLON) {
  75126. var GLTF1;
  75127. (function (GLTF1) {
  75128. ;
  75129. ;
  75130. ;
  75131. var GLTFMaterialsCommonExtension = (function (_super) {
  75132. __extends(GLTFMaterialsCommonExtension, _super);
  75133. function GLTFMaterialsCommonExtension() {
  75134. return _super.call(this, "KHR_materials_common") || this;
  75135. }
  75136. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  75137. if (!gltfRuntime.extensions)
  75138. return false;
  75139. var extension = gltfRuntime.extensions[this.name];
  75140. if (!extension)
  75141. return false;
  75142. // Create lights
  75143. var lights = extension.lights;
  75144. if (lights) {
  75145. for (var thing in lights) {
  75146. var light = lights[thing];
  75147. switch (light.type) {
  75148. case "ambient":
  75149. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  75150. var ambient = light.ambient;
  75151. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  75152. break;
  75153. case "point":
  75154. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  75155. var point = light.point;
  75156. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  75157. break;
  75158. case "directional":
  75159. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  75160. var directional = light.directional;
  75161. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  75162. break;
  75163. case "spot":
  75164. var spot = light.spot;
  75165. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), light.spot.fallOffAngle || Math.PI, light.spot.fallOffExponent || 0.0, gltfRuntime.scene);
  75166. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  75167. break;
  75168. default:
  75169. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  75170. break;
  75171. }
  75172. }
  75173. }
  75174. return false;
  75175. };
  75176. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  75177. var material = gltfRuntime.materials[id];
  75178. if (!material || !material.extensions)
  75179. return false;
  75180. var extension = material.extensions[this.name];
  75181. if (!extension)
  75182. return false;
  75183. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  75184. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  75185. if (extension.technique === "CONSTANT") {
  75186. standardMaterial.disableLighting = true;
  75187. }
  75188. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  75189. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  75190. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  75191. // Ambient
  75192. if (typeof extension.values.ambient === "string") {
  75193. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  75194. }
  75195. else {
  75196. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  75197. }
  75198. // Diffuse
  75199. if (typeof extension.values.diffuse === "string") {
  75200. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  75201. }
  75202. else {
  75203. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  75204. }
  75205. // Emission
  75206. if (typeof extension.values.emission === "string") {
  75207. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  75208. }
  75209. else {
  75210. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  75211. }
  75212. // Specular
  75213. if (typeof extension.values.specular === "string") {
  75214. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  75215. }
  75216. else {
  75217. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  75218. }
  75219. return true;
  75220. };
  75221. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  75222. // Create buffer from texture url
  75223. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  75224. // Create texture from buffer
  75225. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  75226. }, onError);
  75227. };
  75228. return GLTFMaterialsCommonExtension;
  75229. }(GLTF1.GLTFLoaderExtension));
  75230. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  75231. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  75232. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  75233. })(BABYLON || (BABYLON = {}));
  75234. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  75235. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  75236. var BABYLON;
  75237. (function (BABYLON) {
  75238. var GLTF2;
  75239. (function (GLTF2) {
  75240. /**
  75241. * Enums
  75242. */
  75243. var EComponentType;
  75244. (function (EComponentType) {
  75245. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  75246. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  75247. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  75248. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  75249. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  75250. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  75251. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  75252. var EMeshPrimitiveMode;
  75253. (function (EMeshPrimitiveMode) {
  75254. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  75255. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  75256. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  75257. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  75258. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  75259. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  75260. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  75261. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  75262. var ETextureMagFilter;
  75263. (function (ETextureMagFilter) {
  75264. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  75265. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  75266. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  75267. var ETextureMinFilter;
  75268. (function (ETextureMinFilter) {
  75269. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  75270. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  75271. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  75272. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  75273. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  75274. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  75275. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  75276. var ETextureWrapMode;
  75277. (function (ETextureWrapMode) {
  75278. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  75279. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  75280. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  75281. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  75282. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  75283. })(BABYLON || (BABYLON = {}));
  75284. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  75285. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  75286. var BABYLON;
  75287. (function (BABYLON) {
  75288. var GLTF2;
  75289. (function (GLTF2) {
  75290. var GLTFLoaderTracker = (function () {
  75291. function GLTFLoaderTracker(onComplete) {
  75292. this._pendingCount = 0;
  75293. this._callback = onComplete;
  75294. }
  75295. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  75296. this._pendingCount++;
  75297. };
  75298. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  75299. if (--this._pendingCount === 0) {
  75300. this._callback();
  75301. }
  75302. };
  75303. return GLTFLoaderTracker;
  75304. }());
  75305. var GLTFLoader = (function () {
  75306. function GLTFLoader(parent) {
  75307. this._renderReady = false;
  75308. this._disposed = false;
  75309. this._renderReadyObservable = new BABYLON.Observable();
  75310. // Count of pending work that needs to complete before the asset is rendered.
  75311. this._renderPendingCount = 0;
  75312. // Count of pending work that needs to complete before the loader is disposed.
  75313. this._loaderPendingCount = 0;
  75314. this._loaderTrackers = new Array();
  75315. this._parent = parent;
  75316. }
  75317. GLTFLoader.RegisterExtension = function (extension) {
  75318. if (GLTFLoader.Extensions[extension.name]) {
  75319. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  75320. return;
  75321. }
  75322. GLTFLoader.Extensions[extension.name] = extension;
  75323. // Keep the order of registration so that extensions registered first are called first.
  75324. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  75325. };
  75326. GLTFLoader.prototype.dispose = function () {
  75327. if (this._disposed) {
  75328. return;
  75329. }
  75330. this._disposed = true;
  75331. // Revoke object urls created during load
  75332. if (this._gltf.textures) {
  75333. this._gltf.textures.forEach(function (texture) {
  75334. if (texture.url) {
  75335. URL.revokeObjectURL(texture.url);
  75336. }
  75337. });
  75338. }
  75339. this._gltf = undefined;
  75340. this._babylonScene = undefined;
  75341. this._rootUrl = undefined;
  75342. this._defaultMaterial = undefined;
  75343. this._successCallback = undefined;
  75344. this._errorCallback = undefined;
  75345. this._renderReady = false;
  75346. this._renderReadyObservable.clear();
  75347. this._renderPendingCount = 0;
  75348. this._loaderPendingCount = 0;
  75349. };
  75350. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  75351. var _this = this;
  75352. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  75353. onSuccess(_this._getMeshes(), null, _this._getSkeletons());
  75354. }, onProgress, onError);
  75355. };
  75356. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  75357. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  75358. };
  75359. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  75360. var _this = this;
  75361. this._tryCatchOnError(function () {
  75362. _this._loadData(data);
  75363. _this._babylonScene = scene;
  75364. _this._rootUrl = rootUrl;
  75365. _this._successCallback = onSuccess;
  75366. _this._progressCallback = onProgress;
  75367. _this._errorCallback = onError;
  75368. GLTF2.GLTFUtils.AssignIndices(_this._gltf.accessors);
  75369. GLTF2.GLTFUtils.AssignIndices(_this._gltf.animations);
  75370. GLTF2.GLTFUtils.AssignIndices(_this._gltf.buffers);
  75371. GLTF2.GLTFUtils.AssignIndices(_this._gltf.bufferViews);
  75372. GLTF2.GLTFUtils.AssignIndices(_this._gltf.images);
  75373. GLTF2.GLTFUtils.AssignIndices(_this._gltf.materials);
  75374. GLTF2.GLTFUtils.AssignIndices(_this._gltf.meshes);
  75375. GLTF2.GLTFUtils.AssignIndices(_this._gltf.nodes);
  75376. GLTF2.GLTFUtils.AssignIndices(_this._gltf.scenes);
  75377. GLTF2.GLTFUtils.AssignIndices(_this._gltf.skins);
  75378. GLTF2.GLTFUtils.AssignIndices(_this._gltf.textures);
  75379. _this._addPendingData(_this);
  75380. _this._loadDefaultScene(nodeNames);
  75381. _this._loadAnimations();
  75382. _this._removePendingData(_this);
  75383. });
  75384. };
  75385. GLTFLoader.prototype._onError = function (message) {
  75386. if (this._disposed) {
  75387. return;
  75388. }
  75389. BABYLON.Tools.Error("glTF Loader: " + message);
  75390. if (this._errorCallback) {
  75391. this._errorCallback(message);
  75392. }
  75393. this.dispose();
  75394. };
  75395. GLTFLoader.prototype._onProgress = function (event) {
  75396. if (this._disposed) {
  75397. return;
  75398. }
  75399. if (this._progressCallback) {
  75400. this._progressCallback(event);
  75401. }
  75402. };
  75403. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  75404. if (this._renderReady) {
  75405. func();
  75406. }
  75407. else {
  75408. this._renderReadyObservable.add(func);
  75409. }
  75410. };
  75411. GLTFLoader.prototype._onRenderReady = function () {
  75412. this._rootNode.babylonMesh.setEnabled(true);
  75413. this._startAnimations();
  75414. this._successCallback();
  75415. this._renderReadyObservable.notifyObservers(this);
  75416. if (this._parent.onReady) {
  75417. this._parent.onReady();
  75418. }
  75419. };
  75420. GLTFLoader.prototype._onComplete = function () {
  75421. if (this._parent.onComplete) {
  75422. this._parent.onComplete();
  75423. }
  75424. this.dispose();
  75425. };
  75426. GLTFLoader.prototype._loadData = function (data) {
  75427. this._gltf = data.json;
  75428. if (data.bin) {
  75429. var buffers = this._gltf.buffers;
  75430. if (buffers && buffers[0] && !buffers[0].uri) {
  75431. var binaryBuffer = buffers[0];
  75432. if (binaryBuffer.byteLength != data.bin.byteLength) {
  75433. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  75434. }
  75435. binaryBuffer.loadedData = data.bin;
  75436. }
  75437. else {
  75438. BABYLON.Tools.Warn("Unexpected BIN chunk");
  75439. }
  75440. }
  75441. };
  75442. GLTFLoader.prototype._getMeshes = function () {
  75443. var meshes = [this._rootNode.babylonMesh];
  75444. var nodes = this._gltf.nodes;
  75445. if (nodes) {
  75446. nodes.forEach(function (node) {
  75447. if (node.babylonMesh) {
  75448. meshes.push(node.babylonMesh);
  75449. }
  75450. });
  75451. }
  75452. return meshes;
  75453. };
  75454. GLTFLoader.prototype._getSkeletons = function () {
  75455. var skeletons = new Array();
  75456. var skins = this._gltf.skins;
  75457. if (skins) {
  75458. skins.forEach(function (skin) {
  75459. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  75460. skeletons.push(skin.babylonSkeleton);
  75461. }
  75462. });
  75463. }
  75464. return skeletons;
  75465. };
  75466. GLTFLoader.prototype._getAnimationTargets = function () {
  75467. var targets = new Array();
  75468. var animations = this._gltf.animations;
  75469. if (animations) {
  75470. animations.forEach(function (animation) {
  75471. targets.push.apply(targets, animation.targets);
  75472. });
  75473. }
  75474. return targets;
  75475. };
  75476. GLTFLoader.prototype._startAnimations = function () {
  75477. var _this = this;
  75478. this._getAnimationTargets().forEach(function (target) { return _this._babylonScene.beginAnimation(target, 0, Number.MAX_VALUE, true); });
  75479. };
  75480. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  75481. var scene = GLTF2.GLTFUtils.GetArrayItem(this._gltf.scenes, this._gltf.scene || 0);
  75482. if (!scene) {
  75483. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  75484. }
  75485. this._loadScene("scenes[" + scene.index + "]", scene, nodeNames);
  75486. };
  75487. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  75488. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  75489. switch (this._parent.coordinateSystemMode) {
  75490. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO:
  75491. if (!this._babylonScene.useRightHandedSystem) {
  75492. this._rootNode.babylonMesh.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  75493. this._rootNode.babylonMesh.scaling = new BABYLON.Vector3(1, 1, -1);
  75494. }
  75495. break;
  75496. case BABYLON.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:
  75497. // do nothing
  75498. break;
  75499. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:
  75500. this._babylonScene.useRightHandedSystem = true;
  75501. break;
  75502. default:
  75503. BABYLON.Tools.Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  75504. return;
  75505. }
  75506. var nodeIndices = scene.nodes;
  75507. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  75508. node.parent = parentNode;
  75509. return true;
  75510. }, this._rootNode);
  75511. if (nodeNames) {
  75512. if (!(nodeNames instanceof Array)) {
  75513. nodeNames = [nodeNames];
  75514. }
  75515. var filteredNodeIndices = new Array();
  75516. this._traverseNodes(context, nodeIndices, function (node) {
  75517. if (nodeNames.indexOf(node.name) !== -1) {
  75518. filteredNodeIndices.push(node.index);
  75519. return false;
  75520. }
  75521. return true;
  75522. }, this._rootNode);
  75523. nodeIndices = filteredNodeIndices;
  75524. }
  75525. for (var i = 0; i < nodeIndices.length; i++) {
  75526. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, nodeIndices[i]);
  75527. if (!node) {
  75528. throw new Error(context + ": Failed to find node " + nodeIndices[i]);
  75529. }
  75530. this._loadNode("nodes[" + nodeIndices[i] + "]", node);
  75531. }
  75532. // Disable the root mesh until the asset is ready to render.
  75533. this._rootNode.babylonMesh.setEnabled(false);
  75534. };
  75535. GLTFLoader.prototype._loadNode = function (context, node) {
  75536. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  75537. return;
  75538. }
  75539. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  75540. this._loadTransform(node);
  75541. if (node.mesh != null) {
  75542. var mesh = GLTF2.GLTFUtils.GetArrayItem(this._gltf.meshes, node.mesh);
  75543. if (!mesh) {
  75544. throw new Error(context + ": Failed to find mesh " + node.mesh);
  75545. }
  75546. this._loadMesh("meshes[" + node.mesh + "]", node, mesh);
  75547. }
  75548. node.babylonMesh.parent = node.parent ? node.parent.babylonMesh : null;
  75549. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  75550. node.babylonAnimationTargets.push(node.babylonMesh);
  75551. if (node.skin != null) {
  75552. var skin = GLTF2.GLTFUtils.GetArrayItem(this._gltf.skins, node.skin);
  75553. if (!skin) {
  75554. throw new Error(context + ": Failed to find skin " + node.skin);
  75555. }
  75556. node.babylonMesh.skeleton = this._loadSkin("skins[" + node.skin + "]", skin);
  75557. }
  75558. if (node.camera != null) {
  75559. // TODO: handle cameras
  75560. }
  75561. if (node.children) {
  75562. for (var i = 0; i < node.children.length; i++) {
  75563. var childNode = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, node.children[i]);
  75564. if (!childNode) {
  75565. throw new Error(context + ": Failed to find child node " + node.children[i]);
  75566. }
  75567. this._loadNode("nodes[" + node.children[i] + "]", childNode);
  75568. }
  75569. }
  75570. };
  75571. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  75572. node.babylonMesh.name = mesh.name || node.babylonMesh.name;
  75573. var babylonMultiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  75574. node.babylonMesh.material = babylonMultiMaterial;
  75575. var geometry = new BABYLON.Geometry(node.babylonMesh.name, this._babylonScene, null, false, node.babylonMesh);
  75576. var vertexData = new BABYLON.VertexData();
  75577. vertexData.positions = [];
  75578. vertexData.indices = [];
  75579. var subMeshInfos = [];
  75580. var numRemainingPrimitives = mesh.primitives.length;
  75581. for (var index = 0; index < mesh.primitives.length; index++) {
  75582. var primitive = mesh.primitives[index];
  75583. this._loadPrimitive(context + "/primitives[" + index + "]", node, mesh, primitive, function (subVertexData, loadMaterial) {
  75584. subMeshInfos.push({
  75585. verticesStart: vertexData.positions.length,
  75586. verticesCount: subVertexData.positions.length,
  75587. indicesStart: vertexData.indices.length,
  75588. indicesCount: subVertexData.indices.length,
  75589. loadMaterial: loadMaterial
  75590. });
  75591. vertexData.merge(subVertexData);
  75592. if (--numRemainingPrimitives === 0) {
  75593. geometry.setAllVerticesData(vertexData, false);
  75594. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  75595. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  75596. node.babylonMesh.subMeshes = [];
  75597. for (var index = 0; index < subMeshInfos.length; index++) {
  75598. var info = subMeshInfos[index];
  75599. new BABYLON.SubMesh(index, info.verticesStart, info.verticesCount, info.indicesStart, info.indicesCount, node.babylonMesh);
  75600. info.loadMaterial(index);
  75601. }
  75602. }
  75603. });
  75604. }
  75605. };
  75606. GLTFLoader.prototype._loadPrimitive = function (context, node, mesh, primitive, onSuccess) {
  75607. var _this = this;
  75608. var subMaterials = node.babylonMesh.material.subMaterials;
  75609. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  75610. // TODO: handle other primitive modes
  75611. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  75612. }
  75613. this._createMorphTargets(node, mesh, primitive);
  75614. this._loadVertexDataAsync(context, mesh, primitive, function (vertexData) {
  75615. _this._loadMorphTargetsData(context, mesh, primitive, vertexData, node.babylonMesh);
  75616. var loadMaterial = function (index) {
  75617. if (primitive.material == null) {
  75618. subMaterials[index] = _this._getDefaultMaterial();
  75619. }
  75620. else {
  75621. var material = GLTF2.GLTFUtils.GetArrayItem(_this._gltf.materials, primitive.material);
  75622. if (!material) {
  75623. throw new Error(context + ": Failed to find material " + primitive.material);
  75624. }
  75625. _this._loadMaterial("materials[" + material.index + "]", material, function (babylonMaterial, isNew) {
  75626. if (isNew && _this._parent.onMaterialLoaded) {
  75627. _this._parent.onMaterialLoaded(babylonMaterial);
  75628. }
  75629. if (_this._parent.onBeforeMaterialReadyAsync) {
  75630. _this._addLoaderPendingData(material);
  75631. _this._parent.onBeforeMaterialReadyAsync(babylonMaterial, node.babylonMesh, subMaterials[index] != null, function () {
  75632. subMaterials[index] = babylonMaterial;
  75633. _this._removeLoaderPendingData(material);
  75634. });
  75635. }
  75636. else {
  75637. subMaterials[index] = babylonMaterial;
  75638. }
  75639. });
  75640. }
  75641. };
  75642. onSuccess(vertexData, loadMaterial);
  75643. });
  75644. };
  75645. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  75646. var _this = this;
  75647. var attributes = primitive.attributes;
  75648. if (!attributes) {
  75649. throw new Error(context + ": Attributes are missing");
  75650. }
  75651. var vertexData = new BABYLON.VertexData();
  75652. var numRemainingAttributes = Object.keys(attributes).length;
  75653. var _loop_1 = function (attribute) {
  75654. accessor = GLTF2.GLTFUtils.GetArrayItem(this_1._gltf.accessors, attributes[attribute]);
  75655. if (!accessor) {
  75656. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  75657. }
  75658. this_1._loadAccessorAsync("accessors[" + accessor.index + "]", accessor, function (data) {
  75659. switch (attribute) {
  75660. case "NORMAL":
  75661. vertexData.normals = data;
  75662. break;
  75663. case "POSITION":
  75664. vertexData.positions = data;
  75665. break;
  75666. case "TANGENT":
  75667. vertexData.tangents = data;
  75668. break;
  75669. case "TEXCOORD_0":
  75670. vertexData.uvs = data;
  75671. break;
  75672. case "TEXCOORD_1":
  75673. vertexData.uvs2 = data;
  75674. break;
  75675. case "JOINTS_0":
  75676. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  75677. break;
  75678. case "WEIGHTS_0":
  75679. vertexData.matricesWeights = data;
  75680. break;
  75681. case "COLOR_0":
  75682. vertexData.colors = data;
  75683. break;
  75684. default:
  75685. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  75686. break;
  75687. }
  75688. if (--numRemainingAttributes === 0) {
  75689. if (primitive.indices == null) {
  75690. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  75691. vertexData.indices.forEach(function (v, i) { return vertexData.indices[i] = i; });
  75692. onSuccess(vertexData);
  75693. }
  75694. else {
  75695. var indicesAccessor = GLTF2.GLTFUtils.GetArrayItem(_this._gltf.accessors, primitive.indices);
  75696. if (!indicesAccessor) {
  75697. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  75698. }
  75699. _this._loadAccessorAsync("accessors[" + indicesAccessor.index + "]", indicesAccessor, function (data) {
  75700. vertexData.indices = data;
  75701. onSuccess(vertexData);
  75702. });
  75703. }
  75704. }
  75705. });
  75706. };
  75707. var this_1 = this, accessor;
  75708. for (var attribute in attributes) {
  75709. _loop_1(attribute);
  75710. }
  75711. };
  75712. GLTFLoader.prototype._createMorphTargets = function (node, mesh, primitive) {
  75713. var targets = primitive.targets;
  75714. if (!targets) {
  75715. return;
  75716. }
  75717. if (!node.babylonMesh.morphTargetManager) {
  75718. node.babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  75719. }
  75720. for (var index = 0; index < targets.length; index++) {
  75721. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  75722. node.babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  75723. }
  75724. };
  75725. GLTFLoader.prototype._loadMorphTargetsData = function (context, mesh, primitive, vertexData, babylonMesh) {
  75726. var targets = primitive.targets;
  75727. if (!targets) {
  75728. return;
  75729. }
  75730. var _loop_2 = function () {
  75731. var babylonMorphTarget = babylonMesh.morphTargetManager.getTarget(index);
  75732. attributes = targets[index];
  75733. var _loop_3 = function (attribute) {
  75734. accessor = GLTF2.GLTFUtils.GetArrayItem(this_2._gltf.accessors, attributes[attribute]);
  75735. if (!accessor) {
  75736. throw new Error(context + "/targets[" + index + "]: Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  75737. }
  75738. this_2._loadAccessorAsync("accessors[" + accessor.index + "]", accessor, function (data) {
  75739. if (accessor.name) {
  75740. babylonMorphTarget.name = accessor.name;
  75741. }
  75742. // glTF stores morph target information as deltas while babylon.js expects the final data.
  75743. // As a result we have to add the original data to the delta to calculate the final data.
  75744. var values = data;
  75745. switch (attribute) {
  75746. case "NORMAL":
  75747. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.normals[i]; });
  75748. babylonMorphTarget.setNormals(values);
  75749. break;
  75750. case "POSITION":
  75751. GLTF2.GLTFUtils.ForEach(values, function (v, i) { return values[i] += vertexData.positions[i]; });
  75752. babylonMorphTarget.setPositions(values);
  75753. break;
  75754. case "TANGENT":
  75755. // Tangent data for morph targets is stored as xyz delta.
  75756. // The vertexData.tangent is stored as xyzw.
  75757. // So we need to skip every fourth vertexData.tangent.
  75758. for (var i = 0, j = 0; i < values.length; i++, j++) {
  75759. values[i] += vertexData.tangents[j];
  75760. if ((i + 1) % 3 == 0) {
  75761. j++;
  75762. }
  75763. }
  75764. babylonMorphTarget.setTangents(values);
  75765. break;
  75766. default:
  75767. BABYLON.Tools.Warn("Ignoring unrecognized attribute '" + attribute + "'");
  75768. break;
  75769. }
  75770. });
  75771. };
  75772. for (var attribute in attributes) {
  75773. _loop_3(attribute);
  75774. }
  75775. };
  75776. var this_2 = this, attributes, accessor;
  75777. for (var index = 0; index < targets.length; index++) {
  75778. _loop_2();
  75779. }
  75780. };
  75781. GLTFLoader.prototype._loadTransform = function (node) {
  75782. var position = BABYLON.Vector3.Zero();
  75783. var rotation = BABYLON.Quaternion.Identity();
  75784. var scaling = BABYLON.Vector3.One();
  75785. if (node.matrix) {
  75786. var mat = BABYLON.Matrix.FromArray(node.matrix);
  75787. mat.decompose(scaling, rotation, position);
  75788. }
  75789. else {
  75790. if (node.translation)
  75791. position = BABYLON.Vector3.FromArray(node.translation);
  75792. if (node.rotation)
  75793. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  75794. if (node.scale)
  75795. scaling = BABYLON.Vector3.FromArray(node.scale);
  75796. }
  75797. node.babylonMesh.position = position;
  75798. node.babylonMesh.rotationQuaternion = rotation;
  75799. node.babylonMesh.scaling = scaling;
  75800. };
  75801. GLTFLoader.prototype._loadSkin = function (context, skin) {
  75802. var _this = this;
  75803. var skeletonId = "skeleton" + skin.index;
  75804. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  75805. if (skin.inverseBindMatrices == null) {
  75806. this._loadBones(context, skin, null);
  75807. }
  75808. else {
  75809. var accessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, skin.inverseBindMatrices);
  75810. if (!accessor) {
  75811. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  75812. }
  75813. this._loadAccessorAsync("accessors[" + accessor.index + "]", accessor, function (data) {
  75814. _this._loadBones(context, skin, data);
  75815. });
  75816. }
  75817. return skin.babylonSkeleton;
  75818. };
  75819. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  75820. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  75821. node.babylonBones = node.babylonBones || {};
  75822. node.babylonBones[skin.index] = babylonBone;
  75823. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  75824. node.babylonAnimationTargets.push(babylonBone);
  75825. return babylonBone;
  75826. };
  75827. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  75828. var babylonBones = {};
  75829. for (var i = 0; i < skin.joints.length; i++) {
  75830. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, skin.joints[i]);
  75831. if (!node) {
  75832. throw new Error(context + ": Failed to find joint " + skin.joints[i]);
  75833. }
  75834. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  75835. }
  75836. };
  75837. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  75838. var babylonBone = babylonBones[node.index];
  75839. if (babylonBone) {
  75840. return babylonBone;
  75841. }
  75842. var boneIndex = skin.joints.indexOf(node.index);
  75843. var baseMatrix = BABYLON.Matrix.Identity();
  75844. if (inverseBindMatrixData && boneIndex !== -1) {
  75845. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  75846. baseMatrix.invertToRef(baseMatrix);
  75847. }
  75848. var babylonParentBone;
  75849. if (node.index !== skin.skeleton && node.parent !== this._rootNode) {
  75850. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  75851. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  75852. }
  75853. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  75854. babylonBones[node.index] = babylonBone;
  75855. return babylonBone;
  75856. };
  75857. GLTFLoader.prototype._getNodeMatrix = function (node) {
  75858. return node.matrix ?
  75859. BABYLON.Matrix.FromArray(node.matrix) :
  75860. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  75861. };
  75862. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  75863. if (parentNode === void 0) { parentNode = null; }
  75864. for (var i = 0; i < indices.length; i++) {
  75865. var node = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, indices[i]);
  75866. if (!node) {
  75867. throw new Error(context + ": Failed to find node " + indices[i]);
  75868. }
  75869. this._traverseNode(context, node, action, parentNode);
  75870. }
  75871. };
  75872. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  75873. if (parentNode === void 0) { parentNode = null; }
  75874. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  75875. return;
  75876. }
  75877. if (!action(node, parentNode)) {
  75878. return;
  75879. }
  75880. if (node.children) {
  75881. this._traverseNodes(context, node.children, action, node);
  75882. }
  75883. };
  75884. GLTFLoader.prototype._loadAnimations = function () {
  75885. var animations = this._gltf.animations;
  75886. if (!animations) {
  75887. return;
  75888. }
  75889. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  75890. var animation = animations[animationIndex];
  75891. var context = "animations[" + animationIndex + "]";
  75892. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  75893. var channel = GLTF2.GLTFUtils.GetArrayItem(animation.channels, channelIndex);
  75894. if (!channel) {
  75895. throw new Error(context + ": Failed to find channel " + channelIndex);
  75896. }
  75897. var sampler = GLTF2.GLTFUtils.GetArrayItem(animation.samplers, channel.sampler);
  75898. if (!sampler) {
  75899. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  75900. }
  75901. this._loadAnimationChannel(animation, context + "/channels[" + channelIndex + "]", channel, context + "/samplers[" + channel.sampler + "]", sampler);
  75902. }
  75903. }
  75904. };
  75905. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  75906. var targetNode = GLTF2.GLTFUtils.GetArrayItem(this._gltf.nodes, channel.target.node);
  75907. if (!targetNode) {
  75908. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  75909. }
  75910. var conversion = {
  75911. "translation": "position",
  75912. "rotation": "rotationQuaternion",
  75913. "scale": "scaling",
  75914. "weights": "influence"
  75915. };
  75916. var targetPath = conversion[channel.target.path];
  75917. if (!targetPath) {
  75918. throw new Error(channelContext + ": Invalid target path '" + channel.target.path + "'");
  75919. }
  75920. var animationConvertion = {
  75921. "position": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  75922. "rotationQuaternion": BABYLON.Animation.ANIMATIONTYPE_QUATERNION,
  75923. "scaling": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  75924. "influence": BABYLON.Animation.ANIMATIONTYPE_FLOAT,
  75925. };
  75926. var animationType = animationConvertion[targetPath];
  75927. var inputData;
  75928. var outputData;
  75929. var checkSuccess = function () {
  75930. if (!inputData || !outputData) {
  75931. return;
  75932. }
  75933. var outputBufferOffset = 0;
  75934. var nextOutputConversion = {
  75935. "position": function () {
  75936. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  75937. outputBufferOffset += 3;
  75938. return value;
  75939. },
  75940. "rotationQuaternion": function () {
  75941. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  75942. outputBufferOffset += 4;
  75943. return value;
  75944. },
  75945. "scaling": function () {
  75946. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  75947. outputBufferOffset += 3;
  75948. return value;
  75949. },
  75950. "influence": function () {
  75951. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  75952. var value = new Array(numTargets);
  75953. for (var i = 0; i < numTargets; i++) {
  75954. value[i] = outputData[outputBufferOffset++];
  75955. }
  75956. return value;
  75957. },
  75958. };
  75959. var getNextOutputValue = nextOutputConversion[targetPath];
  75960. var nextKeyConversion = {
  75961. "LINEAR": function (frameIndex) { return ({
  75962. frame: inputData[frameIndex],
  75963. value: getNextOutputValue()
  75964. }); },
  75965. "CUBICSPLINE": function (frameIndex) { return ({
  75966. frame: inputData[frameIndex],
  75967. inTangent: getNextOutputValue(),
  75968. value: getNextOutputValue(),
  75969. outTangent: getNextOutputValue()
  75970. }); },
  75971. };
  75972. var getNextKey = nextKeyConversion[sampler.interpolation];
  75973. if (!getNextKey) {
  75974. throw new Error(samplerContext + ": Invalid interpolation '" + sampler.interpolation + "'");
  75975. }
  75976. var keys = new Array(inputData.length);
  75977. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  75978. keys[frameIndex] = getNextKey(frameIndex);
  75979. }
  75980. animation.targets = animation.targets || [];
  75981. if (targetPath === "influence") {
  75982. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  75983. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  75984. var morphTarget = morphTargetManager.getTarget(targetIndex);
  75985. var animationName = (animation.name || "anim" + animation.index) + "_" + targetIndex;
  75986. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  75987. babylonAnimation.setKeys(keys.map(function (key) { return ({
  75988. frame: key.frame,
  75989. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  75990. value: key.value[targetIndex],
  75991. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  75992. }); }));
  75993. morphTarget.animations.push(babylonAnimation);
  75994. animation.targets.push(morphTarget);
  75995. }
  75996. }
  75997. else {
  75998. var animationName = animation.name || "anim" + animation.index;
  75999. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  76000. babylonAnimation.setKeys(keys);
  76001. for (var i = 0; i < targetNode.babylonAnimationTargets.length; i++) {
  76002. var target = targetNode.babylonAnimationTargets[i];
  76003. target.animations.push(babylonAnimation.clone());
  76004. animation.targets.push(target);
  76005. }
  76006. }
  76007. };
  76008. var inputAccessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, sampler.input);
  76009. if (!inputAccessor) {
  76010. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  76011. }
  76012. this._loadAccessorAsync("accessors[" + inputAccessor.index + "]", inputAccessor, function (data) {
  76013. inputData = data;
  76014. checkSuccess();
  76015. });
  76016. var outputAccessor = GLTF2.GLTFUtils.GetArrayItem(this._gltf.accessors, sampler.output);
  76017. if (!outputAccessor) {
  76018. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  76019. }
  76020. this._loadAccessorAsync("accessors[" + outputAccessor.index + "]", outputAccessor, function (data) {
  76021. outputData = data;
  76022. checkSuccess();
  76023. });
  76024. };
  76025. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  76026. var _this = this;
  76027. this._addPendingData(buffer);
  76028. if (buffer.loadedData) {
  76029. onSuccess(buffer.loadedData);
  76030. this._removePendingData(buffer);
  76031. }
  76032. else if (buffer.loadedObservable) {
  76033. buffer.loadedObservable.add(function (buffer) {
  76034. onSuccess(buffer.loadedData);
  76035. _this._removePendingData(buffer);
  76036. });
  76037. }
  76038. else {
  76039. if (!buffer.uri) {
  76040. throw new Error(context + ": Uri is missing");
  76041. }
  76042. if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  76043. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  76044. buffer.loadedData = new Uint8Array(data);
  76045. onSuccess(buffer.loadedData);
  76046. this._removePendingData(buffer);
  76047. }
  76048. else {
  76049. if (!GLTF2.GLTFUtils.ValidateUri(buffer.uri)) {
  76050. throw new Error(context + ": Uri '" + buffer.uri + "' is invalid");
  76051. }
  76052. buffer.loadedObservable = new BABYLON.Observable();
  76053. buffer.loadedObservable.add(function (buffer) {
  76054. onSuccess(buffer.loadedData);
  76055. _this._removePendingData(buffer);
  76056. });
  76057. BABYLON.Tools.LoadFile(this._rootUrl + buffer.uri, function (data) {
  76058. _this._tryCatchOnError(function () {
  76059. buffer.loadedData = new Uint8Array(data);
  76060. buffer.loadedObservable.notifyObservers(buffer);
  76061. buffer.loadedObservable = null;
  76062. });
  76063. }, function (event) {
  76064. _this._tryCatchOnError(function () {
  76065. _this._onProgress(event);
  76066. });
  76067. }, this._babylonScene.database, true, function (request) {
  76068. _this._tryCatchOnError(function () {
  76069. throw new Error(context + ": Failed to load '" + buffer.uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  76070. });
  76071. });
  76072. }
  76073. }
  76074. };
  76075. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  76076. var _this = this;
  76077. var buffer = GLTF2.GLTFUtils.GetArrayItem(this._gltf.buffers, bufferView.buffer);
  76078. if (!buffer) {
  76079. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  76080. }
  76081. this._loadBufferAsync("buffers[" + buffer.index + "]", buffer, function (bufferData) {
  76082. if (_this._disposed) {
  76083. return;
  76084. }
  76085. try {
  76086. var data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  76087. }
  76088. catch (e) {
  76089. throw new Error(context + ": " + e.message);
  76090. }
  76091. onSuccess(data);
  76092. });
  76093. };
  76094. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  76095. var _this = this;
  76096. if (accessor.sparse) {
  76097. throw new Error(context + ": Sparse accessors are not currently supported");
  76098. }
  76099. if (accessor.normalized) {
  76100. throw new Error(context + ": Normalized accessors are not currently supported");
  76101. }
  76102. var bufferView = GLTF2.GLTFUtils.GetArrayItem(this._gltf.bufferViews, accessor.bufferView);
  76103. if (!bufferView) {
  76104. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  76105. }
  76106. this._loadBufferViewAsync("bufferViews[" + bufferView.index + "]", bufferView, function (bufferViewData) {
  76107. var numComponents = _this._getNumComponentsOfType(accessor.type);
  76108. if (numComponents === 0) {
  76109. throw new Error(context + ": Invalid type (" + accessor.type + ")");
  76110. }
  76111. var data;
  76112. switch (accessor.componentType) {
  76113. case GLTF2.EComponentType.BYTE:
  76114. data = _this._buildArrayBuffer(Float32Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  76115. break;
  76116. case GLTF2.EComponentType.UNSIGNED_BYTE:
  76117. data = _this._buildArrayBuffer(Uint8Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  76118. break;
  76119. case GLTF2.EComponentType.SHORT:
  76120. data = _this._buildArrayBuffer(Int16Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  76121. break;
  76122. case GLTF2.EComponentType.UNSIGNED_SHORT:
  76123. data = _this._buildArrayBuffer(Uint16Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  76124. break;
  76125. case GLTF2.EComponentType.UNSIGNED_INT:
  76126. data = _this._buildArrayBuffer(Uint32Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  76127. break;
  76128. case GLTF2.EComponentType.FLOAT:
  76129. data = _this._buildArrayBuffer(Float32Array, context, bufferViewData, accessor.byteOffset, accessor.count, numComponents, bufferView.byteStride);
  76130. break;
  76131. default:
  76132. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  76133. }
  76134. onSuccess(data);
  76135. });
  76136. };
  76137. GLTFLoader.prototype._getNumComponentsOfType = function (type) {
  76138. switch (type) {
  76139. case "SCALAR": return 1;
  76140. case "VEC2": return 2;
  76141. case "VEC3": return 3;
  76142. case "VEC4": return 4;
  76143. case "MAT2": return 4;
  76144. case "MAT3": return 9;
  76145. case "MAT4": return 16;
  76146. }
  76147. return 0;
  76148. };
  76149. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, context, data, byteOffset, count, numComponents, byteStride) {
  76150. try {
  76151. var byteOffset = data.byteOffset + (byteOffset || 0);
  76152. var targetLength = count * numComponents;
  76153. if (byteStride == null || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  76154. return new typedArray(data.buffer, byteOffset, targetLength);
  76155. }
  76156. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  76157. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  76158. var targetBuffer = new typedArray(targetLength);
  76159. var sourceIndex = 0;
  76160. var targetIndex = 0;
  76161. while (targetIndex < targetLength) {
  76162. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  76163. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  76164. targetIndex++;
  76165. }
  76166. sourceIndex += elementStride;
  76167. }
  76168. return targetBuffer;
  76169. }
  76170. catch (e) {
  76171. throw new Error(context + ": " + e);
  76172. }
  76173. };
  76174. GLTFLoader.prototype._addPendingData = function (data) {
  76175. if (!this._renderReady) {
  76176. this._renderPendingCount++;
  76177. }
  76178. this._addLoaderPendingData(data);
  76179. };
  76180. GLTFLoader.prototype._removePendingData = function (data) {
  76181. if (!this._renderReady) {
  76182. if (--this._renderPendingCount === 0) {
  76183. this._renderReady = true;
  76184. this._onRenderReady();
  76185. }
  76186. }
  76187. this._removeLoaderPendingData(data);
  76188. };
  76189. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  76190. this._loaderPendingCount++;
  76191. this._loaderTrackers.forEach(function (tracker) { return tracker._addPendingData(data); });
  76192. };
  76193. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  76194. this._loaderTrackers.forEach(function (tracker) { return tracker._removePendingData(data); });
  76195. if (--this._loaderPendingCount === 0) {
  76196. this._onComplete();
  76197. }
  76198. };
  76199. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  76200. var _this = this;
  76201. var tracker = new GLTFLoaderTracker(function () {
  76202. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker));
  76203. onComplete();
  76204. });
  76205. this._loaderTrackers.push(tracker);
  76206. this._addLoaderPendingData(tracker);
  76207. action();
  76208. this._removeLoaderPendingData(tracker);
  76209. };
  76210. GLTFLoader.prototype._getDefaultMaterial = function () {
  76211. if (!this._defaultMaterial) {
  76212. var id = "__gltf_default";
  76213. var material = this._babylonScene.getMaterialByName(id);
  76214. if (!material) {
  76215. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  76216. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  76217. material.metallic = 1;
  76218. material.roughness = 1;
  76219. }
  76220. this._defaultMaterial = material;
  76221. }
  76222. return this._defaultMaterial;
  76223. };
  76224. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  76225. var babylonMaterial = material.babylonMaterial;
  76226. // Ensure metallic workflow
  76227. babylonMaterial.metallic = 1;
  76228. babylonMaterial.roughness = 1;
  76229. var properties = material.pbrMetallicRoughness;
  76230. if (!properties) {
  76231. return;
  76232. }
  76233. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  76234. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  76235. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  76236. if (properties.baseColorTexture) {
  76237. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, properties.baseColorTexture.index);
  76238. if (!texture) {
  76239. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  76240. }
  76241. babylonMaterial.albedoTexture = this._loadTexture("textures[" + texture.index + "]", texture, properties.baseColorTexture.texCoord);
  76242. }
  76243. if (properties.metallicRoughnessTexture) {
  76244. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, properties.metallicRoughnessTexture.index);
  76245. if (!texture) {
  76246. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  76247. }
  76248. babylonMaterial.metallicTexture = this._loadTexture("textures[" + texture.index + "]", texture, properties.metallicRoughnessTexture.texCoord);
  76249. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  76250. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  76251. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  76252. }
  76253. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  76254. };
  76255. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  76256. if (material.babylonMaterial) {
  76257. assign(material.babylonMaterial, false);
  76258. return;
  76259. }
  76260. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  76261. return;
  76262. }
  76263. this._createPbrMaterial(material);
  76264. this._loadMaterialBaseProperties(context, material);
  76265. this._loadMaterialMetallicRoughnessProperties(context, material);
  76266. assign(material.babylonMaterial, true);
  76267. };
  76268. GLTFLoader.prototype._createPbrMaterial = function (material) {
  76269. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  76270. babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  76271. material.babylonMaterial = babylonMaterial;
  76272. };
  76273. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  76274. var babylonMaterial = material.babylonMaterial;
  76275. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  76276. if (material.doubleSided) {
  76277. babylonMaterial.backFaceCulling = false;
  76278. babylonMaterial.twoSidedLighting = true;
  76279. }
  76280. if (material.normalTexture) {
  76281. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.normalTexture.index);
  76282. if (!texture) {
  76283. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  76284. }
  76285. babylonMaterial.bumpTexture = this._loadTexture("textures[" + texture.index + "]", texture, material.normalTexture.texCoord);
  76286. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  76287. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  76288. if (material.normalTexture.scale != null) {
  76289. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  76290. }
  76291. }
  76292. if (material.occlusionTexture) {
  76293. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.occlusionTexture.index);
  76294. if (!texture) {
  76295. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  76296. }
  76297. babylonMaterial.ambientTexture = this._loadTexture("textures[" + texture.index + "]", texture, material.occlusionTexture.texCoord);
  76298. babylonMaterial.useAmbientInGrayScale = true;
  76299. if (material.occlusionTexture.strength != null) {
  76300. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  76301. }
  76302. }
  76303. if (material.emissiveTexture) {
  76304. var texture = GLTF2.GLTFUtils.GetArrayItem(this._gltf.textures, material.emissiveTexture.index);
  76305. if (!texture) {
  76306. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  76307. }
  76308. babylonMaterial.emissiveTexture = this._loadTexture("textures[" + texture.index + "]", texture, material.emissiveTexture.texCoord);
  76309. }
  76310. };
  76311. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  76312. var babylonMaterial = material.babylonMaterial;
  76313. var alphaMode = material.alphaMode || "OPAQUE";
  76314. switch (alphaMode) {
  76315. case "OPAQUE":
  76316. // default is opaque
  76317. break;
  76318. case "MASK":
  76319. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  76320. if (colorFactor) {
  76321. if (colorFactor[3] == 0) {
  76322. babylonMaterial.alphaCutOff = 1;
  76323. }
  76324. else {
  76325. babylonMaterial.alphaCutOff /= colorFactor[3];
  76326. }
  76327. }
  76328. if (babylonMaterial.albedoTexture) {
  76329. babylonMaterial.albedoTexture.hasAlpha = true;
  76330. }
  76331. break;
  76332. case "BLEND":
  76333. if (colorFactor) {
  76334. babylonMaterial.alpha = colorFactor[3];
  76335. }
  76336. if (babylonMaterial.albedoTexture) {
  76337. babylonMaterial.albedoTexture.hasAlpha = true;
  76338. babylonMaterial.useAlphaFromAlbedoTexture = true;
  76339. }
  76340. break;
  76341. default:
  76342. throw new Error(context + ": Invalid alpha mode '" + material.alphaMode + "'");
  76343. }
  76344. };
  76345. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  76346. var _this = this;
  76347. var sampler = (texture.sampler == null ? {} : GLTF2.GLTFUtils.GetArrayItem(this._gltf.samplers, texture.sampler));
  76348. if (!sampler) {
  76349. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  76350. }
  76351. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  76352. var samplingMode = GLTF2.GLTFUtils.GetTextureSamplingMode(sampler.magFilter, sampler.minFilter);
  76353. this._addPendingData(texture);
  76354. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, noMipMaps, false, samplingMode, function () {
  76355. _this._tryCatchOnError(function () {
  76356. _this._removePendingData(texture);
  76357. });
  76358. }, function (message) {
  76359. _this._tryCatchOnError(function () {
  76360. throw new Error(context + ": " + message);
  76361. });
  76362. });
  76363. if (texture.url) {
  76364. babylonTexture.updateURL(texture.url);
  76365. }
  76366. else if (texture.dataReadyObservable) {
  76367. texture.dataReadyObservable.add(function (texture) {
  76368. babylonTexture.updateURL(texture.url);
  76369. });
  76370. }
  76371. else {
  76372. texture.dataReadyObservable = new BABYLON.Observable();
  76373. texture.dataReadyObservable.add(function (texture) {
  76374. babylonTexture.updateURL(texture.url);
  76375. });
  76376. var image = GLTF2.GLTFUtils.GetArrayItem(this._gltf.images, texture.source);
  76377. if (!image) {
  76378. throw new Error(context + ": Failed to find source " + texture.source);
  76379. }
  76380. this._loadImage("images[" + image.index + "]", image, function (data) {
  76381. texture.url = URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  76382. texture.dataReadyObservable.notifyObservers(texture);
  76383. });
  76384. }
  76385. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  76386. babylonTexture.wrapU = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapS);
  76387. babylonTexture.wrapV = GLTF2.GLTFUtils.GetTextureWrapMode(sampler.wrapT);
  76388. babylonTexture.name = texture.name || "texture" + texture.index;
  76389. if (this._parent.onTextureLoaded) {
  76390. this._parent.onTextureLoaded(babylonTexture);
  76391. }
  76392. return babylonTexture;
  76393. };
  76394. GLTFLoader.prototype._loadImage = function (context, image, onSuccess) {
  76395. var _this = this;
  76396. if (image.uri) {
  76397. if (!GLTF2.GLTFUtils.ValidateUri(image.uri)) {
  76398. throw new Error(context + ": Uri '" + image.uri + "' is invalid");
  76399. }
  76400. if (GLTF2.GLTFUtils.IsBase64(image.uri)) {
  76401. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(image.uri)));
  76402. }
  76403. else {
  76404. BABYLON.Tools.LoadFile(this._rootUrl + image.uri, function (data) {
  76405. _this._tryCatchOnError(function () {
  76406. onSuccess(data);
  76407. });
  76408. }, function (event) {
  76409. _this._tryCatchOnError(function () {
  76410. _this._onProgress(event);
  76411. });
  76412. }, this._babylonScene.database, true, function (request) {
  76413. _this._tryCatchOnError(function () {
  76414. throw new Error(context + ": Failed to load '" + image.uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""));
  76415. });
  76416. });
  76417. }
  76418. }
  76419. else {
  76420. var bufferView = GLTF2.GLTFUtils.GetArrayItem(this._gltf.bufferViews, image.bufferView);
  76421. if (!bufferView) {
  76422. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  76423. }
  76424. this._loadBufferViewAsync("bufferViews[" + bufferView.index + "]", bufferView, onSuccess);
  76425. }
  76426. };
  76427. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  76428. try {
  76429. handler();
  76430. }
  76431. catch (e) {
  76432. this._onError(e.message);
  76433. }
  76434. };
  76435. GLTFLoader.Extensions = {};
  76436. return GLTFLoader;
  76437. }());
  76438. GLTF2.GLTFLoader = GLTFLoader;
  76439. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  76440. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  76441. })(BABYLON || (BABYLON = {}));
  76442. //# sourceMappingURL=babylon.glTFLoader.js.map
  76443. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  76444. var BABYLON;
  76445. (function (BABYLON) {
  76446. var GLTF2;
  76447. (function (GLTF2) {
  76448. /**
  76449. * Utils functions for GLTF
  76450. */
  76451. var GLTFUtils = (function () {
  76452. function GLTFUtils() {
  76453. }
  76454. /**
  76455. * If the uri is a base64 string
  76456. * @param uri: the uri to test
  76457. */
  76458. GLTFUtils.IsBase64 = function (uri) {
  76459. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  76460. };
  76461. /**
  76462. * Decode the base64 uri
  76463. * @param uri: the uri to decode
  76464. */
  76465. GLTFUtils.DecodeBase64 = function (uri) {
  76466. var decodedString = atob(uri.split(",")[1]);
  76467. var bufferLength = decodedString.length;
  76468. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  76469. for (var i = 0; i < bufferLength; i++) {
  76470. bufferView[i] = decodedString.charCodeAt(i);
  76471. }
  76472. return bufferView.buffer;
  76473. };
  76474. GLTFUtils.ForEach = function (view, func) {
  76475. for (var index = 0; index < view.length; index++) {
  76476. func(view[index], index);
  76477. }
  76478. };
  76479. GLTFUtils.ValidateUri = function (uri) {
  76480. return (uri.indexOf("..") === -1);
  76481. };
  76482. GLTFUtils.AssignIndices = function (array) {
  76483. if (array) {
  76484. for (var index = 0; index < array.length; index++) {
  76485. array[index].index = index;
  76486. }
  76487. }
  76488. };
  76489. GLTFUtils.GetArrayItem = function (array, index) {
  76490. if (!array || !array[index]) {
  76491. return null;
  76492. }
  76493. return array[index];
  76494. };
  76495. GLTFUtils.GetTextureWrapMode = function (mode) {
  76496. // Set defaults if undefined
  76497. mode = mode === undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  76498. switch (mode) {
  76499. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  76500. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  76501. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  76502. default:
  76503. BABYLON.Tools.Warn("Invalid texture wrap mode (" + mode + ")");
  76504. return BABYLON.Texture.WRAP_ADDRESSMODE;
  76505. }
  76506. };
  76507. GLTFUtils.GetTextureSamplingMode = function (magFilter, minFilter) {
  76508. // Set defaults if undefined
  76509. magFilter = magFilter === undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  76510. minFilter = minFilter === undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  76511. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  76512. switch (minFilter) {
  76513. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  76514. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  76515. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  76516. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  76517. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  76518. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  76519. default:
  76520. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  76521. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  76522. }
  76523. }
  76524. else {
  76525. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  76526. BABYLON.Tools.Warn("Invalid texture magnification filter (" + magFilter + ")");
  76527. }
  76528. switch (minFilter) {
  76529. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  76530. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  76531. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  76532. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  76533. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  76534. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  76535. default:
  76536. BABYLON.Tools.Warn("Invalid texture minification filter (" + minFilter + ")");
  76537. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  76538. }
  76539. }
  76540. };
  76541. /**
  76542. * Decodes a buffer view into a string
  76543. * @param view: the buffer view
  76544. */
  76545. GLTFUtils.DecodeBufferToText = function (view) {
  76546. var result = "";
  76547. var length = view.byteLength;
  76548. for (var i = 0; i < length; ++i) {
  76549. result += String.fromCharCode(view[i]);
  76550. }
  76551. return result;
  76552. };
  76553. return GLTFUtils;
  76554. }());
  76555. GLTF2.GLTFUtils = GLTFUtils;
  76556. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  76557. })(BABYLON || (BABYLON = {}));
  76558. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  76559. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  76560. var BABYLON;
  76561. (function (BABYLON) {
  76562. var GLTF2;
  76563. (function (GLTF2) {
  76564. var GLTFLoaderExtension = (function () {
  76565. function GLTFLoaderExtension() {
  76566. this.enabled = true;
  76567. }
  76568. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  76569. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  76570. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  76571. GLTFLoaderExtension.prototype._loadExtension = function (property, action) {
  76572. var _this = this;
  76573. if (!property.extensions) {
  76574. return false;
  76575. }
  76576. var extension = property.extensions[this.name];
  76577. if (!extension) {
  76578. return false;
  76579. }
  76580. // Clear out the extension before executing the action to avoid recursing into the same property.
  76581. property.extensions[this.name] = undefined;
  76582. action(extension, function () {
  76583. // Restore the extension after completing the action.
  76584. property.extensions[_this.name] = extension;
  76585. });
  76586. return true;
  76587. };
  76588. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  76589. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  76590. };
  76591. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  76592. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  76593. };
  76594. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  76595. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  76596. };
  76597. GLTFLoaderExtension._ApplyExtensions = function (action) {
  76598. var extensions = GLTFLoaderExtension._Extensions;
  76599. if (!extensions) {
  76600. return;
  76601. }
  76602. for (var i = 0; i < extensions.length; i++) {
  76603. var extension = extensions[i];
  76604. if (extension.enabled && action(extension)) {
  76605. return true;
  76606. }
  76607. }
  76608. return false;
  76609. };
  76610. //
  76611. // Utilities
  76612. //
  76613. GLTFLoaderExtension._Extensions = [];
  76614. return GLTFLoaderExtension;
  76615. }());
  76616. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  76617. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  76618. })(BABYLON || (BABYLON = {}));
  76619. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  76620. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  76621. var BABYLON;
  76622. (function (BABYLON) {
  76623. var GLTF2;
  76624. (function (GLTF2) {
  76625. var Extensions;
  76626. (function (Extensions) {
  76627. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  76628. var MSFTLOD = (function (_super) {
  76629. __extends(MSFTLOD, _super);
  76630. function MSFTLOD() {
  76631. return _super !== null && _super.apply(this, arguments) || this;
  76632. }
  76633. Object.defineProperty(MSFTLOD.prototype, "name", {
  76634. get: function () {
  76635. return "MSFT_lod";
  76636. },
  76637. enumerable: true,
  76638. configurable: true
  76639. });
  76640. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  76641. return this._loadExtension(node, function (extension, onComplete) {
  76642. for (var i = extension.ids.length - 1; i >= 0; i--) {
  76643. var lodNode = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.nodes, extension.ids[i]);
  76644. if (!lodNode) {
  76645. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  76646. }
  76647. loader._traverseNode(context, lodNode, action, parentNode);
  76648. }
  76649. loader._traverseNode(context, node, action, parentNode);
  76650. onComplete();
  76651. });
  76652. };
  76653. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  76654. var _this = this;
  76655. return this._loadExtension(node, function (extension, onComplete) {
  76656. var nodes = [node.index].concat(extension.ids).map(function (index) { return loader._gltf.nodes[index]; });
  76657. loader._addLoaderPendingData(node);
  76658. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  76659. loader._removeLoaderPendingData(node);
  76660. onComplete();
  76661. });
  76662. });
  76663. };
  76664. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  76665. var _this = this;
  76666. loader._whenAction(function () {
  76667. loader._loadNode(context, nodes[index]);
  76668. }, function () {
  76669. if (index !== nodes.length - 1) {
  76670. var previousNode = nodes[index + 1];
  76671. previousNode.babylonMesh.setEnabled(false);
  76672. }
  76673. if (index === 0) {
  76674. onComplete();
  76675. return;
  76676. }
  76677. setTimeout(function () {
  76678. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  76679. }, MSFTLOD.MinimalLODDelay);
  76680. });
  76681. };
  76682. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  76683. var _this = this;
  76684. return this._loadExtension(material, function (extension, onComplete) {
  76685. var materials = [material.index].concat(extension.ids).map(function (index) { return loader._gltf.materials[index]; });
  76686. loader._addLoaderPendingData(material);
  76687. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  76688. material.extensions[_this.name] = extension;
  76689. loader._removeLoaderPendingData(material);
  76690. onComplete();
  76691. });
  76692. });
  76693. };
  76694. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  76695. var _this = this;
  76696. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  76697. assign(babylonMaterial, isNew);
  76698. if (index === 0) {
  76699. onComplete();
  76700. return;
  76701. }
  76702. // Load the next LOD when the loader is ready to render and
  76703. // all active material textures of the current LOD are loaded.
  76704. loader._executeWhenRenderReady(function () {
  76705. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  76706. setTimeout(function () {
  76707. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  76708. }, MSFTLOD.MinimalLODDelay);
  76709. });
  76710. });
  76711. });
  76712. };
  76713. /**
  76714. * Specify the minimal delay between LODs in ms (default = 250)
  76715. */
  76716. MSFTLOD.MinimalLODDelay = 250;
  76717. return MSFTLOD;
  76718. }(GLTF2.GLTFLoaderExtension));
  76719. Extensions.MSFTLOD = MSFTLOD;
  76720. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  76721. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  76722. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  76723. })(BABYLON || (BABYLON = {}));
  76724. //# sourceMappingURL=MSFT_lod.js.map
  76725. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  76726. var BABYLON;
  76727. (function (BABYLON) {
  76728. var GLTF2;
  76729. (function (GLTF2) {
  76730. var Extensions;
  76731. (function (Extensions) {
  76732. var KHRMaterialsPbrSpecularGlossiness = (function (_super) {
  76733. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  76734. function KHRMaterialsPbrSpecularGlossiness() {
  76735. return _super !== null && _super.apply(this, arguments) || this;
  76736. }
  76737. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  76738. get: function () {
  76739. return "KHR_materials_pbrSpecularGlossiness";
  76740. },
  76741. enumerable: true,
  76742. configurable: true
  76743. });
  76744. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  76745. var _this = this;
  76746. return this._loadExtension(material, function (extension, onComplete) {
  76747. loader._createPbrMaterial(material);
  76748. loader._loadMaterialBaseProperties(context, material);
  76749. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  76750. assign(material.babylonMaterial, true);
  76751. });
  76752. };
  76753. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  76754. var babylonMaterial = material.babylonMaterial;
  76755. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  76756. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  76757. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  76758. if (properties.diffuseTexture) {
  76759. var texture = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.textures, properties.diffuseTexture.index);
  76760. if (!texture) {
  76761. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  76762. }
  76763. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  76764. }
  76765. if (properties.specularGlossinessTexture) {
  76766. var texture = GLTF2.GLTFUtils.GetArrayItem(loader._gltf.textures, properties.specularGlossinessTexture.index);
  76767. if (!texture) {
  76768. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  76769. }
  76770. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  76771. babylonMaterial.reflectivityTexture.hasAlpha = true;
  76772. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  76773. }
  76774. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  76775. };
  76776. return KHRMaterialsPbrSpecularGlossiness;
  76777. }(GLTF2.GLTFLoaderExtension));
  76778. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  76779. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  76780. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  76781. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  76782. })(BABYLON || (BABYLON = {}));
  76783. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  76784. (function universalModuleDefinition(root, factory) {
  76785. if (root && root["BABYLON"]) {
  76786. return;
  76787. }
  76788. if(typeof exports === 'object' && typeof module === 'object')
  76789. module.exports = factory();
  76790. else if(typeof define === 'function' && define.amd)
  76791. define([], factory);
  76792. else if(typeof exports === 'object')
  76793. exports["BABYLON"] = factory();
  76794. else {
  76795. root["BABYLON"] = factory();
  76796. }
  76797. })(this, function() {
  76798. return BABYLON;
  76799. });